Spring Security認証プロバイダー
1. 概要
このチュートリアルでは、UserDetailsServiceを設定して、単純なUserDetailsServiceを使用した標準シナリオと比較して柔軟性を高める方法を示します。
2. 認証プロバイダー
Spring Securityは、認証を実行するためのさまざまなオプションを提供します。 これらは単純なコントラクトに従います–an Authentication request is processed by an AuthenticationProviderと、完全な資格情報を持つ完全に認証されたオブジェクトが返されます。
標準で最も一般的な実装は、DaoAuthenticationProvider –単純な読み取り専用ユーザーDAO –UserDetailsServiceからユーザーの詳細を取得します。 このユーザー詳細サービスonly has access to the usernameは、完全なユーザーエンティティを取得します。 ほとんどのシナリオではこれで十分です。
認証プロセスを実行できるようにするには、さらに多くのカスタムシナリオでAuthenticationリクエスト全体にアクセスする必要があります。 たとえば、外部のサードパーティサービス(Crowdなど)–both the username and the password from the authentication request will be necessaryに対して認証する場合です。
これらのより高度なシナリオでは、define a custom Authentication Providerを実行する必要があります。
@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. 認証プロバイダーを登録する
認証プロバイダーを定義したので、利用可能な名前空間サポートを使用して、XMLセキュリティ構成で認証プロバイダーを指定する必要があります。
4. Java設定
次に、対応するJava構成を見てみましょう。
@Configuration
@EnableWebSecurity
@ComponentScan("org.example.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
この例では、基本認証を使用してRESTAPIを保護しました。
そして、サーバーから予想される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のカスタム認証プロバイダーの例を説明しました。
このチュートリアルの完全な実装は、the GitHub projectにあります。