spring security调用过程;及自定义改造

news2025/7/18 9:22:43

认证/授权概述

一般系统都有登录接口来校验用户是否存在,密码是否正确,然后会颁发一个token给客户端,后续客户端就可以带着这个token来请求,代表自己是合法请求。

在这里插入图片描述

spring security责任链

请求->UsernamePasswordAuthenticationFilter(判断用户名密码是否正确)->ExceptionTranslationFilter(认证授权时的异常统一处理)->FilterSecurityInterceptor(判断当前用户是否有访问资源权限)->API接口->响应

调用链路图如下,一般我们会从db中去获取用户,所以我们要自己实现userDetailService接口,去重写loadUserByUsername。同时因为自带的UsernamePasswordAuthenticationFilter认证完了就结束了,但实际上我们在认证之后还要授权,所以这里的入口也需要替换成我们自己的controller。在认证过程中查询用户信息的时候,顺序把用户权限也查出来塞到redis中,后面在拿到token来请求的时候就可以直接从redis中获取权限缓存了。

认证授权完了之后,就可以自己再定义个filter,检查请求头里携带的token,解析之后拿到信息封装成
Authentication对象再塞进SecurityContextHolder里的threadLocal变量中,后面在当前请求线程中就可以直接拿出来用了。
在这里插入图片描述

下面来直接上个demo

就拿ruoyi现成的配置来举例了,上面说我们需要自定义登录和用户查询逻辑,所以需要在springsecurity中给我们自己的登录接口开一个口子。
在登录完成之后会返回一个token,所以我们还需要自己写一个token过滤器,解析token,并且把用户信息塞到SecurityContextHolder中给security后面的过滤器使用

配置类

package com.ruoyi.framework.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.web.filter.CorsFilter;
import com.ruoyi.framework.config.properties.PermitAllUrlProperties;
import com.ruoyi.framework.security.filter.JwtAuthenticationTokenFilter;
import com.ruoyi.framework.security.handle.AuthenticationEntryPointImpl;
import com.ruoyi.framework.security.handle.LogoutSuccessHandlerImpl;

/**
 * spring security配置
 * 
 * @author ruoyi
 */
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter
{
    /**
     * 自定义用户认证逻辑
     */
    @Autowired
    private UserDetailsService userDetailsService;
    
    /**
     * 认证失败处理类
     */
    @Autowired
    private AuthenticationEntryPointImpl unauthorizedHandler;

    /**
     * 退出处理类
     */
    @Autowired
    private LogoutSuccessHandlerImpl logoutSuccessHandler;

    /**
     * token认证过滤器
     */
    @Autowired
    private JwtAuthenticationTokenFilter authenticationTokenFilter;
    
    /**
     * 跨域过滤器
     */
    @Autowired
    private CorsFilter corsFilter;

    /**
     * 允许匿名访问的地址
     */
    @Autowired
    private PermitAllUrlProperties permitAllUrl;

    /**
     * 解决 无法直接注入 AuthenticationManager
     *
     * @return
     * @throws Exception
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception
    {
        return super.authenticationManagerBean();
    }

    /**
     * anyRequest          |   匹配所有请求路径
     * access              |   SpringEl表达式结果为true时可以访问
     * anonymous           |   匿名可以访问
     * denyAll             |   用户不能访问
     * fullyAuthenticated  |   用户完全认证可以访问(非remember-me下自动登录)
     * hasAnyAuthority     |   如果有参数,参数表示权限,则其中任何一个权限可以访问
     * hasAnyRole          |   如果有参数,参数表示角色,则其中任何一个角色可以访问
     * hasAuthority        |   如果有参数,参数表示权限,则其权限可以访问
     * hasIpAddress        |   如果有参数,参数表示IP地址,如果用户IP和参数匹配,则可以访问
     * hasRole             |   如果有参数,参数表示角色,则其角色可以访问
     * permitAll           |   用户可以任意访问
     * rememberMe          |   允许通过remember-me登录的用户访问
     * authenticated       |   用户登录后可访问
     */
    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception
    {
        // 注解标记允许匿名访问的url
        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = httpSecurity.authorizeRequests();
        permitAllUrl.getUrls().forEach(url -> registry.antMatchers(url).permitAll());

        httpSecurity
                // CSRF禁用,因为不使用session
                .csrf().disable()
                // 禁用HTTP响应标头
                .headers().cacheControl().disable().and()
                // 认证失败处理类
                .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
                // 基于token,所以不需要session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                // 过滤请求
                .authorizeRequests()
                // 对于登录login 注册register 验证码captchaImage 允许匿名访问
                .antMatchers("/login", "/register", "/captchaImage").permitAll()
                // 静态资源,可匿名访问
                .antMatchers(HttpMethod.GET, "/", "/*.html", "/**/*.html", "/**/*.css", "/**/*.js", "/profile/**").permitAll()
                .antMatchers("/swagger-ui.html", "/swagger-resources/**", "/webjars/**", "/*/api-docs", "/druid/**").permitAll()
                // 除上面外的所有请求全部需要鉴权认证
                .anyRequest().authenticated()
                .and()
                .headers().frameOptions().disable();
        // 添加Logout filter
        httpSecurity.logout().logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandler);
        // 添加JWT filter
        httpSecurity.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
        // 添加CORS filter
        httpSecurity.addFilterBefore(corsFilter, JwtAuthenticationTokenFilter.class);
        httpSecurity.addFilterBefore(corsFilter, LogoutFilter.class);
    }

    /**
     * 强散列哈希加密实现
     */
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder()
    {
        return new BCryptPasswordEncoder();
    }

    /**
     * 身份认证接口
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception
    {
        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
    }
}

token过滤器
直接拿ruoyi的把

package com.ruoyi.framework.security.filter;

import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;

/**
 * token过滤器 验证token有效性
 * 
 * @author ruoyi
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter
{
    @Autowired
    private TokenService tokenService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser) && StringUtils.isNull(SecurityUtils.getAuthentication()))
        {
            tokenService.verifyToken(loginUser);
            //三个参数的构造函数会将一个认证参数 set true,代表是已经认证过的。不然还会进入loadUserByUsername方法
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        chain.doFilter(request, response);
    }
}

退出登录

只需要把redis中的存放的用户信息删除即可,这样在token filter那一层获取不到redis缓存就会报异常。

自定义权限认证

先加上注解开启@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
常用就是@PreAuthorize这个注解了,代表在处理前校验。

自定义一个权限处理类,在权限验证方法中返回boolean值。

package com.fchan.service;

import com.fchan.entity.Role;
import com.fchan.security.model.MyUserDTO;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.stream.Collectors;

/**
 * ClassName: SpringSecurityPermissionService
 * Description:
 * date: 2022/11/14 20:52
 *
 * @author fchen
 */
