WebFluxを使用したSpring Security OAuthログイン
1. 概要
Spring Securityは、5.1.x GAからWebFluxのOAuthサポートを追加しました。
how to configure our WebFlux application to use OAuth2 Login supportについて説明します。 また、WebClientを使用してOAuth2で保護されたリソースにアクセスする方法についても説明します。
WebfluxのOAuthログイン設定は、標準のWeb MVCアプリケーションの設定に似ています。 詳細については、Spring OAuth2Login elementに関する記事もご覧ください。
2. Mavenの構成
まず、単純なSpring Bootアプリケーションを作成し、これらの依存関係をpom.xmlに追加します。
org.springframework.boot
spring-boot-starter-security
org.springframework.boot
spring-boot-starter-webflux
org.springframework.security
spring-security-oauth2-client
spring-boot-starter-security、spring-boot-starter-webflux、およびspring-security-oauth2-clientの依存関係は、MavenCentralで利用できます。
3. メインコントローラー
次に、ホームページにユーザー名を表示する簡単なコントローラーを追加します。
@RestController
public class MainController {
@GetMapping("/")
public Mono index(@AuthenticationPrincipal Mono oauth2User) {
return oauth2User
.map(OAuth2User::getName)
.map(name -> String.format("Hi, %s", name));
}
}
we’ll display the username obtained from OAuth2 client UserInfo endpointに注意してください。
4. Googleを使用してログイン
次に、Googleを使用したログインをサポートするようにアプリケーションを構成します。
まず、Google Developer Consoleで新しいプロジェクトを作成する必要があります
次に、OAuth2資格情報を追加する必要があります(資格情報の作成> OAuthクライアントID)。
次に、これを「承認されたリダイレクトURI」に追加します。
http://localhost:8080/login/oauth2/code/google
次に、we need to configure our application.yml to use the Client ID and Secret:
spring:
security:
oauth2:
client:
registration:
google:
client-id: YOUR_APP_CLIENT_ID
client-secret: YOUR_APP_CLIENT_SECRET
パスにspring-security-oauth2-clientが含まれているため、アプリケーションは保護されます。
ユーザーは、ホームページにアクセスする前に、Googleを使用してログインするようにリダイレクトされます。
5. 認証プロバイダーを使用してログインする
カスタム認証サーバーからログインするようにアプリケーションを構成することもできます。
次の例では、previous articleの承認サーバーを使用します。
今回は、ClientIDとClient Secretだけでなく、より多くのプロパティを構成する必要があります。
spring:
security:
oauth2:
client:
registration:
custom:
client-id: fooClientIdPassword
client-secret: secret
scopes: read,foo
authorization-grant-type: authorization_code
redirect-uri-template: http://localhost:8080/login/oauth2/code/custom
provider:
custom:
authorization-uri: http://localhost:8081/spring-security-oauth-server/oauth/authorize
token-uri: http://localhost:8081/spring-security-oauth-server/oauth/token
user-info-uri: http://localhost:8088/spring-security-oauth-resource/users/extra
user-name-attribute: user_name
この場合、OAuth2クライアントのscope,grant typeとredirect URIも指定する必要があります。 また、承認サーバーのauthorizationとtoken URIも提供します。
最後に、ユーザー認証の詳細を取得できるように、UserInfoエンドポイントも構成する必要があります。
6. セキュリティ構成
デフォルトでは、Spring Securityはすべてのパスを保護します。 したがって、OAuthクライアントが1つしかない場合は、このクライアントを承認してログインするようにリダイレクトされます。
複数のOAuthクライアントが登録されている場合は、ログイン方法を選択するためのログインページが自動的に作成されます。
必要に応じて、provide a detailed security configurationで変更できます。
@EnableWebFluxSecurity
public class SecurityConfig {
@Bean
public SecurityWebFilterChain configure(ServerHttpSecurity http) throws Exception {
return http.authorizeExchange()
.pathMatchers("/about").permitAll()
.anyExchange().authenticated()
.and().oauth2Login()
.and().build();
}
}
この例では、「/ about」を除くすべてのパスを保護しています。
7. WebClient
OAuth2を使用してユーザーを認証するだけではありません。 We can use WebClient to access OAuth2 secured resources using OAuth2AuthorizedClient。
それでは、WebClientを構成しましょう。
@Bean
public WebClient webClient(ReactiveClientRegistrationRepository clientRegistrationRepo,
ServerOAuth2AuthorizedClientRepository authorizedClientRepo) {
ServerOAuth2AuthorizedClientExchangeFilterFunction filter =
new ServerOAuth2AuthorizedClientExchangeFilterFunction(clientRegistrationRepo, authorizedClientRepo);
return WebClient.builder().filter(filter).build();
}
次に、OAuth2で保護されたリソースを取得できます。
@Autowired
private WebClient webClient;
@GetMapping("/foos/{id}")
public Mono getFooResource(@RegisteredOAuth2AuthorizedClient("custom")
OAuth2AuthorizedClient client, @PathVariable final long id){
return webClient
.get()
.uri("http://localhost:8088/spring-security-oauth-resource/foos/{id}", id)
.attributes(oauth2AuthorizedClient(client))
.retrieve()
.bodyToMono(Foo.class);
}
we retrieved the remote resource Foo using AccessToken from*OAuth2AuthorizedClient*.に注意してください
8. 結論
この簡単な記事では、OAuth2 Loginサポートを使用するようにWebFluxアプリケーションを構成する方法と、OAuth2で保護されたリソースにアクセスするためにWebClientを使用する方法を学びました。
いつものように、完全なソースコードはover on GitHubで入手できます。