私のアプリケーションでは、特定のAPI呼び出しにのみOAuth2セキュリティを提供したいと考えています。私の質問は、パス変数に基づいてHttpBasicまたはOauth2認証を提供できるかどうかです。
以下は、私が検討する2つのシナリオです。
1)ユーザー(パス変数に名前が指定されている)xyzについて、xyzにOAuthの機能がない場合、httpBasicを使用して認証したいとします
2)別のユーザーabcがOAuthの機能を持っている場合、Oauth / OpenId connectを使用して認証します。
ユーザーに機能を割り当てるテーブルがあります。以下はテーブルの概要です。
名前、機能
xyz、HttpBasic
abc、Oauth
さて、私は自分でいくつかの研究を行い、解決策を見つけることができました。これが私がしたことです、
-WebSecurityConfigurerAdapterを使用して1つのhttpbasic構成を作成しました。インターセプターがタスクを開始する前に、認証ヘッダーがBasicかBearerかをチェックする1つのリクエストマッチャーを作成しました。
//By default this filter order is 100 and OAuth has filter order 3
@Order(2)
public class MicroserviceSecurityConfigurationHttpBasic extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().exceptionHandling()
.authenticationEntryPoint(customAccessDeniedHandler())
.and().headers().frameOptions().disable()
.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.requestMatcher(new BasicRequestMatcher())
.authorizeRequests()
.antMatchers("/api/**").authenticated()
.and().httpBasic();
}
private class BasicRequestMatcher implements RequestMatcher {
@Override
public boolean matches(HttpServletRequest httpRequest) {
String auth = httpRequest.getHeader("Authorization");
String requestUri = httpRequest.getRequestURI();
//Fetching Identifier to provide OAuth Security to only specific urls
String identifier= requestUri.substring(requestUri.lastIndexOf("/") + 1, requestUri.length());
//Lets say for identifier ABC only, I want to secure it using OAuth2.0
if (auth != null && auth.startsWith("Basic") && identifier.equalsIgnoreCase("ABC")) {
auth=null;
}
//For ABC identifier this method will return null so then the authentication will be redirected to OAuth2.0 config.
return (auth != null && auth.startsWith("Basic"));
}
}
}
-この後、ResourceServerConfigurerAdapterを使用してOAuth2.0構成を作成しました。その一例を次に示します。
//Default filter order=3 so this will be executed after WebSecurityConfigurerAdapter
public class MicroserviceSecurityConfiguration extends ResourceServerConfigurerAdapter {
...
//Here I am intercepting the same url but the config will look for bearer token only
@Override
public void configure(HttpSecurity http) throws Exception {
http.csrf().disable().exceptionHandling()
.and().headers().frameOptions().disable()
.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and().authorizeRequests()
.antMatchers("/api/**").authenticated();
}
}
参照:https : //github.com/spring-projects/spring-security-oauth/issues/1024
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加