开发者学堂课程【Spring Security知识精讲与实战演示(三):集中式整合之授权操作】学习笔记与课程紧密联系,让用户快速学习知识
课程地址:https://developer.aliyun.com/learning/course/732/detail/13065
集中式整合之授权操作
内容介绍:
一、动态权限的控制
二、异常拦截性的配置
三、测试
一、动态权限的控制
授权跟以前没有跟做整合的时候是一样的,不一样是开启授权的这个操作需要加在这个配置类,而不是之前的配置文件。里面的global method security的配置是一样的。
同样有三个方式:
spring的表达式的方式,spring security内部制定的方式和jsr250。
*Determines if Spring Security's pre post annotations should be enabled. Default is* false.
*return true if pre post annotations should be enabled false otherwise.*/
boolean prePostEnabled() default false;
* Determines if Spring Security's (@link Secured) annotations should be enabled. *ceturn true if (@link Secured)annotations should be enabled false otherwise.* Default is false.
*/
boolean securedEnabled() default false;
/**
* Determines if JSR-250annotations should be enabled. Default is false.
*return true if JSR-250 should be enabled false otherwise.
*/
boolean jsr250Enabled() default false;
这三种方式是一样的效果,只是方法不一样。选择其中一种,将其改成true,即:enable global method security(secure enable = true)
这是spring security内置的一种方式来开启方法级的动态授权。
接下来找到处理器,在类上或者方法上都可以加上一个security,写上一个ROLE_PRODUCT,需要一个role_product的角色。
package comitheima.controller;
import org.springframework.security.access.annotation. Secured; import org. springframework.stereotype. Controller;
import org. springframework.web.bind. annotation. RequestMapping;
@Controller
@RequestMapping("/product")
public class ProductController(
@Secured(”ROLB_PRODUC”)
@RequestMapping("/findA11")
public String findA11() (return "product-list";
]
重新启动之后,浏览器登陆之后,来到首页,点基础数据,点产品管理会跳转出403权限不足。证明动态授权已经控制住。
二、异常拦截性的配置
但是需要注意的是:不能让它跳转到这个页面,不美观了。让其跳转到自定义的页面,因此需要指定一个,在处理器里面取一个名字,在上面加上一个control advance的注解,可以对异常进行编写,可以是一个也可以是多个。
接着需要编写拦截的异常,但是此时权限的不足并不是runtime这么大的异常,因此做一个判断,如果e属于accessdeniedexception,重新导入第一个包。让spring security的异常跳转到403,其余跳转到500。可以根据具体情况来指定。此时异常的拦截性配置完成。
@ControllerAdvice
public class HandlerControllerException(
@ExceptionHandler(RuntimeException.class)
public
String
handException(RuntimeException
e)(
if(e
instanceof AccessDeniedException)(return"redirect:/403.jsp";
return "redirect:/500.jsp"
)
三、测试
重新启动后,再一次测试时,是否会再次来到403页面。重新访问后,认证之后,点击产品管理,会来到403自定义页面。