Springboot集成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#/**");
    }
}

原因:地址前去掉项目路径才能生效。如项目路径为“/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()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值