zoukankan      html  css  js  c++  java
  • 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表达式。

  • 相关阅读:
    scala 数据结构(七 ):集 Set
    scala 数据结构(六):映射 Map
    scala 数据结构(五):队列 Queue
    scala 数据结构(四):列表 List
    scala 数据结构(三):元组Tuple
    scala 数据结构(二):数组
    scala 数据结构(一):数据结构简介
    Scala 面向对象(十三):隐式转换和隐式参数
    vba报表制作
    Apache与Nginx
  • 原文地址:https://www.cnblogs.com/LoveShare/p/12666680.html
Copyright © 2011-2022 走看看