当前位置: 首页 > news >正文

考试系统Spring Security的配置

设置Spring Security配置类

1、设置包括认证、授权方法

        protected void configure(HttpSecurity http) throws Exception {http.headers().frameOptions().disable();List<String> securityIgnoreUrls = systemConfig.getSecurityIgnoreUrls();String[] ignores = new String[securityIgnoreUrls.size()];http.addFilterAt(authenticationFilter(), UsernamePasswordAuthenticationFilter.class)// 将自定义的认证过滤器添加到 UsernamePasswordAuthenticationFilter 位置.exceptionHandling().authenticationEntryPoint(restAuthenticationEntryPoint)// 配置认证失败处理器.and().authenticationProvider(restAuthenticationProvider).authorizeRequests()// 允许忽略安全检查的 URL 列表中的所有 URL.antMatchers(securityIgnoreUrls.toArray(ignores)).permitAll()// 只允许具有 ADMIN 角色的用户访问 /api/admin/** URL.antMatchers("/api/admin/**").hasRole(RoleEnum.ADMIN.getName())// 只允许具有 STUDENT 角色的用户访问 /api/student/** URL.antMatchers("/api/student/**").hasRole(RoleEnum.STUDENT.getName()).anyRequest().permitAll()// 配置访问拒绝处理器.and().exceptionHandling().accessDeniedHandler(restAccessDeniedHandler)// 配置登录成功和失败处理器.and().formLogin().successHandler(restAuthenticationSuccessHandler).failureHandler(restAuthenticationFailureHandler)// 配置登出 URL 和登出成功处理器.and().logout().logoutUrl("/api/user/logout").logoutSuccessHandler(restLogoutSuccessHandler).invalidateHttpSession(true)// 配置 "记住我" 功能.and().rememberMe().key(CookieConfig.getName()).tokenValiditySeconds(CookieConfig.getInterval()).userDetailsService(formDetailsService).and().csrf().disable().cors();}

2、设置跨域资源共享

        //设置跨域资源共享@Beanpublic CorsConfigurationSource corsConfigurationSource() {final CorsConfiguration configuration = new CorsConfiguration();configuration.setMaxAge(3600L);configuration.setAllowedOrigins(Collections.singletonList("*"));configuration.setAllowedMethods(Collections.singletonList("*"));configuration.setAllowCredentials(true);configuration.setAllowedHeaders(Collections.singletonList("*"));final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();source.registerCorsConfiguration("/api/**", configuration);return source;}

3、自定义认证过滤器

        @Beanpublic RestLoginAuthenticationFilter authenticationFilter() throws Exception {RestLoginAuthenticationFilter authenticationFilter = new RestLoginAuthenticationFilter();authenticationFilter.setAuthenticationSuccessHandler(restAuthenticationSuccessHandler);authenticationFilter.setAuthenticationFailureHandler(restAuthenticationFailureHandler);authenticationFilter.setAuthenticationManager(authenticationManagerBean());authenticationFilter.setUserDetailsService(formDetailsService);return authenticationFilter;}

二、关于spring security执行逻辑

Filter


public class RestLoginAuthenticationFilter extends AbstractAuthenticationProcessingFilter {private final org.slf4j.Logger logger = LoggerFactory.getLogger(RestLoginAuthenticationFilter.class);//设置该过滤器匹配的 URL 和 HTTP 方法,这里是匹配 /api/user/login 和 POST 请求。public RestLoginAuthenticationFilter() {super(new AntPathRequestMatcher("/api/user/login", "POST"));}@Overridepublic Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {UsernamePasswordAuthenticationToken authRequest;try (InputStream is = request.getInputStream()) {AuthenticationBean authenticationBean = JsonUtil.toJsonObject(is, AuthenticationBean.class);request.setAttribute(TokenBasedRememberMeServices.DEFAULT_PARAMETER, authenticationBean.isRemember());authRequest = new UsernamePasswordAuthenticationToken(authenticationBean.getUserName(), authenticationBean.getPassword());} catch (IOException e) {logger.error(e.getMessage(), e);authRequest = new UsernamePasswordAuthenticationToken("", "");}setDetails(request, authRequest);//return this.getAuthenticationManager().authenticate(authRequest); 这行代码的作用是将包含认证信息的// Authentication 对象交给 Spring Security 的 AuthenticationManager 进行处理。AuthenticationManager 会根据配置的// AuthenticationProvider 执行认证逻辑,并返回认证结果。return this.getAuthenticationManager().authenticate(authRequest);}//配置记住我的服务void setUserDetailsService(UserDetailsService userDetailsService) {RestTokenBasedRememberMeServices tokenBasedRememberMeServices = new RestTokenBasedRememberMeServices(CookieConfig.getName(), userDetailsService);tokenBasedRememberMeServices.setTokenValiditySeconds(CookieConfig.getInterval());setRememberMeServices(tokenBasedRememberMeServices);}private void setDetails(HttpServletRequest request, UsernamePasswordAuthenticationToken authRequest) {authRequest.setDetails(authenticationDetailsSource.buildDetails(request));}
}

provider


@Component
public class RestAuthenticationProvider implements AuthenticationProvider {private final AuthenticationService authenticationService;private final UserService userService;private final WebContext webContext;@Autowiredpublic RestAuthenticationProvider(AuthenticationService authenticationService, UserService userService, WebContext webContext) {this.authenticationService = authenticationService;this.userService = userService;this.webContext = webContext;}@Overridepublic Authentication authenticate(Authentication authentication) throws AuthenticationException {String username = authentication.getName();String password = (String) authentication.getCredentials();com.mindskip.xzs.domain.User user = userService.getUserByUserName(username);if (user == null) {throw new UsernameNotFoundException("用户名或密码错误");}boolean result = authenticationService.authUser(user, username, password);if (!result) {throw new BadCredentialsException("用户名或密码错误");}UserStatusEnum userStatusEnum = UserStatusEnum.fromCode(user.getStatus());if (UserStatusEnum.Disable == userStatusEnum) {throw new LockedException("用户被禁用");}ArrayList<GrantedAuthority> grantedAuthorities = new ArrayList<>();grantedAuthorities.add(new SimpleGrantedAuthority(RoleEnum.fromCode(user.getRole()).getRoleName()));User authUser = new User(user.getUserName(), user.getPassword(), grantedAuthorities);return new UsernamePasswordAuthenticationToken(authUser, authUser.getPassword(), authUser.getAuthorities());}@Overridepublic boolean supports(Class<?> aClass) {return true;}
}

相关文章:

  • SQL题:未完成率较高的50%用户近三个月答卷情况
  • 深入了解常用负载均衡软件
  • 第三方软件测试机构流程分享,软件检测报告需多少时间和费用?
  • 如何利用AI大模型设计电机本体?
  • 反激开关电源开关MOS管选择
  • 【漏洞复现】世邦通信 SPON IP网络对讲广播系统 addscenedata.php 任意文件上传漏洞
  • Linux 查看 CPU核数 及 内存
  • Goroutine和协程的区别
  • SpringCloud微服务框架的原理及应用详解(一)
  • 常见的宽基指数基金
  • PHP混淆加密以及常用的一些加密工具
  • 内核学习——1、list_head
  • 深度解析响应式异步编程模型
  • 巧用newSingleThreadExecutor让异步任务顺序跑
  • 构建一个强大的小型虚拟负载
  • 时间复杂度分析经典问题——最大子序列和
  • iBatis和MyBatis在使用ResultMap对应关系时的区别
  • Swoft 源码剖析 - 代码自动更新机制
  • 翻译--Thinking in React
  • 基于OpenResty的Lua Web框架lor0.0.2预览版发布
  • 通过git安装npm私有模块
  • 小程序上传图片到七牛云(支持多张上传,预览,删除)
  • 一、python与pycharm的安装
  • 一道面试题引发的“血案”
  • 在electron中实现跨域请求,无需更改服务器端设置
  • 怎么将电脑中的声音录制成WAV格式
  • 自动记录MySQL慢查询快照脚本
  • TPG领衔财团投资轻奢珠宝品牌APM Monaco
  • ​猴子吃桃问题:每天都吃了前一天剩下的一半多一个。
  • #define,static,const,三种常量的区别
  • #数据结构 笔记一
  • $ is not function   和JQUERY 命名 冲突的解说 Jquer问题 (
  • (175)FPGA门控时钟技术
  • (2)(2.4) TerraRanger Tower/Tower EVO(360度)
  • (done) 声音信号处理基础知识(2) (重点知识:pitch)(Sound Waveforms)
  • (二)七种元启发算法(DBO、LO、SWO、COA、LSO、KOA、GRO)求解无人机路径规划MATLAB
  • (附源码)spring boot基于Java的电影院售票与管理系统毕业设计 011449
  • (附源码)spring boot球鞋文化交流论坛 毕业设计 141436
  • (七)Knockout 创建自定义绑定
  • ***原理与防范
  • .\OBJ\test1.axf: Error: L6230W: Ignoring --entry command. Cannot find argumen 'Reset_Handler'
  • .htaccess配置重写url引擎
  • .NET Core IdentityServer4实战-开篇介绍与规划
  • .NET Core WebAPI中使用swagger版本控制,添加注释
  • .net core 使用js,.net core 使用javascript,在.net core项目中怎么使用javascript
  • .NET Framework 服务实现监控可观测性最佳实践
  • .NET 回调、接口回调、 委托
  • .Net转前端开发-启航篇,如何定制博客园主题
  • @Conditional注解详解
  • @RunWith注解作用
  • @四年级家长,这条香港优才计划+华侨生联考捷径,一定要看!
  • [ JavaScript ] JSON方法
  • [ 代码审计篇 ] 代码审计案例详解(一) SQL注入代码审计案例
  • [000-002-01].数据库调优相关学习
  • [100天算法】-每个元音包含偶数次的最长子字符串(day 53)