深入理解Spring Security授权机制原理
java1234
共 17361字,需浏览 35分钟
· 2021-05-11
点击上方蓝色字体,选择“标星公众号”
优质文章,第一时间送达
作者 | 朱季谦
来源 | urlify.cn/i2UJRn
1 @PostMapping("/test")
2 @Secured({WebResRole.ROLE_PEOPLE_W})
3 public void test(){
4 ......
5 return null;
6 }
1 @PostMapping("save")
2 @PreAuthorize("hasAuthority('sys:user:add') AND hasAuthority('sys:user:edit')")
3 public RestResponse save(@RequestBody @Validated SysUser sysUser, BindingResult result) {
4 ValiParamUtils.ValiParamReq(result);
5 return sysUserService.save(sysUser);
6 }
1 @Override
2 protected void configure(HttpSecurity httpSecurity) throws Exception {
3 //使用的是JWT,禁用csrf
4 httpSecurity.cors().and().csrf().disable()
5 //设置请求必须进行权限认证
6 .authorizeRequests()
7 //首页和登录页面
8 .antMatchers("/").permitAll()
9 .antMatchers("/login").permitAll()
10 // 其他所有请求需要身份认证
11 .anyRequest().authenticated();
12 //退出登录处理
13 httpSecurity.logout().logoutSuccessHandler(...);
14 //token验证过滤器
15 httpSecurity.addFilterBefore(...);
16 }
1 @PostMapping("save")
2 @PreAuthorize("hasAuthority('sys:user:add')")
3 public RestResponse save(@RequestBody @Validated SysUser sysUser, BindingResult result) {
4 ValiParamUtils.ValiParamReq(result);
5 return sysUserService.save(sysUser);
6 }
1 @Configuration
2 @EnableWebSecurity
3 @EnableGlobalMethodSecurity(prePostEnabled = true)
4 public class SecurityConfig extends WebSecurityConfigurerAdapter {
5 ......
6 @Override
7 protected void configure(HttpSecurity httpSecurity) throws Exception {
8 //使用的是JWT,禁用csrf
9 httpSecurity.cors().and().csrf().disable()
10 //设置请求必须进行权限认证
11 .authorizeRequests()
12 ......
13 //首页和登录页面
14 .antMatchers("/").permitAll()
15 .antMatchers("/login").permitAll()
16 // 其他所有请求需要身份认证
17 .anyRequest().authenticated();
18 ......
19 //token验证过滤器
20 httpSecurity.addFilterBefore(new JwtFilter(authenticationManager()), UsernamePasswordAuthenticationFilter.class);
21 }
22 }
1 public class JwtFilter extends BasicAuthenticationFilter {
2
3 @Autowired
4 public JwtFilter(AuthenticationManager authenticationManager) {
5 super(authenticationManager);
6 }
7
8 @Override
9 protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
10 // 获取token, 并检查登录状态
11 // 获取令牌并根据令牌获取登录认证信息
12 Authentication authentication = JwtTokenUtils.getAuthenticationeFromToken(request);
13 // 设置登录认证信息到上下文
14 SecurityContextHolder.getContext().setAuthentication(authentication);
15
16 chain.doFilter(request, response);
17 }
18
19 }
1 package javax.servlet;
2
3 import java.io.IOException;
4
5 public interface FilterChain {
6 void doFilter(ServletRequest var1, ServletResponse var2) throws IOException, ServletException;
7 }
1 public void doFilter(ServletRequest request, ServletResponse response,
2 FilterChain chain) throws IOException, ServletException {
3 FilterInvocation fi = new FilterInvocation(request, response, chain);
4 invoke(fi);
5 }
1 public class FilterInvocation {
2
3 private FilterChain chain;
4 private HttpServletRequest request;
5 private HttpServletResponse response;
6
7
8 public FilterInvocation(ServletRequest request, ServletResponse response,
9 FilterChain chain) {
10 if ((request == null) || (response == null) || (chain == null)) {
11 throw new IllegalArgumentException("Cannot pass null values to constructor");
12 }
13
14 this.request = (HttpServletRequest) request;
15 this.response = (HttpServletResponse) response;
16 this.chain = chain;
17 }
18 ......
19 }
1 public void invoke(FilterInvocation fi) throws IOException, ServletException {
2 if ((fi.getRequest() != null)
3 && (fi.getRequest().getAttribute(FILTER_APPLIED) != null)
4 && observeOncePerRequest) {
5 //筛选器已应用于此请求,每个请求处理一次,所以不需重新进行安全检查
6 fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
7 }
8 else {
9 // 第一次调用此请求时,需执行安全检查
10 if (fi.getRequest() != null && observeOncePerRequest) {
11 fi.getRequest().setAttribute(FILTER_APPLIED, Boolean.TRUE);
12 }
13 //1.授权具体实现入口
14 InterceptorStatusToken token = super.beforeInvocation(fi);
15 try {
16 //2.授权通过后执行的业务
17 fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
18 }
19 finally {
20 super.finallyInvocation(token);
21 }
22 //3.后续处理
23 super.afterInvocation(token, null);
24 }
25 }
1 private Authentication authenticateIfRequired() {
2 Authentication authentication = SecurityContextHolder.getContext()
3 .getAuthentication();
4 if (authentication.isAuthenticated() && !alwaysReauthenticate) {
5 ......
6 return authentication;
7 }
8 authentication = authenticationManager.authenticate(authentication);
9 SecurityContextHolder.getContext().setAuthentication(authentication);
10 return authentication;
11 }
1 public interface AccessDecisionManager {
2 void decide(Authentication authentication, Object object,
3 Collection<ConfigAttribute> configAttributes) throws AccessDeniedException,
4 InsufficientAuthenticationException;
5 boolean supports(ConfigAttribute attribute);
6 boolean supports(Class<?> clazz);
7 }
1 public interface AccessDecisionVoter<S> {
2 int ACCESS_GRANTED = 1;//表示同意
3 int ACCESS_ABSTAIN = 0;//表示弃权
4 int ACCESS_DENIED = -1;//表示拒绝
5 ......
6 }
锋哥最新SpringCloud分布式电商秒杀课程发布
👇👇👇
👆长按上方微信二维码 2 秒
感谢点赞支持下哈
评论
学一学 Spring Boot 3.x
在 Java 后端开发领域,功能强大的 Spring 开源框架不仅是首选,也是事实上的标准。但由于 Spring 存在配置烦琐、部署不易、依赖管理困难等问题,因此基于 Spring 的快速开发框架 Spring Boot 应运而生,它能大大简化 Spring 应用程序的配置和部署过程。2018 年,
小哈学Java
0
架构应该如何来理解?
来源:zhuanlan.zhihu.com/p/141027477👉 欢迎加入小哈的星球 ,你将获得: 专属的项目实战 / Java 学习路线 / 一对一提问 / 学习打卡 / 赠书福利全栈前后端分离博客项目 2.0 版本完结啦, 演示链接:htt
小哈学Java
0
有意思!一个关于 Spring 历史的在线小游戏
发现 Spring One 的官网上有个好玩的彩蛋,分享给大家!进到Spring One的官网,可以看到右下角有个类似马里奥游戏中的金币图标。点击该金币之后,会打开一个新的页面,进入下面这样一个名为:The History Of Spring 的在线小游戏你可以使用上下左右的方向键来控制Spring
公众号程序猿DD
1
【深度学习】图解自注意力机制(Self-Attention)
一、注意力机制和自注意力机制的区别Attention机制与Self-Attention机制的区别传统的Attention机制发生在Target的元素和Source中的所有元素之间。简单讲就是说Attention机制中的权重的计算需要Target来参与。即在Encoder-Decoder 模型中,At
机器学习初学者
0
你真的理解 devDependencies 和 dependencies 的区别吗?
点击上方 前端Q,关注公众号回复加群,加入前端Q技术交流群作者:井柏然原文:https://juejin.cn/post/7135795969370619918你是否真的理解 devDependencies 和 dependencies 的区别?如果不能确切的回答、理解还停留在模糊的阶段,
前端Q
0
PyPy为什么能让Python比C还快?一文了解内在机制
我的小册:(小白零基础用Python量化股票分析小册) ,原价299,限时特价2杯咖啡,满100人涨10元。来源:机器之心「如果想让代码运行得更快,您应该使用 PyPy。」—— Python 之父 Guido van Rossum对于研究人员来说,迅速把想法代码化并查看其是否行得通至关重要。Pyth
菜鸟学Python
0
图解 transformer 中的自注意力机制
↓推荐关注↓本文将将介绍注意力的概念从何而来,它是如何工作的以及它的简单的实现。注意力机制在整个注意力过程中,模型会学习了三个权重:查询、键和值。查询、键和值的思想来源于信息检索系统。所以我们先理解数据库查询的思想。假设有一个数据库,里面有所有一些作家和他们的书籍信息。现在我想读一些Rabindra
Python学习与数据挖掘
0
每天骑的共享单车是什么通信原理,有人了解过吗?
转自:网络我们经常骑的共享单车到底是什么通信原理,有人了解过吗?现在就带大家了解下。一、智能车锁共享单车最核心的硬件是智能车锁,主要用于实现控制和定位功能。车锁内集成了嵌入式芯片(通信模块),GPS模块和物联网SIM卡。智能锁制造商通过在锁内集成带有独立号码的SIM卡,通过2G、3G、4G网络,与云
菜鸟学Python
1