Spring Security認證提供程式

程式猿Knight發表於2019-05-18

1.簡介

本教程將介紹如何在Spring Security中設定身份驗證提供程式,與使用簡單UserDetailsService的標準方案相比,提供了額外的靈活性

2. The Authentication Provider

Spring Security提供了多種執行身份驗證的選項 - 所有這些都遵循簡單的規範 - 身份驗證請求由Authentication Provider處理,並且返回具有完整憑據的完全身份驗證的物件。

標準和最常見的實現是DaoAuthenticationProvider - 它從一個簡單的只讀使用者DAO檢索使用者詳細資訊 - UserDetailsService。此UserDetailsService只能訪問使用者名稱,用來檢索完整的使用者實體 - 在很多情況下,這就足夠了。

更多常見的場景仍然需要訪問完整的身份驗證請求才能執行身份驗證過程。例如,在針對某些外部第三方服務(例如Crowd)進行身份驗證時,將需要來自身份驗證請求的使用者名稱和密碼。

對於這些更高階的方案,我們需要定義自定義身份驗證提供程式:

@Component
public class CustomAuthenticationProvider
  implements AuthenticationProvider {
 
    @Override
    public Authentication authenticate(Authentication authentication) 
      throws AuthenticationException {
  
        String name = authentication.getName();
        String password = authentication.getCredentials().toString();
         
        if (shouldAuthenticateAgainstThirdPartySystem()) {
  
            // use the credentials
            // and authenticate against the third-party system
            return new UsernamePasswordAuthenticationToken(
              name, password, new ArrayList<>());
        } else {
            return null;
        }
    }
 
    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(
          UsernamePasswordAuthenticationToken.class);
    }
}

請注意,在返回的Authentication物件上設定的授予許可權是空的 - 這是因為許可權當然是特定於應用程式的

3.註冊Authentication Provider

既然定義了身份驗證提供程式,我們需要使用可用的名稱空間支援在XML安全配置中指定它:

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans
  xmlns="http://www.springframework.org/schema/security"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:beans="http://www.springframework.org/schema/beans"
  xsi:schemaLocation="
    http://www.springframework.org/schema/security 
    http://www.springframework.org/schema/security/spring-security-4.0.xsd
    http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-4.2.xsd">
 
    <http use-expressions="true">
        <intercept-url pattern="/**" access="isAuthenticated()"/>
        <http-basic/>
    </http>
 
    <authentication-manager>
        <authentication-provider
          ref="customAuthenticationProvider" />
    </authentication-manager>
 
</beans:beans>

4. Java Configuration

接下來,我們來看看相應的Java配置:

@Configuration
@EnableWebSecurity
@ComponentScan("org.baeldung.security")
public class SecurityConfig extends WebSecurityConfigurerAdapter {
  
    @Autowired
    private CustomAuthenticationProvider authProvider;
 
    @Override
    protected void configure(
      AuthenticationManagerBuilder auth) throws Exception {
  
        auth.authenticationProvider(authProvider);
    }
 
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().authenticated()
            .and()
            .httpBasic();
    }
}

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

六,總結

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

可以在GitHub專案中找到本教程的完整實現 - 這是一個基於Maven的專案,因此它應該很容易匯入和執行。

相關文章