SpringSecurity5(8-权限注解)

news/2025/3/28 14:37:57/文章来源:https://www.cnblogs.com/penggx/p/18784440

注解使用

Spring Security 默认是禁用注解的,要想开启注解,需要加上@EnableMethodSecurity 注解

  1. 使用@Secured 需要在配置类中添加注解@EnableGlobalMethodSecurity(securedEnabled = true)才能生效
  2. 使用@PreAuthorize 和@PostAuthorize 需要在配置类中配置注解@EnableGlobalMethodSecurity(prePostEnable = true)才能生效

@Secured

角色校验,请求到来访问控制单元方法时必须包含 XX 角色才能访问

注意:

  1. 角色必须添加 ROLE_前缀
  2. 如果要求只有同时拥有 admin 和 user 的用户才能访问某个方法时,@Secured 就无能为力了
@Component
public class UserDetailServiceImpl implements UserDetailsService {@Resourceprivate PasswordEncoder passwordEncoder;@Overridepublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {if (username.equals("root")) {return new User(username, passwordEncoder.encode("123"), AuthorityUtils.createAuthorityList("ROLE_read"));} else if (username.equals("user")) {return new User(username, passwordEncoder.encode("123"), AuthorityUtils.createAuthorityList("ROLE_write"));}return new User(username, passwordEncoder.encode("123"), AuthorityUtils.createAuthorityList("read"));}
}
@RestController
public class HelloController {@RequestMapping("/read")@Secured(value = {"ROLE_read"})public String read() {return "read";}@RequestMapping("/write")@Secured(value = {"ROLE_write"})public String write() {return "write";}// 错误实例@RequestMapping("/read2")@Secured(value = {"read"})public String read2() {return "read2";}
}

@PreAuthorize

权限校验,请求到来访问控制单元之前必须包含 XX 权限才能访问,控制单元方法执行前进行角色校验

@RestController
public class HelloController {@RequestMapping("/read3")@PreAuthorize(value = "hasRole('ROLE_read')")public String read3() {return "read3";}@RequestMapping("/read4")@PreAuthorize(value = "hasAnyRole('ROLE_read','ROLE_write')")public String read4() {return "read4";}@RequestMapping("/read5")@PreAuthorize(value = "hasAnyAuthority('ROLE_read','read')")public String read5() {return "read5";}
}

hasRole 与 hasAuthority 的区别

  1. hasRole 的值会添加 ROLE_开头进行判断,而 hasAuthority 不会
  2. 其他方法判断一致
public abstract class SecurityExpressionRoot implements SecurityExpressionOperations {protected final Authentication authentication;private AuthenticationTrustResolver trustResolver;private RoleHierarchy roleHierarchy;private Set<String> roles;private String defaultRolePrefix = "ROLE_";/** Allows "permitAll" expression */public final boolean permitAll = true;/** Allows "denyAll" expression */public final boolean denyAll = false;private PermissionEvaluator permissionEvaluator;public final String read = "read";public final String write = "write";public final String create = "create";public final String delete = "delete";public final String admin = "administration";//...public final boolean hasAuthority(String authority) {return hasAnyAuthority(authority);}public final boolean hasAnyAuthority(String... authorities) {return hasAnyAuthorityName(null, authorities);}public final boolean hasRole(String role) {return hasAnyRole(role);}public final boolean hasAnyRole(String... roles) {return hasAnyAuthorityName(defaultRolePrefix, roles);}private boolean hasAnyAuthorityName(String prefix, String... roles) {Set<String> roleSet = getAuthoritySet();for (String role : roles) {String defaultedRole = getRoleWithDefaultPrefix(prefix, role);if (roleSet.contains(defaultedRole)) {return true;}}return false;}// ....private static String getRoleWithDefaultPrefix(String defaultRolePrefix, String role) {if (role == null) {return role;}if (defaultRolePrefix == null || defaultRolePrefix.length() == 0) {return role;}// 判断是否以 ROLE_开头if (role.startsWith(defaultRolePrefix)) {return role;}return defaultRolePrefix + role;}
}