@Service("ss")
public class SpringSecurityPermissionService {

    public boolean hasPermi(String permission){

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        MyUserDTO myUserDTO = (MyUserDTO) authentication.getPrincipal();

        return myUserDTO.getRoles().stream().map(it -> it.getId().toString()).collect(Collectors.toList()).contains(permission);

    }


}

controller中校验,这里的2就是自定义参数,和当前登录用户信息中的参数进行比较,符合要求就进行放行

@GetMapping("test")
@PreAuthorize("@ss.hasPermi('2')")
public Object test(){
    return "test success";
}

认证/授权失败异常处理

认证失败:实现org.springframework.security.web.AuthenticationEntryPoint接口可自定义认证失败
授权失败:实现org.springframework.security.web.access.AccessDeniedHandler接口可自定义授权失败

认证失败demo

package com.ruoyi.framework.security.handle;

import java.io.IOException;
import java.io.Serializable;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;

/**
 * 认证失败处理类 返回未授权
 * 
 * @author ruoyi
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint, Serializable
{
    private static final long serialVersionUID = -8970718410437077606L;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e)
            throws IOException
    {
        int code = HttpStatus.UNAUTHORIZED;
        String msg = StringUtils.format("请求访问:{},认证失败,无法访问系统资源", request.getRequestURI());
        renderString(response, JSON.toJSONString(AjaxResult.error(code, msg)));
    }


 /**
     * 将字符串渲染到客户端
     * 
     * @param response 渲染对象
     * @param string 待渲染的字符串
     */
    public static void renderString(HttpServletResponse response, String string)
    {
        try
        {
            response.setStatus(200);
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().print(string);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

}

鉴权失败(用户没有权限访问)
同样实现org.springframework.security.web.access.AccessDeniedHandler接口完成方法接口。

最后需要配置生效

 httpSecurity
            // CSRF禁用,因为不使用session
            .csrf().disable()
            // 禁用HTTP响应标头
            .headers().cacheControl().disable().and()
            // 认证失败处理类
            .exceptionHandling()
            .authenticationEntryPoint(authenticationEntryPointImpl)
            //鉴权失败
            .accessDeniedHandler(accessDeniedHandlerImpl)

spring security跨域允许


    /**
     * 跨域配置
     */
    @Bean
    public CorsFilter corsFilter()
    {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        // 设置访问源地址
        config.addAllowedOriginPattern("*");
        // 设置访问源请求头
        config.addAllowedHeader("*");
        // 设置访问源请求方法
        config.addAllowedMethod("*");
        // 有效期 1800秒
        config.setMaxAge(1800L);
        // 添加映射路径,拦截一切请求
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        // 返回新的CorsFilter
        return new CorsFilter(source);
    }


//需要添加到sprint security的拦截器之前生效才可以,这里是在自定义的token校验拦截和登出拦截之前
// 添加CORS filter
httpSecurity.addFilterBefore(corsFilter(), com.ruoyi.framework.security.filter.JwtAuthenticationTokenFilter.class);
httpSecurity.addFilterBefore(corsFilter(), org.springframework.security.web.authentication.logout.LogoutFilter.class);

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

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

相关文章

【MFC】打砖块小游戏(上)(5)

创建WIN32项目的时候&#xff0c;可以去掉勾选【空项目】可以减少工作量。 创建项目 文件-》新建-》 项目-》WIN32项目-》取消勾选空项目&#xff0c;完成创建 创建完成后&#xff0c;多出了很多文件&#xff0c;当然很多代码是前面已经手动写过了的&#xff1a; stdafx.h …

聚醚羰基铑功能化离子液体{[CH3O(CH2CH2O)nmim][Rhx(CO)y]}

聚醚羰基铑功能化离子液体{[CH3O(CH2CH2O)nmim][Rhx(CO)y]} 离子液体种类 目前研究较多的离子液体阳离子&#xff0c;根据有机母体的不同主要可分四种&#xff0c;即咪唑类离子[R1R3Im]、吡啶类离子[RPy]、烷基季铵类离子[NRxH4-x]以及烷基季膦类离子[PRxH4-x]。这四类阳离子…

【Designing ML Systems】第 9 章 :生产中的持续学习和测试

&#x1f50e;大家好&#xff0c;我是Sonhhxg_柒&#xff0c;希望你看完之后&#xff0c;能对你有所帮助&#xff0c;不足请指正&#xff01;共同学习交流&#x1f50e; &#x1f4dd;个人主页&#xff0d;Sonhhxg_柒的博客_CSDN博客 &#x1f4c3; &#x1f381;欢迎各位→点赞…

MySQL数据库的约束

文章目录一、约束是什么&#xff1f;二、约束的具体操作Not NULLUNIQUE约束的组合使用PRIMARY KEYDEFAULTFOREIGN KEY一、约束是什么&#xff1f; 约束就是&#xff0c;在创建表的时候&#xff0c;对表设置一些规则&#xff0c;只有满足这些规则&#xff0c;才可以插入数据&am…

【微服务】Nacos通知客户端服务变更以及重试机制

&#x1f496;Spring家族源码解析及微服务系列 ✨【微服务】Nacos服务发现源码分析 ✨【微服务】SpringBoot监听器机制以及在Nacos中的应用 ✨【微服务】Nacos客户端微服务注册原理流程 ✨【微服务】SpringCloud中使用Ribbon实现负载均衡的原理 ✨【微服务】SpringBoot启动流程…

字节一面后,我又看了一遍ThreadLocal核心原理

前言&#xff1a;上周在面试字节的时候&#xff0c;问到了ThreadLocal的核心原理&#xff0c;由于这个知识点当时有些淡忘&#xff0c;因此作此篇文章进行知识的记录&#xff0c;同时希望能够帮助到其他的小伙伴儿们。 本篇文章记录的基础知识&#xff0c;适合在学Java的小白&a…

动态 SQL

文章目录一、学习目的二、动态 SQL 中的元素三、条件查询操作四、更新操作五、复杂查询操作1.foreach 元素中的属性2.foreach 元素迭代数组3.foreach 元素迭代 List4.foreach 元素迭代 Map一、学习目的 在实际项目的开发中&#xff0c;开发人员在使用 JDBC 或其他持久层框架进…

【汇编 C++】多态底层---虚表、__vfptr指针

前言&#xff1a;如果对多态不太了解的话&#xff0c;可以看我的这篇文章《C多态》&#xff0c;另外本文中出现到的汇编代码&#xff0c;我都会予以解释&#xff0c;看不懂没关系&#xff0c;知道大概意思就行&#xff0c;能不讲汇编的地方我就不讲&#xff1b; 本文使用到的工…

networkx学习记录

networkx学习记录networkx学习记录1. 创建图表2. 节点3. 边4.检查图的元素5.从图中删除元素6.使用图构造函数7.访问边和邻居8.向图、节点和边添加属性9.有向图10. 绘制图形networkx学习记录 1. 创建图表 创建一个空图 import networkx as nx G nx.Graph()此时如果报以下错误…

HTML网页设计结课作业——11张精美网页 html+css+javascript+bootstarp

HTML实例网页代码, 本实例适合于初学HTML的同学。该实例里面有设置了css的样式设置&#xff0c;有div的样式格局&#xff0c;这个实例比较全面&#xff0c;有助于同学的学习,本文将介绍如何通过从头开始设计个人网站并将其转换为代码的过程来实践设计。 精彩专栏推荐&#x1f4…

学姐突然问我键盘怎么选?原来是为了这个...

前言&#xff1a; 上个星期学姐来问我该买啥键盘&#xff0c;说是自己用的笔记本的键盘实在是不太好用&#xff0c;很喜欢机械键盘的手感&#xff0c;但是常规的机械键盘有太大了而且声音十分大&#xff0c;对她们女生来说并不是很友好。于是我给她推荐了我现在正在用的这款键盘…

头歌-信息安全技术-Java生成验证码

头歌-信息安全技术-Java生成验证码一、第1关&#xff1a;使用Servlet生成验证码1、任务描述2、编程要求3、评测代码二、第2关&#xff1a;用户登录时校验验证码是否正确1、任务描述2、编程要求3、评测代码三、第3关&#xff1a;使用Kaptcha组件生成验证码1、任务描述2、编程要求…

2023年前端开发未来可期

☆ 对于很多质疑&#xff0c;很多不解&#xff0c;本文将从 △ 目前企业内前端开发职业的占比&#xff1b; △ 目前业内开发语言的受欢迎程度&#xff1b; △ 近期社区问答活跃度&#xff1b; 等维度来说明目前前端这个职业的所处位置。 ☆ 还有强硬的干货&#xff0c;通过深入…

跳槽前恶补面试题,成功上岸阿里,拿到33k的测开offer

不知不觉间&#xff0c;时间过得真快啊。作为一名程序员&#xff0c;应该都清楚每年的3、4月份和9、10月份都是跳槽的黄金季&#xff0c;各大企业在这段时间会大量招聘人才。在这段时间里&#xff0c;有人欢喜有人悲。想必各位在跳槽前都会做好充足的准备&#xff0c;同样做足了…

详细讲解网络协议:TCP和UDP什么区别?

该文章是学习了 B 站 up 主的视频做的总结&#xff0c;讲的很通俗易懂&#xff0c;首先感谢博主的分享。视频地址&#xff1a;https://www.bilibili.com/video/BV1kV411j7hA/?spm_id_from333.337.search-card.all.click&vd_source0a3d4c746a63d737330e738fa043eaf6 重新认…

【HDU No. 3567】八数码 II Eight II

【HDU No. 3567】八数码 II Eight II 杭电OJ 题目地址 【题意】 八数码&#xff0c;也叫作“九宫格”&#xff0c;来自一个古老的游戏。在这个游戏中&#xff0c;你将得到一个33的棋盘和8个方块。方块的编号为1&#xff5e;8&#xff0c;其中一块方块丢失&#xff0c;称之为“…

【python】基础复习

注&#xff1a;最后有面试挑战&#xff0c;看看自己掌握了吗 文章目录python的应用基础语法编码标识符python保留字第一个注释多行语句数字(Number)类型字符串(String)print 默认输出是换行的&#xff0c;如果要实现不换行需要在变量末尾加上 end""&#xff1a;impor…

猿创征文|在校大学生学习UI设计必备工具及日常生活中使用的软件

嗨&#xff0c;大家好&#xff0c;我是异星球的小怪同志 一个想法有点乱七八糟的小怪 如果觉得对你有帮助&#xff0c;请支持一波。 希望未来可以一起学习交流。 我是一名在校大二的学生&#xff0c;目前在学习关于UI设计方向的一些课程&#xff0c;平时会用到UI设计必备的工…

我终于读懂了适配器模式。。。

文章目录&#x1f5fe;&#x1f306;什么是适配器模式&#xff1f;&#x1f3ef;类适配器模式&#x1f3f0;对象适配器模式⛺️接口适配器模式&#x1f3ed;适配器模式在SpringMVC 框架应用的源码剖析&#x1f5fc;适配器模式的注意事项和细节&#x1f306;什么是适配器模式&am…

基于SDN环境下的DDoS异常攻击的检测与缓解--实验

基于SDN环境下的DDoS异常攻击的检测与缓解--实验基于SDN环境下的DDoS异常攻击的检测与缓解--实验1.安装floodlight2.安装sFlow-RT流量监控设备3.命令行安装curl工具4.构建拓扑5.DDoS 攻击检测6.DDoS 攻击防御7.总结申明&#xff1a; 未经许可&#xff0c;禁止以任何形式转载&am…