Spring security笔记4/4: 自定义成功和失败

自定义成功和失败

仍是在以前示例的基础上,将认证成功跳转页面,修改成认证成功返回数据html

实现步骤

1. 复制上一示例的源码

重命名包名 case3 为 case4java

重命名 Case3Application.java 为 Case4Application.javaweb

2. 在 WebSecurityConfig 中配置登陆页

在 config(HttpSecurity http) 方法中对 formLogin 选项进行配置。须要包含如下设置:算法

  • 建立 SuccessHandler 实现 AuthenticationSuccessHandler 接口,并实现 onAuthenticationSuccess 方法,自定义返回内容;
  • 建立 FailureHandler 实现 AuthenticationFailureHandler 接口,并实现 onAuthenticationFailure 方法,自定义返回内容;
  • 在 formLogin 配置项上增长 successHandler 和 failureHandler 配置

相关代码以下:spring

package net.txt100.learn.springsecurity.base.case4.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Title: WebSecurityConfig
 * Package: net.txt100.learn.springsecurity.base.case2.config
 * Creation date: 2019-08-11
 * Description:
 *
 * @author <a href="zgjt_tongl@thunis.com">Tonglei</a>
 * @since 1.0
 */
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder() {
        // 配置密码的保护策略,spring security 默认使用 bcrypt 加密算法。
        // 此处只要显式声明 BCryptPasswordEncoder Bean 便可
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        AuthenticationSuccessHandler successHandler = new AuthenticationSuccessHandler() {
            @Override
            public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
                response.setContentType("application/json;charset=UTF-8");
                JSON.writeJSONString(response.getOutputStream(), authentication);
            }
        };

        AuthenticationFailureHandler failureHandler = new AuthenticationFailureHandler() {
            @Override
            public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
                response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
                response.setContentType("application/json;charset=UTF-8");
                JSON.writeJSONString(response.getOutputStream(), exception);
            }
        };

        http
            .csrf().disable() // 关闭 CSRF 保护功能,不然不支持 Post 请求
            .authorizeRequests() // 针对 HttpServletRequest 进行安全配置
                .antMatchers("/login.html").permitAll() // login.html 页面无需登陆便可访问
                .anyRequest().authenticated() // 对全部 Request 均需安全认证
            .and().formLogin()
                .successHandler(successHandler)
                .failureHandler(failureHandler)
            .and().httpBasic(); // 定义如何验证用户,此项表明弹出浏览器认证窗口
    }
}

3. 登陆测试

  1. 尝试认证失败,此时返回以下 (不一样浏览器环境效果可能不一样)

  1. 尝试认证成功,此时返回以下

总结

经过修改 formLogin 配置,能够让认证中心提供更丰富的返回内容。json

相关文章
相关标签/搜索