• Spring Security 注解


    需求缘起

           在之前的章节中我们介绍过通过注解的方式进行权限的控制了,这里再详细的讲解下方法级安全的几个注解。

    一、注解式方法级安全开启

           需要在WebSecuirtyConfig添加配置:

    @Configuration
    @EnableWebSecurity //启用Spring Security.

    ////会拦截注解了@PreAuthrize注解的配置.
    @EnableGlobalMethodSecurity(prePostEnabled=true)
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter{

    }

    二、允许的注解

           这里主要@PreAuthorize, @PostAuthorize, @Secured这三个注解可以使用。

    2.1 @Secured

           当@EnableGlobalMethodSecurity(securedEnabled=true)的时候,@Secured可以使用:

    @GetMapping("/helloUser")
    @Secured({"ROLE_normal","ROLE_admin"})
    public String helloUser() {
        return "hello,user";
    }

    说明:拥有normal或者admin角色的用户都可以方法helloUser()方法。另外需要注意的是这里匹配的字符串需要添加前缀“ROLE_“

           如果我们要求,只有同时拥有admin & noremal的用户才能方法helloUser()方法,这时候@Secured就无能为力了。

    2.2 @PreAuthorize

           Spring的 @PreAuthorize/@PostAuthorize 注解更适合方法级的安全,也支持Spring 表达式语言,提供了基于表达式的访问控制。

           当@EnableGlobalMethodSecurity(prePostEnabled=true)的时候,@PreAuthorize可以使用:

    @GetMapping("/helloUser")
    @PreAuthorize("hasAnyRole('normal','admin')")
    public String helloUser() {
        return "hello,user";
    }

    说明:拥有normal或者admin角色的用户都可以方法helloUser()方法。

           此时如果我们要求用户必须同时拥有normal和admin的话,那么可以这么编码:

    @GetMapping("/helloUser")
    @PreAuthorize("hasRole('normal') AND hasRole('admin')"
    public String helloUser() {
        return "hello,user";
    }

           此时如果使用user/123登录的话,就无法访问helloUser()的方法了。

    2.3 @PostAuthorize

           @PostAuthorize 注解使用并不多,在方法执行后再进行权限验证,适合验证带有返回值的权限,Spring EL 提供 返回对象能够在表达式语言中获取返回的对象returnObject。

    当@EnableGlobalMethodSecurity(prePostEnabled=true)的时候,@PostAuthorize可以使用:

    @GetMapping("/helloUser")
    @PostAuthorize(" returnObject!=null &&  returnObject.username == authentication.name")
    public User helloUser() {
            Object pricipal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            User user;
            if("anonymousUser".equals(pricipal)) {
                user = null;
            }else {
                user = (User) pricipal;
            }
            return user;
    }

           这三个最常用也就是@PreAuthorize这个注解了,在使用中主要是配合Spring EL表达式。

  • 相关阅读:
    mysql__视图
    mysql__索引的设计和使用
    mysql————表类型(存储引擎)的选择
    mysql 常用函数
    mysql中的运算符
    HTML5 API详解(1):fullscreen全屏模式
    深入了解 Flexbox 伸缩盒模型
    BAT及各大互联网公司2014前端笔试面试题--Html,Css篇
    js运动动画
    原创:自定义三叉树
  • 原文地址:https://www.cnblogs.com/LoveShare/p/12666680.html
Copyright © 2020-2023  润新知