考试系统Spring Security的配置

news2024/10/5 19:16:11

设置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、设置跨域资源共享

        //设置跨域资源共享
        @Bean
        public 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、自定义认证过滤器

        @Bean
        public 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"));
    }

    @Override
    public 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;

    @Autowired
    public RestAuthenticationProvider(AuthenticationService authenticationService, UserService userService, WebContext webContext) {
        this.authenticationService = authenticationService;
        this.userService = userService;
        this.webContext = webContext;
    }

    @Override
    public 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());
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}

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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

重生奇迹mu圣导师介绍

出生地&#xff1a;勇者大陆 性 别&#xff1a;男 擅 长&#xff1a;统率&宠物使用 转 职&#xff1a;祭师&#xff08;3转&#xff09; 介 绍&#xff1a;当玩家账号中有一个Lv250以上角色时&#xff0c;便可以创建职业为圣导师的新角色&#xff0c;圣导师每升一级获得…

Trying to access array offset on value of type null

主要原因是版本7.4以后PHP解析器会对null类型的下标访问直接报错 背景&#xff1a; laravel框架 同时使用了扩展A和扩展B 扩展A要求 php>7.4,同时扩展B的对null类型的下标访问不兼容php7.4 修改扩展B不太现实&#xff0c;毕竟扩展B中有太多的对null类型的下标访问。 解决…

6月17日(周一),AH 股行情总结

AI手机及苹果概念股全日走强&#xff0c;领益智造、山东精密等多股涨停&#xff0c;立讯精、歌尔股份涨逾6% 。新车型秦L销售预期提振股价&#xff0c;比亚迪涨超1% &#xff1b;航运、煤炭、地产板块下跌。 文章正文 周一&#xff0c;A股低开高走&#xff0c;上证指数收跌0.…

代码随想录算法训练营第二十六天|39. 组合总和、 40.组合总和II、 131.分割回文串

39. 组合总和 题目链接&#xff1a;39. 组合总和 文档讲解&#xff1a;代码随想录 状态&#xff1a;卡了一会儿 思路&#xff1a;先排序&#xff0c;方便剪枝。允许数字重复使用&#xff0c;因此递归调用时传入当前索引i。 题解&#xff1a; public class Solution {// 用于存…

ETAS AUTOSAR工具链的作用

一、AUTOSAR是什么&#xff1f; AUTOSAR&#xff08;Automotive Open System Architecture&#xff09;是一个全球性的联盟&#xff0c;致力于制定和推广汽车电子系统的标准化解决方案。它是由汽车制造商、供应商和工程公司组成的合作伙伴网络&#xff0c;旨在解决汽车电子系统…

如何理解 Java 类加载器的工作原理及其使用场景

1. 简介 Java类加载器&#xff08;ClassLoader&#xff09;是Java运行时环境的一部分&#xff0c;负责动态加载Java类文件到Java虚拟机&#xff08;JVM&#xff09;中。类加载器是Java反射机制和动态特性的重要基础&#xff0c;为Java的跨平台和动态加载提供了支持。理解类加载…

ANSYS EMC解决方案与经典案例

EMC问题非常复杂&#xff0c;各行各业都会涉及&#xff0c;例如航空、航天、船舶、汽车、火车、高科技、物联网、消费电子。要考虑EMC的对象很多&#xff0c;包含整个系统、设备、PCB、线缆、电源、芯片封装。而且技术领域覆盖广&#xff0c;涉及高频问题、低频问题&#xff1b…

《山西教育》教学版是什么级别的刊物?

《山西教育》教学版是什么级别的刊物&#xff1f; 《山西教育(教学版)》创刊于1956年&#xff0c;是由山西教育报刊社主办的教学刊物。山西省一级期刊&#xff0c;是“宣传教育政策&#xff0c;关注教育热点&#xff0c;传播先进经验&#xff0c;提供教改资讯”的权威性期刊&a…

Http协议JSON格式

1. 计算机网络 计算机网络是指将地理位置不同的具有独立功能的多台计算机及其外部设备&#xff0c;通过通信线路连接起来&#xff0c;在网络操作系统&#xff0c;网络管理软件及网络通信协议的管理和协调下&#xff0c;实现资源共享和信息传递的计算机系统。 思考:计算机网络…

UniVue更新日志:使用Carousel组件实现轮播图效果

