1. 首先添加-登陆成功处理类
package *******;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* @author
* @Description 是登陆成功处理类
*/
@Component("urlAuthenticationSuccessHandler")
public class UrlAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
Authentication authentication) throws IOException, ServletException {
// 认证成功后,相应前端json信息
String token = TokenUtils.createToken("***"); // 自定义token 生成类
Cookie cookie = new Cookie("token", token); // 将token放入cookie中
httpServletResponse.addCookie(cookie);
httpServletResponse.setHeader("Content-Type", "application/json;charset=utf-8");
httpServletResponse.setStatus(200);
PrintWriter writer = httpServletResponse.getWriter();
writer.write(ResultUtil.success("登陆成功").toString()); // ResultUtil 是自定义工具类,返回json字符串信息即可
writer.flush();
writer.close();
}
}
2. 注入登录成功处理类,并将登录成功的处理类放入http.formLogin().successHandler.successHandler(urlAuthenticationSuccessHandler)
package com.*.*.*.*;
import lombok.extern.slf4j.Slf4j;
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.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
/**
* @author
* @Description web 安全配置
*/
@Configuration
@EnableWebSecurity
@Slf4j
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
SelfUserDetailsService userDetailsService; // UserDetailsService 的实现类
@Autowired
private AuthenticationSuccessHandler urlAuthenticationSuccessHandler; // 注入登陆成功处理类
/**
* 登录认证
* @param auth 登陆管理器
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// 2. 采用数据库方式存储
auth.userDetailsService(userDetailsService);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin()
.successHandler(urlAuthenticationSuccessHandler)
.and()
.authorizeRequests() // 对请求授权
.anyRequest().authenticated()// 需要身份认证
;
}
}