Spring Security登录配置文件讲解

spring security的登录文件一般会自己重新定义,重新里面的方法 configure,设置方法参数属性,达到重新自定意拦截登录以及重定向方法的作用。
方法参数为 HttpSecurity http

	//设置表单提交
	http.formLogin().
		//重新定义表单的username接受值的key
		usernameParameter("name").
		//重新定义表单的password接受值的key
		passwordParameter("pass").
		//当发现/login为登录时,必须和表单提交的地址一致,去执行UserDateilsServiceImpl
		loginProcessingUrl("/login").
		//自定义登录页面
		loginPage("/login.html").
		//登录成功后跳转页面,POST请求
		successForwardUrl("toMain").
		//登录成功后的处理器,不能和successForwardUrl共存
		successHandler(new MyAuthenticationSuccessHandler("自定西成功路径")).
		//登录失败跳转路径,POST请求
		failureForward("/toError").
		//登录失败后处理器,不能和failuerForward共存
		failureHandler(new MyAuthenticationFailureHandler("自定失败处理页面路径.html"));

	//请求拦截的配置
	//授权认证
	http.authorizeRequests()
		//登录失败页面不需要认证拦截
		.antMatchers("/error.html").permitAll()
		//去登陆页面不需要认证拦截
		.antMatchers("/login.html").permitAll()
		//除了登陆和登陆出错的页面,其他的请求都应该被拦截,需要认证才能访问
		.anyRequest().authenticated();
		
	//关系CSRF防护
	http.csrf().disable();

	//自定义错误信息以及返回的状态码和描述
	htt.exceptionHandling()
		.authenticationEntryPoint(authenticationErrorHandler)
		.accessDeniedHandler(jwtAccessDeniedHandler)

MyAuthenticationSuccessHandler和MyAuthenticationFailureHandler是自定义的跳转类,需要实现对应的AuthenticationSuccessHandler和AuthenticationFailureHandler里面的方法进行重写。

authenticationErrorHandler和jwtAccessDeniedHandler 都是实现对应方法进行重写,已jwtAccessDeniedHandler 错误的重现代码示例:

@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException authException) throws IOException {
        // 当用户尝试访问安全的REST资源而不提供任何凭据时,将调用此方法发送401 响应
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException==null?"Unauthorized":authException.getMessage());
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值