github仓库 稳定版本仓库&#xff1a;https://github.com/Avalon712/UniVue 开发版本仓库&#xff1a;https://github.com/Avalon712/UniVue-Develop UniVue扩展框架-UniVue源生成器仓库&#xff1a;https://github.com/Avalon712/UniVue-SourceGenerator 更新说明 今天的更…

数字人源码部署怎么做?如何高效搭建好用的数字人系统?

作为人工智能时代的风口项目&#xff0c;AI数字人自出现之日起便引发了大量的关注。不少创业者都有了搭建数字人系统的想法&#xff0c;但却苦于没有强大的专业背景和雄厚资金支撑&#xff0c;只能在局外徘徊&#xff0c;而这恰恰为数字人源码公司推出的数字人源码部署服务的火…

自然语言处理学习路线(1)——NLP的基本流程

NLP基本流程 【NLP基本流程】 0. 获取语料 1. 语料预处理 2. 特征工程&选择 3. 模型训练 4. 模型输出&上线 【NLP基本流程图】 Reference 1. 自然语言处理(NLP)的一般处理流程&#xff01;-腾讯云开发者社区-腾讯云 2. https://zhuanlan.zhihu.com/p/55…

FreeBSD通过CBSD管理低资源容器jail来安装Ubuntu子系统实践

简介 FreeBSD、CBSD、Jail和Ubuntu&#xff0c;四者的组合方案可以说是强强联合&#xff0c;极具性价比和竞争力&#xff01;同时安装简单方便&#xff0c;整体方案非常先进。 CBSD是为FreeBSD jail子系统、bhyve、QEMU/NVMM和Xen编写的管理层。该项目定位为一个综合解决方案…

YOLOv5目标检测——基于YOLOv5的吊车安全监测

移动式起重机是建筑施工中使用的重要设备。 遵守正确的操作程序对于防止事故很重要。 然而&#xff0c;其中存在人为错误的因素。 这里我将举一个例子来说明计算机视觉&#xff08;CV&#xff09;如何帮助解决这个问题。 1、移动式起重机操作的安全问题 为简单起见&#xff0…

室内外一体化定位系统的创新与应用

随着科技的飞速发展&#xff0c;人们对定位技术的需求日益增强。传统的定位技术主要依赖于室外环境&#xff0c;如GPS等卫星定位技术。然而&#xff0c;在室内环境下&#xff0c;由于信号遮挡和多径效应等问题&#xff0c;这些技术往往难以发挥有效作用。因此&#xff0c;室内外…

记录一次基于Vite搭建Vue3项目的过程

Vue2已经于2023年12月31日停止维护了&#xff0c;2024年算是vue3的崭新的一年&#xff0c;我们的项目也基本从vue2逐渐向着Vue3过渡&#xff0c;Vue3相较于vue2有更好的开发体验&#xff0c;和ts的自然融合使得项目的结构、功能拆分变得更加的清晰&#xff1b;组合式声明有种MV…

【吉林大学Java程序设计】第7章:对象的容纳

第7章&#xff1a;对象的容纳 1.数组 Arrays1.1 数组的创建、初始化和使用&#xff08;1&#xff09;数组的声明&#xff08;2&#xff09;数组初始化静态初始化动态初始化对象数组的初始化 &#xff08;3&#xff09;数组的使用 1.2 多维数组1.3 数组与数组的引用1.4 数组工具…

Python学习从0开始——Kaggle深度学习002

Python学习从0开始——Kaggle深度学习002 一、单个神经元1.深度学习2.线性单元示例 - 线性单元作为模型多个输入 3.Keras中的线性单元 二、深度神经网络1.层多种类型的层 2.激活函数3.堆叠密集层4.构建Sequential模型 三、随机梯度下降1.介绍2.损失函数3.梯度下降法1.梯度下降法…

Spring Boot 优雅关机时异步线程安全优化

个人名片 &#x1f393;作者简介&#xff1a;java领域优质创作者 &#x1f310;个人主页&#xff1a;码农阿豪 &#x1f4de;工作室&#xff1a;新空间代码工作室&#xff08;提供各种软件服务&#xff09; &#x1f48c;个人邮箱&#xff1a;[2435024119qq.com] &#x1f4f1…

【Python】在运行中使用warnings.filterwarnings,可以忽略测试中遇到的问题

在 Python 中&#xff0c;warnings 是一个内置模块&#xff0c;用于发出有关程序执行的警告信息&#xff0c;这些警告信息通常是关于程序行为的潜在问题。 不过&#xff0c;这些问题通常不是致命的错误&#xff0c;只不过是展示我们代码中潜在的问题&#xff0c;或不推荐的做法…