REST APIを保護したい。ルールは単純です。Springセキュリティでエンドポイントの認証方法を制限する
- ユーザーは、エンドポイント
/api/authenticate
のみHTTP基本認証(無トークン認証を)受け入れるユーザーがAPIにアクセスするために(/api/authenticate
から受け取った)トークンを使用することができます/api/**
- トークンを取得するために
- エンドポイント
/api/**
(/api/authenticate
を除く)は、トークン認証(基本認証なし)のみを受け入れます。 - すべての残りのエンドポイントは公開されており、authe 。
/api/authenticate
を呼び出す必要があります
私は実際にこれを使用します。
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private TokenAuthenticationProvider tokenAuthenticationProvider;
@Override
protected void configure(final HttpSecurity httpSecurity) throws Exception {
httpSecurity.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
httpSecurity.headers().disable();
httpSecurity.setSharedObject(TokenAuthenticationProvider.class, this.tokenAuthenticationProvider);
httpSecurity.antMatcher("/api/authenticate").httpBasic();
httpSecurity.antMatcher("/api/**").apply(new TokenAuthenticationConfigurer());
httpSecurity.authorizeRequests()
.antMatchers("/api/**").authenticated()
.anyRequest().permitAll();
}
}
を実際に、私は私の設定が要求を受け入れる/api/authenticate
するトークンでリクエストを送信する場合。 /api/authenticate
が/api/**
の一部であるため、これが発生すると思います。だから私はトークン認証のためにこのパスを除外する必要があります。
どうすればいいですか?
EDIT 1
私は.and()
流暢なスタイルを使用する場合、結果はまったく同じです。
@Override
protected void configure(final HttpSecurity httpSecurity) throws Exception {
httpSecurity.setSharedObject(TokenAuthenticationProvider.class, this.tokenAuthenticationProvider);
httpSecurity
.headers().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.antMatcher("/api/authenticate").httpBasic()
.and()
.antMatcher("/api/**").apply(new TokenAuthenticationConfigurer())
.and()
.authorizeRequests().antMatchers("/api/**").authenticated().anyRequest().permitAll();
}
EDIT 2
IはSecurityBuilder
(HttpSecurity
)を理解するように、configure(...)
方法でantMatcher(...)
のすべての呼び出しは、前の呼び出しを上書き。私が見ることができるデバッグログでは、Spring Securityは常に/api/**
と要求パスを一致させようと試みますが、もう一度/api/authenticate
とは一致しません。私が注文を切り替えると、APIにはもうアクセスすることができなくなりました。ただちに/api/authenticate
となりました。これは、Spring Securityが常に/api/authenticate
と一致するようになるためです。
そこで質問です:どのように私は複数のルール登録することができます。
/api/authenticate
- >HttpBasicConfigurer
(.http()
)/api/**
- >TokenAuthenticationConfigurer
(私のトークン認証が設定され、.apply(...)
)
あなたは、この問題を解決するために管理したのですか? –
はい。 'WebSecurityConfigurerAdapter'を拡張することで、複数のセキュリティ設定を作成する必要があります。 '/ api/authenticate'の設定と'/api/** 'の設定があります。それらのそれぞれは、所望のセキュリティ機構で構成することができる。 '@ Order'を使ってセキュリティ設定の優先順位を定義する必要もあります。 – baymon