基于角色得后台权限管理系统设计(七、spring security 之请求鉴权(详解)

讲了这么多篇幅,现在开始讲大家最关心得问题,那么当认证通过后,过滤器走完了之后,怎么拦截用户得请求呢?网络上应该可以搜索到大量得  这种方式得拦截,但是我们总不能预先知道有什么角色什么权限都去改这里得代码吧,这点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进行转换了。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值