@PostAuthorize

权限校验,请求到来访问控制单元之后必须包含 XX 权限才能访问,在方法执行后进行权限校验,适合验证带有返回值的权限

@PostAuthorize("hasRole('ROLE_管理员')")
@RequestMapping("/toMain")
public String toMain(){return "main";
}@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;
}

@PreFilter

对传递参数值做过滤

@PostMapping("/preFilter")
@PreAuthorize("hasAnyAuthority('admin','update')") // 注意单引号
@PreFilter("filterObject.id % 2 == 0") // id 为偶数才能请求
public String preFilter(@RequestBody List<User> userLists){log.info("=== 进入当前 preFilter ====");log.info(userLists.toString());return "security test 5  preFilter  需要验证的接口";
}

@PostFilter

权限验证通过后,留下指定用户名的数据,对返回数据做过滤

@RequestMapping("/postFilter")
@PreAuthorize("hasAnyAuthority('admin','update')") // 注意单引号
@PostFilter("filterObject.username == 'xiangjiao'") // 针对返回数据做过滤
public List<User> postFilter(){log.info("=== 进入当前 postFilter ====");List<User> userLists = new ArrayList<>();userLists.add(new User(1,"xiangjiao","bunana",1,0));userLists.add(new User(2,"xiangjiao2","bunana2",1,0));return userLists;
}

