Spring Security使用强大的Spring Expression Language(SpEL)提供各种各样的表达式。大多数这些Security表达式是针对上下文对象(当前经过身份验证的主体)进行工作的.

这些表达式的评估由SecurityExpressionRoot执行 – 它提供了Web安全性和方法级安全性的基础。

Spring Security 3.0中引入了使用SpEL表达式作为授权机制的能力,并在Spring Security 4.x中继续使用,有关Spring Security中表达式的完整列表,请查看本指南

Spring Security提供两种类型的Web授权 – 基于URL保护整页,并根据安全规则有条件地显示JSP页面的各个部分

通过为http元素启用表达式,可以按如下方式保护URL模式:

  1. <http use-expressions = "true">
  2. <intercept-url pattern="/admin/**" access="hasRole('ROLE_ADMIN')" />
  3. ...
  4. </http>
  1. @Configuration
  2. @EnableWebSecurity
  3. public class SecSecurityConfig extends WebSecurityConfigurerAdapter {
  4. @Override
  5. protected void configure(HttpSecurity http) throws Exception {
  6. http
  7. .authorizeRequests()
  8. .antMatchers("/admin/**").hasRole("ADMIN");
  9. }
  10. ...
  11. }

Spring Security会自动为任何角色添加前缀ROLE_

此处使用hasRole表达式来检查当前经过身份验证的主体是否具有指定的权限。

第二种Web授权基于对Security表达式的评估有条件地显示JSP页面的某些部分

让我们在pom.xml中为Spring Security JSP taglib支持添加所需的依赖项:

  1. <dependency>
  2. <groupId>org.springframework.security</groupId>
  3. <artifactId>spring-security-taglibs</artifactId>
  4. <version>5.0.5.RELEASE</version>
  5. </dependency>

必须在页面上启用taglib支持才能使用Security命名空间:

  1. <%@ taglib prefix="security"
  2. uri="http://www.springframework.org/security/tags" %>

现在可以在页面上使用hasRole表达式,当页面渲染时,基于经过身份验证的人显示/隐藏HTML元素.

  1. <security:authorize access="hasRole('ROLE_USER')">
  2. This text is only visible to a user
  3. <br/>
  4. </security:authorize>
  5. <security:authorize access="hasRole('ROLE_ADMIN')">
  6. This text is only visible to an admin
  7. <br/>
  8. </security:authorize>

通过使用注释,Security表达式还可用于在方法级别保护业务功能

释@PreAuthorize和@PostAuthorize(以及@PreFilter和@PostFilter)支持Spring Expression Language(SpEL)并提供基于表达式的访问控制。

首先,为了使用方法级安全性,我们需要使用@EnableGlobalMethodSecurity在安全性配置中启用它

  1. @Configuration
  2. @EnableWebSecurity
  3. @EnableGlobalMethodSecurity(prePostEnabled = true)
  4. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  5. ...
  6. }

等效的XML配置:

  1. <global-method-security pre-post-annotations="enabled" />

然后,我们可以使用Spring @PreAuthorize注释来保护方法:

  1. @Service
  2. public class FooService {
  3. @PreAuthorize("hasRole('ROLE_ADMIN')")
  4. public List<Foo> findAll() { ... }
  5. ...
  6. }

现在,只有具有ADMIN角色的用户才能成功调用findAll方法。

请注意,Pre和Post注释是通过代理进行评估和强制执行的 – 如果使用CGLIB代理,则不能将类和公共方法声明为final

如果请求对象可用,还可以在原始Java代码中以编程方式检查用户权限:

  1. @RequestMapping
  2. public void someControllerMethod(HttpServletRequest request) {
  3. request.isUserInRole("someAuthority");
  4. }

当然,不访问请求,也可以简单的手动校验有特殊权限的已认证通过的用户。可以通过各种方式从Spring Security上下文中获取用户。

本教程简要介绍了一般使用Spring Security Expressions,特别是hasRole表达式 – 快速介绍如何保护应用程序的各个部分。

有关Web授权示例,请查看此Github简单教程。方法级安全性示例也在GitHub

版权声明:本文为xjknight原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/xjknight/p/10887791.html