Spring Security 访问控制的方式

如果对该文章感兴趣欢迎关注我的小博客 Forest,我会分享更多学习时遇到的知识 (●’◡’●)

授权管理

anyRequest

看名字就知道,这个表示所有的请求。但是这个 anyRequest 有个坑点,不能配置 anyRequestantMatchers 前面,一般这个 anyRequest 是放在放行规则的最后面

http
        // 验证策略
        .authorizeRequests()
        // 放行登录
        .antMatchers(HttpMethod.POST, "/doLogin").permitAll()
        .antMatchers(HttpMethod.POST, "/error").permitAll()
        .antMatchers(HttpMethod.POST, "/doLogout").permitAll()
        .anyRequest().authenticated()

antMatchers

这个 antMatchers 用于匹配请求,可以使用 ant 语法,匹配路径可以使用 * 来匹配

http
        // 验证策略
        .authorizeRequests()
        // 可以用来放行静态资源
        .antMatchers("/css/**","/js/**","/images/**").permitAll()
        .antMatchers(HttpMethod.POST, "/doLogin").permitAll()
        // 也可以放行所有目录下的 png 图片
        .antMatchers("/**/*.png").permitAll()
        .anyRequest().authenticated()

上面的匹配也可以只匹配特定类型(不写默认匹配所有类型的请求),使用 HttpMethod 这个枚举

public enum HttpMethod {
	GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE;
    ...

regexMatchers

除了向上面那个使用 ant 语法进行匹配的 antMatchers 也有直接使用正则表达式进行匹配的 regexMatchers

http
        // 验证策略
        .authorizeRequests()
        // 放行所有目录下的 png 图片
        .regexMatchers(".+[.]png").permitAll()
        .anyRequest().authenticated()

内置控制访问方法

表达式备注
hasRole用户具备某个角色即可访问资源
hasAnyRole用户具备多个角色中的任意一个即可访问资源
hasAuthority类似于 hasRole
hasAnyAuthority类似于 hasAnyRole
permitAll统统允许访问
denyAll统统拒绝访问
isAnonymous判断是否匿名用户
isAuthenticated判断是否认证成功
isRememberMe判断是否通过记住我登录的
isFullyAuthenticated判断是否用户名/密码登录的
principle当前用户
authentication从 SecurityContext 中提取出来的用户对象

基于权限访问

例如配置一个请求只有 admin 才能访问

http
        .authorizeRequests()
        .antMatchers(HttpMethod.POST, "/doLogin").permitAll()
        // 注意这个 hasAuthority 对大小写有严格要求
        .antMatchers("/hello").hasAuthority("admin")
        // 或者使用这个 hasAnyAuthority,表示 "admin","temp" 任意一个都可以
        .antMatchers("/hello").hasAnyAuthority("admin","temp")
        .anyRequest().authenticated();

基于角色访问

先修改下 UserDetailServiceImpl 的返回值,使其添加角色

// 在这个 commaSeparatedStringToAuthorityList 后面直接加上以 ROLE 开头的角色(必须是这个,且是大写)
return new User(username, password, AuthorityUtils
                // 例如这里就创建了 admin 和 abc 这两个角色
                .commaSeparatedStringToAuthorityList("admin,normal,ROLE_admin,ROLE_abc"));

然后就可以基于角色访问了

http
        .authorizeRequests()
        .antMatchers(HttpMethod.POST, "/doLogin").permitAll()
        // 这个 hasRole 也区分大小写
        // 这里就不用写 ROLE 了,这里需要 abc 这个角色
        .antMatchers("/hello").hasRole("abc")
        .anyRequest().authenticated();

基于 IP 地址

例如服务器内部访问时这个基于 IP 地址就很有用了,防止外部调用某个服务(Spring Cloud)

// 可以在 Request 获取远程地址
log.info(request.getRemoteAddr());

例如这里只允许 127.0.0.1 访问

http
        .authorizeRequests()
        .antMatchers(HttpMethod.POST, "/doLogin").permitAll()
        // 注意这个 hasRole 对大小写有严格要求
        .antMatchers("/hello").hasIpAddress("127.0.0.1")
        .anyRequest().authenticated();

GrantedAuthority

参考资料 【详解】Spring Security的GrantedAuthority(已授予的权限)

之前编写 UserDetails 时,里面是有一个集合专门来存储 GrantedAuthority 对象的(UserDeitails 接口里面有一个getAuthorities() 方法。这个方法将返回此用户的所拥有的权限。这个集合将用于用户的访问控制,也就是 Authorization

// 如下,添加两个权限
return new User(username, password, AuthorityUtils
        .commaSeparatedStringToAuthorityList("admin,normal"));

所谓权限,就是一个字符串。一般不会重复。
而所谓权限检查,就是查看用户权限列表中是否含有匹配的字符串。

public interface GrantedAuthority extends Serializable {
    String getAuthority();
}

在 Security 提供的 UserDetailsService 默认实现中,角色和权限都存储在 authorities 表中

Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();

GrantedAuthority 接口的默认实现类 SimpleGrantedAuthority 其实就只是用来比对字符串是否匹配

public final class SimpleGrantedAuthority implements GrantedAuthority {
    private static final long serialVersionUID = 500L;
    private final String role;
 
    public SimpleGrantedAuthority(String role) {
        Assert.hasText(role, "A granted authority textual representation is required");
        this.role = role;
    }
 
    public String getAuthority() {
        return this.role;
    }
 
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        } else {
            return obj instanceof SimpleGrantedAuthority ? this.role.equals(((SimpleGrantedAuthority)obj).role) : false;
        }
    }
 
