SpringSecurity个性化用户认证流程

时间:2022-01-19 09:30:28

⒈自定义登录页面

 package cn.coreqi.security.config;

 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.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder; @Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Bean
public PasswordEncoder passwordEncoder(){
return NoOpPasswordEncoder.getInstance();
} @Override
protected void configure(HttpSecurity http) throws Exception {
//http.httpBasic() //httpBasic登录 BasicAuthenticationFilter
http.formLogin() //表单登录 UsernamePasswordAuthenticationFilter
//.loginPage("/coreqi-signIn.html") //指定登录页面
.loginPage("/authentication/require")
.loginProcessingUrl("/authentication/form") //指定表单提交的地址用于替换UsernamePasswordAuthenticationFilter默认的提交地址
.and()
.authorizeRequests() //对授权请求进行配置
.antMatchers("/coreqi-signIn.html").permitAll() //指定登录页面不需要身份认证
.anyRequest().authenticated() //任何请求都需要身份认证
.and().csrf().disable(); //禁用CSRF
//FilterSecurityInterceptor 整个SpringSecurity过滤器链的最后一环
}
}
 package cn.coreqi.security.controller;

 import cn.coreqi.security.support.SimpleResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException; @RestController
public class SecurityController { private Logger logger = LoggerFactory.getLogger(getClass()); //拿到引发跳转的请求
private RequestCache requestCache = new HttpSessionRequestCache(); //SpringSecurity执行身份认证跳转之前会将当前的请求缓存到HttpSessionRequestCache中
//我们可以通过HttpSessionRequestCache把之前缓存的请求拿出来。 private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); //Spring用于跳转的工具 /**
* 当需要身份认证时,跳转到这里
* @param request
* @param response
* @return
*/
@GetMapping("/authentication/require")
@ResponseStatus(code = HttpStatus.UNAUTHORIZED) //返回401状态码
public SimpleResponse requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {
SavedRequest savedRequest = requestCache.getRequest(request,response); //SavedRequest就是跳转前的请求
if(savedRequest != null){ //如果请求缓存存在的话
String target = savedRequest.getRedirectUrl(); //拿到引发跳转的请求URL
logger.info("引发跳转的请求URL是:" + target);
if(StringUtils.endsWithIgnoreCase(target,".html")){ //引发跳转的请求URL是否以html结尾
redirectStrategy.sendRedirect(request,response,"/coreqi-signIn.html"); //将请求跳转到指定的Url
}
}
return new SimpleResponse(401,"访问的服务需要身份认证,请引导用户到登陆页面",null);
}
}

⒉自定义登录成功处理

  默认情况下SpringSecurity登录成功了将会跳转到之前引发登录的那个请求上去,如果我们需要自定义登录成功后的处理过程,只需要实现AuthenticationSuccessHandler接口。(SpringSecurity默认的成功处理器是SavedRequestAwareAuthenticationSuccessHandler)

 package cn.coreqi.security.authentication;

 import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException; @Component("coreqiAuthenticationSuccessHandler")
public class CoreqiAuthenticationSuccessHandler implements AuthenticationSuccessHandler { private Logger logger = LoggerFactory.getLogger(getClass()); @Autowired
private ObjectMapper objectMapper; //将对象转换为Json的工具类,SpringMVC在启动的时候会自动为我们注册ObjectMapper
/**
*
* @param httpServletRequest 不知道
* @param httpServletResponse 不知道
* @param authentication Authentication接口是SpringSecurity的一个核心接口,它的作用是封装我们的认证信息,包含认证请求中的一些信息,包括认证请求的ip,Session是什么,以及认证用户的信息等等。
* @throws IOException
* @throws ServletException
*/
@Override
public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
logger.info("登录成功"); httpServletResponse.setContentType("application/json;charset=UTF-8");
httpServletResponse.getWriter().write(objectMapper.writeValueAsString(authentication));
}
}

配置

 package cn.coreqi.security.config;

 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.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler; @Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired
private AuthenticationSuccessHandler coreqiAuthenticationSuccessHandler; @Bean
public PasswordEncoder passwordEncoder(){
return NoOpPasswordEncoder.getInstance();
} @Override
protected void configure(HttpSecurity http) throws Exception {
//http.httpBasic() //httpBasic登录 BasicAuthenticationFilter
http.formLogin() //表单登录 UsernamePasswordAuthenticationFilter
//.loginPage("/coreqi-signIn.html") //指定登录页面
.loginPage("/authentication/require")
.loginProcessingUrl("/authentication/form") //指定表单提交的地址用于替换UsernamePasswordAuthenticationFilter默认的提交地址
.successHandler(coreqiAuthenticationSuccessHandler) //登录成功以后要用我们自定义的登录成功处理器,不用Spring默认的。
.and()
.authorizeRequests() //对授权请求进行配置
.antMatchers("/coreqi-signIn.html").permitAll() //指定登录页面不需要身份认证
.anyRequest().authenticated() //任何请求都需要身份认证
.and().csrf().disable(); //禁用CSRF
//FilterSecurityInterceptor 整个SpringSecurity过滤器链的最后一环
}
}

⒊自定义登录失败处理

只需要实现AuthenticationSuccessHandler接口即可。(默认为SimpleUrlAuthenticationFailureHandler)

 package cn.coreqi.security.authentication;

 import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component; import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException; @Component("coreqiAuthenticationFailureHandler")
public class CoreqiAuthenticationFailureHandler implements AuthenticationFailureHandler { private Logger logger = LoggerFactory.getLogger(getClass()); @Autowired
private ObjectMapper objectMapper; //将对象转换为Json的工具类,SpringMVC在启动的时候会自动为我们注册ObjectMapper /**
*
* @param httpServletRequest 不知道
* @param httpServletResponse 不知道
* @param e AuthenticationException对象包含了在认证过程中发生的错误产生的异常
* @throws IOException
* @throws ServletException
*/
@Override
public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
logger.info("登录失败"); httpServletResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); //500状态码
httpServletResponse.setContentType("application/json;charset=UTF-8");
httpServletResponse.getWriter().write(objectMapper.writeValueAsString(e));
}
}

配置

 package cn.coreqi.security.config;

 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.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler; @Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired
private AuthenticationSuccessHandler coreqiAuthenticationSuccessHandler; @Autowired
private AuthenticationFailureHandler coreqiAuthenticationFailureHandler; @Bean
public PasswordEncoder passwordEncoder(){
return NoOpPasswordEncoder.getInstance();
} @Override
protected void configure(HttpSecurity http) throws Exception {
//http.httpBasic() //httpBasic登录 BasicAuthenticationFilter
http.formLogin() //表单登录 UsernamePasswordAuthenticationFilter
//.loginPage("/coreqi-signIn.html") //指定登录页面
.loginPage("/authentication/require")
.loginProcessingUrl("/authentication/form") //指定表单提交的地址用于替换UsernamePasswordAuthenticationFilter默认的提交地址
.successHandler(coreqiAuthenticationSuccessHandler) //登录成功以后要用我们自定义的登录成功处理器,不用Spring默认的。
.failureHandler(coreqiAuthenticationFailureHandler) //自己体会把
.and()
.authorizeRequests() //对授权请求进行配置
.antMatchers("/coreqi-signIn.html").permitAll() //指定登录页面不需要身份认证
.anyRequest().authenticated() //任何请求都需要身份认证
.and().csrf().disable(); //禁用CSRF
//FilterSecurityInterceptor 整个SpringSecurity过滤器链的最后一环
}
}