当前位置:   article > 正文

Springboot集成SpringSecurity过程中遇到的问题_在 spring boot 引入springsecurity依赖启动项目报错

在 spring boot 引入springsecurity依赖启动项目报错

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#/**");
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

原因:地址前去掉项目路径才能生效。如项目路径为“/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();
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

解决方法:
增加 .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();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

三、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;
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

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

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

@Bean
public HttpSessionEventPublisher httpSessionEventPublisher() 
{
    return new HttpSessionEventPublisher();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

七、重定向的次数过多
原因:
未将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()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号