Spring Security 表单配置(三)
Spring Security 授权
- 实现授权接口
- 方法安全注解
实现授权接口
实现接口
org.springframework.security.authorization.AuthorizationManager
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.AuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.access.intercept.RequestAuthorizationContext;
import java.util.function.Supplier;
public class MyAuthorizationManager implements AuthorizationManager<RequestAuthorizationContext> {
@Override
public AuthorizationDecision check(Supplier<Authentication> authentication, RequestAuthorizationContext object) {
// ... 这里可以写授权逻辑
// 返回true表示有权限
return new AuthorizationDecision(true);
}
}
然后在配置中加入
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.formLogin(form -> {
form
.loginProcessingUrl("/login") // 接受登录请求的url,默认也是login
.loginPage("/toLogin") // 表单对应的url
.successForwardUrl("/success") // 登录成功后重定向的url
.failureForwardUrl("/failure") // 登录失败后重定向的url
;
})
.authorizeHttpRequests(authorize -> {
// 授权所有请求都得经过授权
authorize.anyRequest().access(new MyAuthorizationManager());
})
.csrf().disable(); // 简单粗暴禁用csrf
return http.build();
}
授权配置完成
方法安全注解
首先开启方法安全注解
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {
// ... 省略配置
}
方法安全注解常用的有两个
org.springframework.security.access.prepost.PreAuthorize
org.springframework.security.access.prepost.PostAuthorize
PreAuthorize 是访问前授权
PostAuthorize 是访问后授权
例子:
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import security.demo.DataEntity;
import java.util.UUID;
@RestController
@RequestMapping("/admin")
public class AdminController {
@GetMapping("/res/{id}")
@PreAuthorize("hasAnyRole('admin')")
public String getResById(@PathVariable("id") String id) {
return id;
}
@GetMapping("/res/{id}")
@PreAuthorize("hasAnyRole('admin')")
@PostAuthorize("returnObject.creator == authentication.name")
public DataEntity getDataEntityById(@PathVariable("id") String id) {
String creator = UUID.randomUUID().toString();
return DataEntity.builder().id(id).someData("一些数据").creator(creator).build();
}
}
其中的DataEntity是一个简单的pojo类
import lombok.Builder;
import lombok.Data;
@Data
@Builder
public class DataEntity {
private String id;
private String someData;
private String creator;
}
PreAuthorize 里面可以接收授权表达式,例子的意思是,当前用户要有admin角色
PostAuthorize 也接收授权表达式,例子里面的意思是,然后的实体类的creator属性必须是当前用户的username
更多的表达式可以参考官方文档: https://docs.spring.io/spring-security/reference/5.7/servlet/authorization/expression-based.html
官方文档里面有更多的注解和更多的使用方式