需要多少配置?
- UserDetailsService、UserDetailsPasswordService
- Filter (AbstractAuthenticationProcessingFilter)
- Paramter
- FilterProcessesUrl(“/login”)
- RememberMe
- AuthenticationManager
- AuthenticationSuccess/FailureHandler
- HttpSecurity
- authorizeRequests // antMathers / mvcMathers().permitAll() anyRequest.authenticated()
- formLogin()
- Logout()
- RememberMe // RememberMeService always paramter
- csrf() // csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())); // 将令牌保存到 cookie 中(并允许前端获取)
- addFilterAt()
- exceptionHandling() // authenticationEntryPoint / accessDeniedHandler
- sessionManagement() // expiredSessionStrategy maximumSessions maxSessionsPreventsLogin
- authenticationManager
- authenticationProvider
- WebSecurityCustomizer // web.ignoring().antMatchers
- AuthenticationManagerBuilder.userDetailsService(xxService)
- @Autowired authenticationManagerBean()
package com.armin.security.config;
import com.armin.security.security.CaptchaAuthenticationProvider;
import com.armin.security.security.filter.CaptchaAuthenticationFilter;
import com.armin.security.service.CaptchaService;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.RegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
@Slf4j
@Configuration
@AllArgsConstructor
public class SecurityConfiguration {
final CaptchaService captchaService;
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.antMatcher("
@Bean
public AbstractAuthenticationProcessingFilter loginFilter() {
// final LoginFilter loginFilter = new LoginFilter(); // 配置无关
// loginFilter.setUsernameParameter("uname"); // 配置无关
// loginFilter.setPasswordParameter("passwd"); // 配置无关
final CaptchaAuthenticationFilter loginFilter =
new CaptchaAuthenticationFilter(); // 配置 authenticationManager
// loginFilter.setFilterProcessesUrl("/doLogin"); // 这里设置会进行顶替
// loginFilter.setRememberMeServices(
// rememberMeServices()); // 前后端分离后,更改了获取方式后,存放也需要同步设置(2/2)
// 指定认证管理器
loginFilter.setAuthenticationManager(
new ProviderManager(Collections.singletonList(captchaAuthenticationProvider())));
// 指定成功时处理
loginFilter.setAuthenticationSuccessHandler(
(request, response, authentication) -> {
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setStatus(HttpStatus.OK.value());
Map data = new HashMap<>();
data.put("userInfo", authentication.getPrincipal());
data.put("msg", "登陆成功");
PrintWriter out = response.getWriter();
ObjectMapper objectMapper = new ObjectMapper();
out.write(objectMapper.writeValueAsString(data));
out.flush();
out.close();
});
// 指定失败时处理
loginFilter.setAuthenticationFailureHandler(
(request, response, exception) -> {
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
Map data = new HashMap<>();
data.put("msg", "登陆失败:" + exception.getMessage());
response.setStatus(HttpStatus.UNAUTHORIZED.value());
PrintWriter out = response.getWriter();
ObjectMapper objectMapper = new ObjectMapper();
out.write(objectMapper.writeValueAsString(data));
out.flush();
out.close();
});
return loginFilter;
}
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
// 仅仅作为演示
return (web) ->
web.ignoring().antMatchers("/withdraw/info", "/withdraw/hello", "/captcha
@Bean(name = "captchaUserDetailsService")
public UserDetailsService captchaUserDetailsService() {
// 验证码登陆后密码无意义了但是需要填充一下
return username ->
User.withUsername(username)
.password("TEMP")
// todo 这里权限 你需要自己注入
.authorities(AuthorityUtils.createAuthorityList("ROLE_ADMIN", "ROLE_APP"))
.build();
}
@Bean
CaptchaAuthenticationProvider captchaAuthenticationProvider() {
// 一个 Provider 需要配置一个 userDetailsService. 验证 service 这里使用到就放入
return new CaptchaAuthenticationProvider(captchaUserDetailsService(), captchaService);
}
@Bean
RegistrationBean corsFilter() {
FilterRegistrationBean registrationBean = new FilterRegistrationBean<>();
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedHeaders(Collections.singletonList("*"));
configuration.setAllowedMethods(Collections.singletonList("*"));
configuration.setAllowedOrigins(Collections.singletonList("*"));
configuration.setMaxAge(3600L);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedHeaders(Collections.singletonList("*"));
configuration.setAllowedMethods(Collections.singletonList("*"));
configuration.setAllowedOrigins(Collections.singletonList("*"));
configuration.setMaxAge(3600L);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("
public class CaptchaAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
public static final String SPRING_SECURITY_FORM_PHONE_KEY = "phone";
public static final String SPRING_SECURITY_FORM_CAPTCHA_KEY = "captcha";
private static final AntPathRequestMatcher DEFAULT_ANT_PATH_REQUEST_MATCHER =
new AntPathRequestMatcher("/captchaLogin", "POST");
public CaptchaAuthenticationFilter() {
super(DEFAULT_ANT_PATH_REQUEST_MATCHER);
}
public Authentication attemptAuthentication(
HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException {
if (!request.getMethod().equals("POST")) {
throw new AuthenticationServiceException(
"Authentication method not supported: " + request.getMethod());
}
String phone = obtainPhone(request);
phone = (phone != null) ? phone : "";
phone = phone.trim();
String captcha = obtainCaptcha(request);
captcha = (captcha != null) ? captcha : "";
CaptchaAuthenticationToken authRequest = new CaptchaAuthenticationToken(phone, captcha);
// Allow subclasses to set the "details" property
setDetails(request, authRequest);
return this.getAuthenticationManager().authenticate(authRequest);
}
@Nullable
protected String obtainCaptcha(HttpServletRequest request) {
return request.getParameter(SPRING_SECURITY_FORM_CAPTCHA_KEY);
}
@Nullable
protected String obtainPhone(HttpServletRequest request) {
return request.getParameter(SPRING_SECURITY_FORM_PHONE_KEY);
}
protected void setDetails(HttpServletRequest request, CaptchaAuthenticationToken authRequest) {
authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
}
}



