Springboot集成SpringSecurity过程中遇到的问题

2023-05-16

Spring Security 开发文档:https://www.springcloud.cc/spring-security-zhcn.html

一、配置的免登录访问接口不生效。

@Component
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter 
{
	
    //免登录的接口
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/testServer/login", "/query/**", "/NoAuthAPIs/**", "/swagger-ui.html#/**");
    }
}

原因:地址前去掉项目路径才能生效。如项目路径为“/testServer”,那么配置的“/testServer/query”是不会生效的。

二、访问接口如果未登录如何返回自定义数据而不是跳转到登录页面\

    /**
     * 权限核心配置
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //基础设置
        http.httpBasic()//配置HTTP基本身份验证
            .and()
                .authorizeRequests()
                .anyRequest().authenticated()//所有请求都需要认证
            .and()
                .formLogin()//登录表单
                .loginProcessingUrl("/login")//登录验证url    
                .successHandler(loginSuccessHandler)//成功登录处理器
                .failureHandler(loginFailureHandler)//失败登录处理器
                .permitAll()//登录成功后有权限访问所有页面
            .and().exceptionHandling().authenticationEntryPoint(new CustomAuthenticationEntryPoint())
            .and().csrf().disable();//关闭csrf跨域攻击防御

        http.logout()
        	.logoutUrl("/logout")
        	.permitAll()
        	.and().csrf().disable();
    }

解决方法:
增加 .and().exceptionHandling().authenticationEntryPoint(new CustomAuthenticationEntryPoint()),
CustomAuthenticationEntryPoint代码如下:
其中CommonResult是一个JSON对象,使用的是阿里的fastjson。

public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint 
{
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {

        response.setStatus(200);
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        CommonResult noLoginResult = new CommonResult();
        noLoginResult.setResultCode("-2");
        noLoginResult.setResultMessage("please login!");
        out.write(new ObjectMapper().writeValueAsString(noLoginResult));
        out.flush();
        out.close();
    }
}

三、SpringSecurity登陆时默认开启CSRF_Token校验,如何关闭。
代码同二
解决方法:
增加.and().csrf().disable();//关闭csrf跨域攻击防御。

四:角色配置后仍然返回403
原因及解决方法:
版本原因:Spring Boot 2.0
角色名必须要 ROLE_ 前缀, 因为 hasRole(“USER”)判断时会自动加上ROLE_前缀变成 ROLE_USER
在给用户赋权限时,数据库存储必须是完整的权限标识ROLE_USER

五、支持跨域访问
增加http.cors()和public CorsConfigurationSource corsConfigurationSource()


    @Override
    protected void configure(HttpSecurity http) throws Exception { 
    	...      
        http.sessionManagement().maximumSessions(1);//限制登录数,单个用户能够存在的最大 session数
        http.csrf().disable()//关闭csrf跨域攻击防御
        	.cors();//允许跨域访问
    }
    
    @Bean
    public CorsConfigurationSource corsConfigurationSource() 
    {
        final CorsConfiguration configuration = new CorsConfiguration();
        //指定允许跨域的请求(*所有):http://wap.ivt.guansichou.com
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH"));
        // setAllowCredentials(true) is important, otherwise:
        // The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
        configuration.setAllowCredentials(true);
        // setAllowedHeaders is important! Without it, OPTIONS preflight request
        // will fail with 403 Invalid CORS request
        configuration.setAllowedHeaders(Arrays.asList("Authorization", "Cache-Control", "X-User-Agent", "Content-Type"));
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

六、用户登出后无法登录
修改增加以下代码:

http.sessionManagement().maximumSessions(1).maxSessionsPreventsLogin(true);

@Bean
public HttpSessionEventPublisher httpSessionEventPublisher() 
{
    return new HttpSessionEventPublisher();
}

七、重定向的次数过多
原因:
未将login接口或页面设置为免登录访问。这样在访问时会自动跳转到登陆页面,而登陆页面未设置可匿访问,就会反复跳转导致死循环。
解决办法(2种场景):
将/login或login.html设置为可匿访问(若无登录页面只将/login加入可匿白名单即可),增加代码:

	//login接口白名单
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/testServer/login", "/login");
    }

	//页面可匿访问
	...
	.and()
	.formLogin()
	.loginPage("/login.html")
	.and()
	.authorizeRequests()
	.antMatchers("/login.html").permitAll()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Springboot集成SpringSecurity过程中遇到的问题 的相关文章

随机推荐

  • Nx C++程序使用spdlog库进行日志存储

    1 spdlog简介 spdlog是一个开源的日志库 xff0c 在github上有 代码见这里 xff0c 文档这里 C 43 43 语言的 xff0c 支持Linux windows等系统 csdn上也有许多介绍 xff0c 这里列举两
  • C++下的Boost库

    1 介绍 xff08 引子网络 xff09 Boost库是为C 43 43 语言标准库提供扩展的一些C 43 43 程序库的总称 xff0c 由Boost社区组织开发 维护 Boost库可以与C 43 43 标准库完美共同工作 xff0c
  • Opencv之边界跟踪

    问题描述 一般是将二值化后的图像进行边界的提取 需要说明的是这个提取不是简单的找到边界 xff0c 而是按照顺序的找出来 即边界上的点是按照邻接关系依次给出 相关算法 xff08 1 xff09 这里解释 xff1a https blog
  • OpenCV之滤波

    图像滤波 xff0c 指在尽量保留图像细节特征的条件下对目标图像的噪声进行抑制 xff0c 是图像预处理中不可缺少的操作 xff0c 其处理效果的好坏将直接影响后续图像处理和分析的准确性 这里有个概述 xff0c 很好的 xff1a Ope
  • C++文件读写

    这个不错 xff1a C 43 43 文件读写详解 xff08 ofstream ifstream fstream xff09 C 43 43 文件读写详解 xff08 ofstream ifstream fstream xff09 c 4
  • python及其工具

    目录 1 conda xff1a 包管理器2 Anoconda xff1a 开源的包 环境管理器3 labelme4 tensorflow5 cuda和cudnn6 使用yml文件创建环境并安装文件6 1 yml文件由来6 2 如何获得ym
  • C++之文件操作移动、复制、重命名

    1 C 43 43 笔记之CopyFile和MoveFile的使用 2 删除和重命名 include lt fstream gt include lt windows h gt 与opencv的命名空间CV有冲突 xff0c 不能在一个文件
  • (转)C#数字转固定长度的字符串

    转 C 数字转固定长度的字符串
  • 进程监视工具

    Process Monitor 搜索能下到 xff0c 记下 xff0c 以后用 Process Monitor分析某个应用行为 Process Monitor 系统进程监视器 介绍教程 Using Process Monitor 帮助文档
  • UML建模工具Enterprise Architect(EA) -- 安装及简单使用

    目录 一 什么是EA xff1f 二 安装EA 三 为什么要学会用EA 四 创建EA工程 五 创建类视图 xff0c 构建类和接口 六 选中模型目录 xff0c 自动检出Java代码 七 构建内部类 八 趁热打铁 xff0c 构建数据表视图
  • SVN目录结构与分支等

    TortoiseSVN打分支 合并分支 切换分支 SVN创建分支 合并分支 切换分支
  • WPF上下标

    这里有个介绍的文章 xff1a 定义显示的上标和下标 里面介绍了三种方法 我之前有的是这个方法 xff1a Typography Variants 61 Superscript xff0c 如下所示 xff1a lt TextBlock g
  • [WPF] HamburgerMenu

    有两个库支持的 xff1a Metro App库中的 VS自己的控件 xff1a https docs microsoft com zh cn windows communitytoolkit archive hamburgermenu
  • 面积误差三种计算表达的比较

    引自 xff1a 面积误差三种计算表达的比较 有三种理论 xff0c 最基本的经典的 xff0c 引用一个吧 xff1a 网上有个题目 xff0c 求桌面面积的测量结果 桌面为矩形 用米尺测量 xff0c 长L为100 0 cm xff0c
  • 【转】WPF:Canvas中元素的定位

    概述 xff1a Canvas中的元素的大小和位置都是相对于Canvas容器的 xff0c 他的左上角为原点 xff0c 长度也是相对于他的 WPF xff1a Canvas中元素的定位 https blog csdn net chz cs
  • 【转】C#中计时

    一般可以用Environment TickCount xff0c 但是25天后会翻转 有很多 xff0c 见下面两个转的 C 中精确计时的一点收获 https www cnblogs com jintianhu archive 2010 0
  • 利用python分析微信聊天记录

    文章目录 前言一 任务分析二 工具三 步骤1 数据获取获取DB计算密码导出数据库 2 数据清洗 xff08 具体方法以后补充 xff09 3 数据分析 前言 昨天跟女朋友讨论谁给对方发的消息比较多 xff0c 两人各执一词 xff0c 事实
  • C++学习之模板

    文章目录 xff1a 一 模板 二 函数模板 三 类模板 一 模板 模板 也称泛型编程 泛型编程 xff1a 编写与类型无关的通用代码 xff0c 是代码复用的一种手段 模板是泛型编程的基础 在这之前我们可以利用C 43 43 的函数重载来
  • ROS2 创建python包

    1 创建python包 ros2 pkg create build type ament python span class token string 39 demo 39 span dependencies rclpy 以上指令为创建一个
  • Springboot集成SpringSecurity过程中遇到的问题

    Spring Security 开发文档 xff1a https www springcloud cc spring security zhcn html 一 配置的免登录访问接口不生效 span class token annotatio