    public int hashCode() {
        return this.role.hashCode();
    }
 
    public String toString() {
        return this.role;
    }
}

access 方法

参考文档 常见的内置表达式
参考资料 Spring Security 基于表达式的权限控制

实际上,内置的访问控制方法都是基于这个 access() 方法进行的封装,这个 access() 传入一个 SpringEL 表达式来控制授权(什么是 SpringEl 参考 Spring03 笔记)

hasRole("abc")
// 等价
access("hasRole('abc')")

// 除了像上面那样调用一个内置的方法,也可以使用 SpEL 来编写逻辑语句
config.antMatchers("/person/*").access("hasRole('ADMIN') or hasRole('USER')")
                // 在Web安全表达式中引用bean
                .antMatchers("/person/{id}").access("@myServiceImpl.checkUserId(authentication,#id)")
                .anyRequest().access("@myServiceImpl.hasPermission(request,authentication)");

如下可见,实际上 permitAllhasAuthorityhasAnyRole 方法都是基于这个 access 方法的二次封装

public ExpressionInterceptUrlRegistry permitAll() {
	return access(permitAll);
}

public ExpressionInterceptUrlRegistry hasAuthority(String authority) {
	return access(ExpressionUrlAuthorizationConfigurer.hasAuthority(authority));
}

public ExpressionInterceptUrlRegistry hasAnyRole(String... roles) {
	return access(ExpressionUrlAuthorizationConfigurer.hasAnyRole(roles));
}

内置的访问控制方法

表达式描述
hasRole([role])用户拥有制定的角色时返回true (Spring security默认会带有ROLE_前缀),去除参考Remove the ROLE_
hasAnyRole([role1,role2])用户拥有任意一个制定的角色时返回true
hasAuthority([authority])等同于hasRole,但不会带有ROLE_前缀
hasAnyAuthority([auth1,auth2])等同于hasAnyRole
permitAll永远返回true
denyAll永远返回false
anonymous当前用户是anonymous时返回true
rememberMe当前勇士是rememberMe用户返回true
authentication当前登录用户的authentication对象
fullAuthenticated当前用户既不是anonymous也不是rememberMe用户时返回true
hasIpAddress(‘192.168.1.0/24’)请求发送的IP匹配时返回true

自定义 access

先创建一个接口

