栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring Security新版配置

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring Security新版配置

配置

需要多少配置?

  1. UserDetailsService、UserDetailsPasswordService
  2. Filter (AbstractAuthenticationProcessingFilter)
    1. Paramter
    2. FilterProcessesUrl(“/login”)
    3. RememberMe
    4. AuthenticationManager
    5. AuthenticationSuccess/FailureHandler
  3. HttpSecurity
    1. authorizeRequests // antMathers / mvcMathers().permitAll() anyRequest.authenticated()
    2. formLogin()
    3. Logout()
    4. RememberMe // RememberMeService always paramter
    5. csrf() // csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())); // 将令牌保存到 cookie 中(并允许前端获取)
    6. addFilterAt()
    7. exceptionHandling() // authenticationEntryPoint / accessDeniedHandler
    8. sessionManagement() // expiredSessionStrategy maximumSessions maxSessionsPreventsLogin
    9. authenticationManager
    10. authenticationProvider
  4. WebSecurityCustomizer // web.ignoring().antMatchers
  5. AuthenticationManagerBuilder.userDetailsService(xxService)
  6. @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));
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/950704.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号