Spring Securityでの私の問題についてお手伝いをしたいと思います。 私は、ユーザーが選択したオプションに基づいてログイン資格情報を検証する必要があります。オプション1は、第三者サービスを介してログインしているユーザーを検証します。オプション2は、データベース認証レベルを使用した通常の検証です。これをどのように実装できますか?Spring Securityでのカスタム認証の実装
答えて
一般的な戦略は
- が
org.springframework.security.authentication.AuthenticationProvider
のカスタム実装を提供することを委任し、適切なバックエンドに認証(サードパーティのサービスを、別のAuthenticationProvider
、など)。 - ユーザーが選択したオプションをカスタム
AuthenticationProvider
に渡し、正しい認証バックエンドを選択できるようにします。 - デフォルトの認証プロバイダとしてカスタム
AuthenticationProvider
を設定します。
ステップ1:
AuthenticationProvider
AuthenticationProvider
実装は、単一のメソッドとのインタフェースです。
class DelegatingAuthenticationProvider implements AuthenticationProvider {
@Autowired
private ThirdPartyAuthenticationService service;
@Autowired
@Qualifier("anotherAuthenticationProvider")
private AuthenticationProvider provider;
@Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
// Get the user selection.
String selection = (String) authentication.getDetails();
// Take action depending on the selection.
Authentication result;
if("ThirdParty".equals(selection)) {
// Authenticate using "service" and generate a new
// Authentication "result" appropriately.
}
else {
// Authenticate using "provider" and generate a new
// Authentication "result" appropriately.
}
return result;
}
}
ステップ2:そのため、カスタム実装は次のように見えるかもしれ
AuthenticationProvider
実装は上記のdetails
プロパティからユーザーの選択をピックアップAuthenticationProvider
にユーザ選択を渡しますAuthentication
オブジェクトです。おそらく、ユーザの選択はHttpServletRequest
から取得し、AuthenticationProvider
を呼び出す前にAuthentication
オブジェクトに追加する必要があります。これは、Authentication
とHttpServletRequest
オブジェクトの両方にアクセスできる別のコンポーネントで、AuthenticationProvider
を実装する必要がある前に呼び出されます。
Authentication
オブジェクトは、AbstractAuthenticationProcessingFilter
の実装によって作成されます。このクラスには、のオブジェクトを受け入れ、というメソッドがあり、Authentication
オブジェクトを返します。だから、これは必要なものを実装するための良い候補になると思われる。ユーザ名とパスワードベースの認証の場合、実装クラスはUsernamePasswordAuthenticationFilter
です。このクラスはという新しいインスタンスを返します。これはAuthentication
の実装です。だから、UsernamePasswordAuthenticationFilter
のクラスで十分です。
class ExtendedUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
...
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(username, password);
authentication.setDetails(obtainUserSelection(request));
...
return authentication;
}
}
obtainUserSelection
は、リクエストからユーザー選択を取得するプライベートメソッドです。
ステップ3:設定
は春のセキュリティ構成のAuthenticationProvider
とフィルタの実装を設定します。正確な手順は、XMLまたはJava構成のどちらを使用するかによって異なります。
wow..thanks manish!これは、春のセキュリティを学ぶ乗り物の1つの地獄です。これは私の最初の実装です。 ExtendedUsernamePasswordAuthenticationFilterの実装に関するチュートリアルサイトを教えてください。 please: –
[UsernamePasswordAuthenticationFilter'の公式の実装](https://github.com/spring-projects/spring-security/blob/master/web/src/main/java/org/springframework/security)を確認することができます。 /web/authentication/UsernamePasswordAuthenticationFilter.java)。 – manish