美文网首页
SpringSecurity(二) 表单认证-个性化自定义(待整

SpringSecurity(二) 表单认证-个性化自定义(待整

作者: 8813d76fee36 | 来源:发表于2017-11-15 17:02 被阅读40次

自定义登录页面

在自定义的WebSecurityConfigurerAdapter的子类重写的configure方法中添加.loginPage(String url)方法指明登录页的路径。
由于登录页不需要身份验证,所以配置不认证该url。

image.png

自定义登录成功处理

自定义类实现org.springframework.security.web.authentication.AuthenticationSuccessHandler,并重写其onAuthenticationSuccess()方法

image.png
该方法接收一个Authentication接口实现对象,该对象封装了认证信息。
可以将该对象以json方式发送到前台。
@Component(value = "imoocAuthenticationSuccessHandler")
public class ImoocAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest,
                                        HttpServletResponse httpServletResponse,
                                        Authentication authentication) throws IOException, ServletException {

        httpServletResponse.setContentType("application/json; charset=utf-8");
        httpServletResponse.getWriter().write(objectMapper.writeValueAsString(authentication));
    }
}
image.png

配置successHandler


image.png

自定义登录错误处理

自定义类实现AuthenticationFailureHandler,并重写其 onAuthenticationFailure方法

image.png

该方法接收一个AuthenticationException,封装了认证错误信息。

@Component(value = "imoocAuthenticationFailureHandler")
public class ImoocAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest,
                                        HttpServletResponse httpServletResponse,
                                        AuthenticationException e) throws IOException, ServletException {
        httpServletResponse.setContentType("application/json; charset=utf-8");
        httpServletResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); //500错误信息
        httpServletResponse.getWriter().write(objectMapper.writeValueAsString(e));
    }
}

配置失败处理器

image.png
若要使用SpringSecurity默认的成功处理方式,则继承SavedRequestAwareAuthenticationSuccessHandler
默认认证失败的处理类SimpleUrlAuthenticationFailureHandler

相关文章

网友评论

      本文标题:SpringSecurity(二) 表单认证-个性化自定义(待整

      本文链接:https://www.haomeiwen.com/subject/rlgcvxtx.html