【Spring Security + OAuth2 + JWT入门到实战】5. 自定义登录成功处理

配置系统参数

hk:
  security:
    browser:
      loginSucess: /index #登录成功跳转
      loginType: JSON #登录成功 失败返回值类型
#      loginPage: /demoLogin.html  #登录页面

改造BrowserProperties方法

package com.spring.security.properties;

import lombok.Data;

/**
 * 浏览器的属性
 */
@Data
public class BrowserProperties {

    /**
     * 登录页面   默认登录页signIn.html
     */
    private String loginPage = "/signIn.html";

    /**
     * 登录成功
     */
    private String loginSucess = "/index";


    /**
     * 登录成功 失败返回值类型
     */
    private LoginType loginType = LoginType.JSON;
}

创建LoginType枚举

package com.spring.security.properties;

/**
 * 登录类型
 *
 */
public enum LoginType {
    REDIRECT,

    JSON
}

创建登录成功Handler

在imooc-security-browser项目创建控制器

package com.spring.security.authentication;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.spring.security.properties.LoginType;
import com.spring.security.properties.SecurityProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

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

/**
 * 认证成功处理程序
 */
@Component
public class HkAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Autowired
    private SecurityProperties securityProperties;
    @Autowired
    private ObjectMapper mapper;

    /**
     * 身份验证成功
     *
     * @param request        请求
     * @param response       响应
     * @param authentication 身份验证
     * @throws java.io.IOException      IOException
     * @throws ServletException Servlet异常
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //判断配置的返回类型
        if (LoginType.JSON.equals(securityProperties.getBrowser().getLoginType())) {
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(mapper.writeValueAsString(authentication));
        } else {
            redirectStrategy.sendRedirect(request, response, securityProperties.getBrowser().getLoginSucess());
        }

    }
}

改造BrowserSecurityConfig类

package com.spring.security;

import com.spring.security.authentication.HkAuthenticationSuccessHandler;
import com.spring.security.properties.SecurityProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private SecurityProperties securityProperties;

    @Autowired
    private HkAuthenticationSuccessHandler hkAuthenticationSuccessHandler;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //配置
        http
                .formLogin()
                .loginPage("/authentication/require")//登录页面路径
                // 处理登录请求路径
                .loginProcessingUrl("/authentication/form")
                .successHandler(hkAuthenticationSuccessHandler) // 处理登录成功
                .and()
                .authorizeRequests() // 授权配置
                //不需要认证的路径
                .antMatchers("/authentication/require","/signIn.html",securityProperties.getBrowser().getLoginPage()).permitAll()
                .anyRequest() // 所有请求
                .authenticated() // 都需要认证
                .and().csrf().disable();
    }
}

修改demo项目HelloController类添加index方法:

    @GetMapping("index")
    public String index() {
        return "登录成功跳转";
    }

现在系统配置返回JSON启动项目访问:http://127.0.0.1:8080/index.html

登录成功返回:

修改系统配置loginType: REDIRECT

现在系统配置返回REDIRECT启动项目访问:http://127.0.0.1:8080/index.html

登录成功返回: