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

2022-07-01 12:48:52

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

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

@Component@EnableWebSecuritypublicclassSpringSecurityConfigextendsWebSecurityConfigurerAdapter{//免登录的接口@Overridepublicvoidconfigure(WebSecurity web)throws Exception{
        web.ignoring().antMatchers("/testServer/login","/query/**","/NoAuthAPIs/**","/swagger-ui.html#/**");}}

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

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

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

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

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

publicclassCustomAuthenticationEntryPointimplementsAuthenticationEntryPoint{@Overridepublicvoidcommence(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=newCommonResult();
        noLoginResult.setResultCode("-2");
        noLoginResult.setResultMessage("please login!");
        out.write(newObjectMapper().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()

@Overrideprotectedvoidconfigure(HttpSecurity http)throws Exception{...      
        http.sessionManagement().maximumSessions(1);//限制登录数,单个用户能够存在的最大 session数
        http.csrf().disable()//关闭csrf跨域攻击防御.cors();//允许跨域访问}@Beanpublic CorsConfigurationSourcecorsConfigurationSource(){final CorsConfiguration configuration=newCorsConfiguration();//指定允许跨域的请求(*所有):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=newUrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);return source;}

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

http.sessionManagement().maximumSessions(1).maxSessionsPreventsLogin(true);@Beanpublic HttpSessionEventPublisherhttpSessionEventPublisher(){returnnewHttpSessionEventPublisher();}

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

//login接口白名单@Overridepublicvoidconfigure(WebSecurity web)throws Exception{
        web.ignoring().antMatchers("/testServer/login","/login");}//页面可匿访问....and().formLogin().loginPage("/login.html").and().authorizeRequests().antMatchers("/login.html").permitAll()
  • 作者:徒手千行代码无bug
  • 原文链接:https://blog.csdn.net/Kevin___________/article/details/104415282
    更新时间:2022-07-01 12:48:52