public interface MyService {
    boolean hasPermission(HttpServletRequest request, Authentication authentication);
}

然后创建实现类

@Service
@Slf4j
public class MyServiceImpl implements MyService {
    @Override
    public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
        // 获取主体
        Object principal = authentication.getPrincipal();
        log.info(request.getRequestURI());
        // 判断主体是否属于 UserDetails
        if (principal instanceof UserDetails) {
            UserDetails userDetails = (UserDetails) principal;
            // 获取权限列表
            Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();
            // 判断请求的 URI 是否在权限里(这个还是需要在 UserDetails 里的返回值 User 加上需要访问的路径)
            return authorities.contains(new SimpleGrantedAuthority(request.getRequestURI()));
        }
        return false;
    }
}

UserDetails 里的返回值加上这个访问权限

return new User(username, password, AuthorityUtils
// 这里的 /hello 不要想太多,不加 ROLE 的单纯就只是一个用来匹配的字符串
                .commaSeparatedStringToAuthorityList("admin,normal,ROLE_admin,ROLE_abc,/hello"));

最后在 access 里调用这个 Bean

http
        .authorizeRequests()
        .antMatchers(HttpMethod.POST, "/doLogin").permitAll()
        // 使用自定义的 access 方法
        .anyRequest().access("@myServiceImpl.hasPermission(request,authentication)");

基于注解的访问控制

参考资料 Spring Security 注解

首先在启动类上加 @EnableGlobalMethodSecurity 注解开启 Security 注解支持

因为默认 @EnableGlobalMethodSecurity 的注解都是单独设置的且全部为 false,所以需要手动开启

@SpringBootApplication
@ServletComponentScan
@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true)
public class SecurityApplication {

    public static void main(String[] args) {
        SpringApplication.run(SecurityApplication.class, args);
    }

}

常用的注解(下面的三个注解都可以写在类或方法上)

@Secured 用来控制一个方法是否能被访问(只验证 Authority,如果要验证 ROLE 需要手动加上 ROLE_

@PreAuthorize 更精确的控制是否能被访问

@PostAuthorize 在方法执行后再进行权限验证,在方法调用完成后检查权限决定是否抛出 AccessDeniedException 异常

注:这些注解一般写在 Controller 上(也可以写在 Service 接口或者方法上,但是一般都是 Controller 上,控制 URL 是否允许被访问)

@Secured

这个用来验证角色的

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

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

@PreAuthorize

其实这个就是上面的 access 方法

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


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

@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;
}
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Security 是一个功能强大的安全框架,提供了一系列的安全功能,其中包括权限控制。 Spring Security 的权限控制主要通过以下几个步骤来实现: 1. 配置安全策略 在 Spring Security 中,可以通过配置安全策略来定义哪些资源需要被保护,以及如何进行保护。安全策略可以通过 XML 配置文件、Java 配置类或注解来定义。 2. 定义用户和角色 在 Spring Security 中,可以通过配置用户和角色来实现权限控制。用户可以被分配到一个或多个角色,每个角色可以被授予一组权限。用户登录时,Spring Security 将会验证用户的凭证,并根据用户所拥有的角色和权限来判断用户是否有权访问某个资源。 3. 配置访问控制Spring Security 中,可以通过配置访问控制来限制用户对某些资源的访问。访问控制可以通过 URL、HTTP 方法、IP 地址等方式进行定义。访问控制可以通过 XML 配置文件、Java 配置类或注解来定义。 4. 实现自定义访问控制 如果默认的访问控制不符合需求,可以通过实现自定义访问控制来扩展 Spring Security 的权限控制机制。自定义访问控制可以通过实现 AccessDecisionVoter 接口或 AccessDecisionManager 接口来实现。 总之,Spring Security 的权限控制是通过配置安全策略、定义用户和角色、配置访问控制和实现自定义访问控制等步骤来实现的。通过这些步骤,可以实现对应用程序中的各种资源的保护和控制,确保只有授权的用户才能访问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值