使用注意

  1. 使用@EnableGlobalMethodSecurity 开启注解支持后,用户必须实现 UserDetailsService 方法,使用 auth.inMemoryAuthentication()内存管理用户信息会失效
  2. 如果注解要使用 permitAll()、isAnonymous()等方法时,需要在 config 方法中取消.anyRequest().authenticated()的设置,否则会无效。
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class MyWebSecurityConfig extends WebSecurityConfigurerAdapter {@Autowiredprivate UserDetailsService userDetailsService;@Autowiredprivate BCryptPasswordEncoder bCryptPasswordEncoder;@Overrideprotected void configure(HttpSecurity http) throws Exception {http.cors().and().csrf().disable();// 下面需注释,否则注解无效,生效的是这里的配置/*.authorizeRequests().anyRequest().authenticated(); */}@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);}
}
@RestController
public class HelloController {@RequestMapping("/read3")@PreAuthorize(value = "hasRole('ROLE_read')")public String read3() {return "read3";}@RequestMapping("/read4")@PreAuthorize(value = "hasAnyRole('ROLE_read','ROLE_write')")public String read4() {return "read4";}@RequestMapping("/read5")@PreAuthorize(value = "hasAnyAuthority('ROLE_read','read')")public String read5() {return "read5";}@RequestMapping("/isAnonymous")@PreAuthorize(value = "isAnonymous()")public String isAnonymous() {return "isAnonymous";}
}

注解方法

  1. hasAuthority(String):判断角色是否具有特定权限

http.authorizeRequests().antMatchers("/main1.html").hasAuthority("admin")

  1. hasAnyAuthority(String ...):如果用户具备给定权限中某一个,就允许访问

http.authorizeRequests().antMatchers("/admin/read").hasAnyAuthority("xxx", "xxx")

  1. hasRole(String):如果用户具备给定角色就允许访问,否则出现 403

http.authorizeRequests().antMatchers("/admin/read").hasRole("ROLE_管理员")

  1. hasAnyRole(String ...):如果用户具备给定角色的任意一个,就允许被访问

http.authorizeRequests().antMatchers("/guest/read").hasAnyRole("ROLE_管理员", "ROLE_访客")

  1. hasIpAddress(String):请求是指定的 IP 就允许访问

http.authorizeRequests().antMatchers("/ip").hasIpAddress("127.0.0.1")

  1. permitAll():允许所有人(可无任何权限)访问
  2. denyAll():不允许任何(即使有最大权限)访问。
  3. isAnonymous():为可匿名(不登录)访问。
  4. isAuthenticated():为身份证认证后访问。
  5. isRememberMe():为记住我用户操作访问。
  6. isFullyAuthenticated():为非匿名且非记住我用户允许访问

JSR-250 注解

注意:使用 JSR-250 注解需要设置@EnableGlobalMethodSecurity(jsr250Enabled = true)才能使用

  1. @DenyAll
  2. @PermitAll
  3. @RolesAllowed

例如:@RolesAllowed({"USER", "ADMIN"}),代表标注的方法只要具有 USER、ADMIN 任意一种权限就可以访问

使用案例

自定义权限校验

interface TestPermissionEvaluator {boolean check(Authentication authentication);
}@Service("testPermissionEvaluator")
public class TestPermissionEvaluatorImpl implements TestPermissionEvaluator {public boolean check(Authentication authentication) {System.out.println("进入了自定义的匹配器" + authentication);return false;}
}
@PreAuthorize("@testPermissionEvaluator.check(authentication)")
public String test0() {return "说明你有自定义权限";
}

权限异常处理

AuthenticationEntryPoint

用来解决匿名用户访问无权限资源时的异常

注意:使用 AuthenticationEntryPoint 会导致原来的/login 登录页面失效

public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {@Overridepublic void commence(HttpServletRequest request, HttpServletResponse response,AuthenticationException authException) throws IOException, ServletException {response.setCharacterEncoding("utf-8");response.setContentType("text/javascript;charset=utf-8");response.getWriter().print(JSONObject.toJSONString(RestMsg.error("没有访问权限!")));}
}

AccessDeniedHandler

用来解决认证过的用户访问无权限资源时的异常

@Component
public class MyAccessDeniedHandler implements AccessDeniedHandler {@Overridepublic void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {response.setStatus(HttpServletResponse.SC_OK);response.setContentType("text/html;charset=UTF-8");response.getWriter().write("<html>" +"<body>" +"<div style='width:800px;text-align:center;margin:auto;font-size:24px'>" +"权限不足,请联系管理员" +"</div>" +"</body>" +"</html>");response.getWriter().flush();//刷新缓冲区}
}

SecurityConfig 配置

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class MyWebSecurityConfig extends WebSecurityConfigurerAdapter {@Autowiredprivate UserDetailsService userDetailsService;@Autowiredprivate BCryptPasswordEncoder bCryptPasswordEncoder;@Overrideprotected void configure(HttpSecurity http) throws Exception {http.cors().and().csrf().disable().authorizeRequests().antMatchers("/user/sign").permitAll().anyRequest().authenticated();//添加自定义异常入口http.exceptionHandling().authenticationEntryPoint(new CustomAuthenticationEntryPoint()).accessDeniedHandler(new CustomAccessDeineHandler());       }@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/902311.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Windows Server 2025 中文版、英文版下载 (2025 年 3 月更新)

Windows Server 2025 中文版、英文版下载 (2025 年 3 月更新)Windows Server 2025 中文版、英文版下载 (2025 年 3 月更新) Windows Server 2025 LTSC x64 (updated Mar 2025) 请访问原文链接:https://sysin.org/blog/windows-server-2025/ 查看最新版。原创作品,转载请保留出…

分享报表工具核心三种扩展模型示例

报表工具的核心是父子格扩展模型,通过父子格扩展模型实现各种类型报表,例如网格式报表、行式报表、主子报表、分组报表、交叉报表等。报表有三种扩展模型父子格扩展模型双父格扩展模型兄弟格扩展模型父子格扩展模型B7单元格是第7行所有其它单元格的父格,其它单元格随父格扩展…

centos忘记密码

centos6系统忘记密码: 1、在开机启动的时候快速按键盘上的“E”键 或者“ESC”键,会进入如下界面2、选择你忘记密码的内核,再次按“E”,出现下图,选择第二项,(以kernel开头的行)再次按“E”键3、在信息的最后加“空格”,直接输入数字的“1”(如图)或者 键入“single…

.NET 10 Preview 2 增强了 Blazor 和.NET MAUI

.NET 团队 3.18 发布了.NET 10 Preview 2(https://devblogs.microsoft.com/dotnet/dotnet-10-preview-2/)。.NET 10 Preview 2 主要对 Blazor 和.NET MAUI 进行了增强。Blazor 在 ASP.NET Core 网络开发框架中的组件以及.NET MAUI 获得了最多关注。此次更新主要集中在小的修复…

读DAMA数据管理知识体系指南26数据集成实施指南

读DAMA数据管理知识体系指南26数据集成实施指南1. 工具 1.1. 数据转换引擎/ETL工具1.1.1. 数据转换引擎(或ETL工具)是数据集成工具箱中的主要工具,是每个企业数据集成程序的核心1.1.2. 无论是批量的还是实时的,物理的或虚拟的数据都存在运用非常复杂的工具来开发和执行ETL1…

BFS 算法模板及使用

BFS 算法模板及使用 什么是 BFS 算法? BFS (Breadth-First Search) 算法,中文全称广度优先搜索(宽度优先搜索), 区别于 DFS 算法一条路走到黑的本质, BFS 使用扩散性搜索。它将会根据规则一层一层向下搜索,容易发现,BFS 算法找到的路径一定是最短的,同时,它的时间复…

ResNet-152 模型性能评估

ResNet-152 模型在渴望模式下的性能评估为了预热 GPU,在进行 20 次额外迭代以获取模型的平均推理时间之前,先运行 ResNet-152 模型 10 次。n_warmup = 10n_test = 20dtype = torch.bfloat16inference_time=[]mode=[]t_warmup, _ = timed(lambda:model(input_batch), n_warmup…

推荐专著1《AI芯片开发核心技术详解》、2《智能汽车传感器:原理设计应用》、3《TVM编译器原理与实践》、4《LLVM编译器原理与实践》

4本书推荐《AI芯片开发核心技术详解》、《智能汽车传感器:原理设计应用》、《TVM编译器原理与实践》、《LLVM编译器原理与实践》由清华大学出版社资深编辑赵佳霓老师策划编辑的新书《AI芯片开发核心技术详解》已经出版,京东、淘宝天猫、当当等网上,相应陆陆续续可以购买。该…

当巴别塔倒下。——从mygo到mujica

。序章 ???? 那时,天下人的口音,言语,都是一样。他们往东边迁移的时候,在示拿地遇见一片平原,就住在那里。他们彼此商量说,来吧,我们要作砖,把砖烧透了。他们就拿砖当石头,又拿石漆当灰泥。他们说,来吧,我们要建造一座城和一座塔,塔顶通天,为要传扬我们的名,…

一文速通Python并行计算:00 并行计算的基本概念

该文介绍了Python并行计算的核心概念、编程模型及其应用,并介绍了了并行程序的性能分析与优化方法,如并行效率、加速比及Amdahl定律。此外,该文介绍了共享内存、消息传递、数据并行和任务并行等并行编程模型,并提供Python环境配置指南。一文速通 Python 并行计算:00 并行计…

Pydantic配置继承抽象基类模式

title: Pydantic配置继承抽象基类模式 date: 2025/3/21 updated: 2025/3/21 author: cmdragon excerpt: Pydantic模型配置系统支持通过嵌套Config类定义字段校验、序列化等行为。配置继承需显式指定父类Config,子类可覆盖或扩展配置项。动态配置管理允许运行时通过工厂函数创…

Day19_java运算符_死锁

每日一题 题目 请解释死锁(Deadlock)的概念及其产生的必要条件,并说明常见的死锁处理策略及其优缺点。问题分析 此问题考察对操作系统资源管理机制的理解,需深入分析死锁的成因、判定条件及解决方法。回答时需结合理论模型与实际策略,体现系统性思维。参考答案 1. 死锁的定…