讲了这么多篇幅,现在开始讲大家最关心得问题,那么当认证通过后,过滤器走完了之后,怎么拦截用户得请求呢?网络上应该可以搜索到大量得 这种方式得拦截,但是我们总不能预先知道有什么角色什么权限都去改这里得代码吧,这点security 当然也考虑得很周全。这种方式只能配置一些固定得权限。
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.mvcMatchers("/data/*").hasRole("ADMIN")
.mvcMatchers("/admin/*").hasRole("ADMIN")
.mvcMatchers("/user/*").hasRole("USER")
.anyRequest()
.authenticated()
;
//注意认证失败处理在这里配置
http.formLogin().failureHandler(authenticationFailureHandler).permitAll();
//权限校验失败处理在这配置
http.exceptionHandling()
.accessDeniedHandler(accessDeniedHandler);
}
下面进入正文:
security提供了几个注解
1、@Secured
2、@PreAuthorize
3、@PostAuthorize
以上三个注解需搭配@EnableGlobalMethodSecurity(...)注解使用
我们可以看下这个注解下面有什么不难发现这里面得值都是false,想要使用什么就设置为true就行了。
@PreAuthorize、@PostAuthorize这两个注解 设置@EnableGlobalMethodSecurity(prePostEnabled=true)。
@Secured 这个注解设置@EnableGlobalMethodSecurity(securedEnabled=true)。
public @interface EnableGlobalMethodSecurity {
boolean prePostEnabled() default false;
boolean securedEnabled() default false;
boolean jsr250Enabled() default false;
boolean proxyTargetClass() default false;
AdviceMode mode() default AdviceMode.PROXY;
int order() default 2147483647;
}
这样以后只需要在你得方法上注解上相关得权限即可,如下:
@RequestMapping(value = "/user/getUser",method = RequestMethod.GET)
@PreAuthorize("hasAuthority('user:getUser')")
public Result getUser(){
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
JSONObject jsonObject=new JSONObject();
jsonObject.put("authentication",authentication);
return Result.success(jsonObject);
}
强烈推荐与url相关得写法,类似下面这种,这样就可以把权限细粒度得控制到url上。如果是多系统权限集中管理得 还可以在上系统唯一标识。这样在后台配置权限时只需要配置url就行了,这个权限入库就可以直接根据url进行转换了。