Spring Security 身份驗證提供者

Spring Security
Remote
0
06:27 PM · Nov 29 ,2025

1. 概述

在本教程中,我們將學習如何設置 Spring Security 中的身份驗證提供者,相比於使用簡單的 UserDetailsService 方案,可以提供更大的靈活性。

2. 身份驗證提供者

Spring Security 提供多種執行身份驗證的選項。這些選項遵循簡單的合同:一個身份驗證提供者處理身份驗證請求, 並返回一個完全經過身份驗證的對象,並帶有完整的憑據。

標準且最常見的實現是 DaoAuthenticationProvider,它從簡單的只讀用户 DAO(UserDetailsService)檢索用户詳細信息。該用户詳細信息服務僅具有訪問用户名以便檢索完整的用户實體,對於大多數場景來説已經足夠。

更復雜的場景仍然需要訪問完整的 身份驗證請求才能執行身份驗證過程。例如,當對某些第三方服務(如 Crowd)進行身份驗證時用户名密碼從身份驗證請求中都需要

對於這些更高級的場景,我們需要定義一個自定義身份驗證提供者

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

    @Override
    public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
        final String name = authentication.getName();
        final String password = authentication.getCredentials().toString();
        if (!"admin".equals(name) || !"system".equals(password)) {
            return null;
        }
        return authenticateAgainstThirdPartyAndGetAuthentication(name, password);
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
}

在這裏,我們有一個通用的方法,它返回一個 身份驗證對象。它的實現可以根據我們想要執行的身份驗證方式而變化。例如,我們可以編寫一個固定憑據的方法:

private static UsernamePasswordAuthenticationToken authenticateAgainstThirdPartyAndGetAuthentication(String name, String password) {
    final List<GrantedAuthority> grantedAuths = new ArrayList<>();
    grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));
    final UserDetails principal = new User(name, password, grantedAuths);
    return new UsernamePasswordAuthenticationToken(principal, password, grantedAuths);
}

值得注意的是,我們還將一個權限添加到我們的 UserDetails對象中。在實際場景中,根據您的需要實現上述方法是必要的,因為短文可能不涵蓋所有情況。

3. 註冊身份驗證提供者

現在我們已經定義了身份驗證提供者,需要使用可用的命名空間在 XML 安全配置中指定它:

 <http use-expressions="true">
    <intercept-url pattern="/**" access="isAuthenticated()"/>
    <http-basic/>
</http>

<authentication-manager>
    <authentication-provider
      ref="customAuthenticationProvider" />
</authentication-manager>

4. Java 配置文件

接下來,我們將查看相應的 Java 配置文件:

@Configuration
@EnableWebSecurity
@ComponentScan("com.baeldung.security")
public class SecurityConfig {

    @Autowired
    private CustomAuthenticationProvider authProvider;

    @Bean
    public AuthenticationManager authManager(HttpSecurity http) throws Exception {
        AuthenticationManagerBuilder authenticationManagerBuilder = 
            http.getSharedObject(AuthenticationManagerBuilder.class);
        authenticationManagerBuilder.authenticationProvider(authProvider);
        return authenticationManagerBuilder.build();
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        return http.authorizeHttpRequests(request -> request.anyRequest()
                .authenticated())
            .httpBasic(Customizer.withDefaults())
            .build();
    }

在這裏,我們配置了所有請求的強制認證,並配置了 Http basic 認證。

5. 執行身份驗證

從客户端請求身份驗證與或不與此自定義身份驗證提供程序在後端使用基本相同。

我們將使用簡單的 curl 命令發送一個經過身份驗證的請求:

curl --header "Accept:application/json" -i --user user1:user1Pass 
    http://localhost:8080/spring-security-custom/api/foo/1

對於這個例子,我們使用基本身份驗證對 REST API 進行了保護。

並且我們從服務器那裏得到了預期的 200 OK 響應:

HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Set-Cookie: JSESSIONID=B8F0EFA81B78DE968088EBB9AFD85A60; Path=/spring-security-custom/; HttpOnly
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Sun, 02 Jun 2013 17:50:40 GMT

6. 結論

在本文中,我們探討了 Spring Security 中自定義身份驗證提供程序的示例。

user avatar
0 位用戶收藏了這個故事!
收藏

發佈 評論

Some HTML is okay.