中文字幕精品亚洲无线码二区,国产黄a三级三级三级看三级,亚洲七七久久桃花影院,丰满少妇被猛烈进入,国产小视频在线观看网站

springboot~3.x版本的認證邏輯

在 Spring Boot 3.4.x 中,HttpSecurityand() 方法已經被標記為過時,因此我們需要采用新的 Lambda 風格 API 來配置安全性。你可以將 exceptionHandling() 移到 HttpSecurity 的頂層配置中,而不是在 authorizeHttpRequests 的內部。

authenticationEntryPoint和accessDeniedHandler的自定義

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import java.io.IOException;

public class CustomAccessDeineHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request,
                       HttpServletResponse response,
                       AccessDeniedException accessDeniedException) throws IOException {
        response.setContentType("application/json");
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        response.getWriter().write("{\"error\": \"forbidden\", \"message\": \"" + accessDeniedException.getMessage() + "\"}");

    }

}

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import java.io.IOException;

/**
 * 默認的認證入口點,當用戶未通過認證時會觸發此類,返回401狀態碼和錯誤信息。
 * @author lind
 * @date 2025/5/28 16:59
 * @since 1.0.0
 */
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException authException) throws IOException {
        response.setContentType("application/json");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.getWriter().write("{\"error\": \"Unauthorized\", \"message\": \"" + authException.getMessage() + "\"}");
    }
}

HandlerConfig注冊bean

@Configuration
public class HandlerConfig {
    @Bean
    @ConditionalOnMissingBean
    AuthenticationEntryPoint authenticationEntryPoint() {
        return new CustomAuthenticationEntryPoint();
    }

    @Bean
    @ConditionalOnMissingBean
    public AccessDeniedHandler accessDeniedHandler() {
        return new CustomAccessDeineHandler();
    }
}

WebSecurityConfig代碼

@EnableWebSecurity
public class WebSecurityConfig {

    private UaaProperty uaaProperty;
    private AuthenticationEntryPoint authenticationEntryPoint;
    private AccessDeniedHandler accessDeniedHandler;

    public WebSecurityConfig(UaaProperty uaaProperty, AuthenticationEntryPoint authenticationEntryPoint, AccessDeniedHandler accessDeniedHandler) {
        this.uaaProperty = uaaProperty;
        this.authenticationEntryPoint = authenticationEntryPoint;
        this.accessDeniedHandler = accessDeniedHandler;
    }

    @Bean
    public JwtAuthenticationFilter jwtAuthenticationFilter() {
        return new JwtAuthenticationFilter(uaaProperty);
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        Set<String> set = new HashSet<>();
        if (uaaProperty.getPermitUrl() != null && uaaProperty.getPermitUrl().length > 0) {
            Collections.addAll(set, uaaProperty.getPermitUrl());
        }

        http.csrf(csrf -> csrf.disable())
                .authorizeHttpRequests(authorize -> authorize
                        .requestMatchers(set.toArray(new String[]{})).permitAll()
                        .anyRequest().authenticated()
                )
                .exceptionHandling(exceptionHandling ->
                        exceptionHandling
                                .authenticationEntryPoint(authenticationEntryPoint)
                                .accessDeniedHandler(accessDeniedHandler)
                )
                .addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }
}

JwtAuthenticationFilter實現自定義驗證邏輯

public class JwtAuthenticationFilter extends OncePerRequestFilter {

    // 配置白名單策略,不走當前doFilterInternal
    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) {
        
    }
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
                
    }
}

新版3.x的SPI風格自動裝配

  • resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
com.xxx.uaa.keycloak.config.UaaProperty
com.xxx.uaa.keycloak.config.WebSecurityConfig
com.xxx.uaa.keycloak.config.HandlerConfig

關鍵點解釋

  1. Lambda 風格 API:使用 exceptionHandling(exceptionHandling -> ...) 的方式來設置 authenticationEntryPointaccessDeniedHandler,這符合(he)新(xin)的配置(zhi)風格,避(bi)免了使用過時(shi)的方法(fa)。

  2. 結構清晰:通過這種方法(fa),你(ni)的代碼結構更加清晰,邏輯分離也(ye)更明顯。

  3. 保持原有邏輯:其(qi)余部分的(de)(de)邏(luo)輯(ji)保持不變,仍然可以根據需(xu)要添加其(qi)他的(de)(de)配置。

注意事項

  • 確保你的 Spring Security 版本已經更新到 5.4 或更高版本,以支持這種新的配置方式。
  • 如果你有其他的異常處理或安全配置,也可以在同一鏈中繼續添加。
posted @ 2025-05-29 08:45  張占嶺  閱讀(111)  評論(0)    收藏  舉報