Spring Securityを学ぶ(8): Spring Security OAuth2を使ってシングルサインオンを実現する

1。概要

このチュートリアルでは、Spring Security OAuth と Spring Boot を使用して SSO (シングル サインオン) を実装する方法について説明します。

この例では 3 つの別々のアプリケーションを使用します

  • 認可サーバー (中央認証メカニズム)

  • 2 つのクライアント アプリケーション (SSO を使用するアプリケーション)

簡単に言うと、ユーザーがクライアント アプリの安全なページにアクセスしようとすると、最初に認証サーバー リダイレクトを通じて認証されます。

OAuth2 の認証コード付与タイプを使用して認証を推進します。

2. クライアントアプリケーション

クライアント アプリケーションから始めて、Spring Boot を使用して構成を最小限に抑えましょう。

2.1. Maven の依存関係

まず、次の依存関係を pom.xml に追加する必要があります。

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency><groupId>org.springframework.security.oauth</groupId><artifactId>spring-security-oauth2</artifactId>
</dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency><groupId>org.thymeleaf.extras</groupId><artifactId>thymeleaf-extras-springsecurity4</artifactId>
</dependency> 

2.2. セキュリティ設定

次に、最も重要な部分は、クライアント アプリケーションのセキュリティ構成です。

@Configuration
@EnableOAuth2Sso
public class UiSecurityConfig extends WebSecurityConfigurerAdapter { @Overridepublic void configure(HttpSecurity http) throws Exception {http.antMatcher("/**").authorizeRequests().antMatchers("/", "/login**").permitAll().anyRequest().authenticated();}
} 

もちろん、この構成の中核となる部分は、シングル サインオンを有効にするために使用する @EnableOAuth2Sso アノテーションです。

WebSecurityConfigurerAdapter をサブクラス化する必要があることに注意してください。これがないと、すべてのパスが保護されます。そのため、ユーザーは任意のページにアクセスしようとするとログイン ページにリダイレクトされます。現在の例では、インデックス ページとログイン ページに認証なしでアクセスできます。

最後に、リクエストを処理するための RequestContextListener Bean も定義します。

アプリケーション.yml:

server:port: 8082context-path: /uisession:cookie:name: UISESSION
security:basic:enabled: falseoauth2:client:clientId: SampleClientIdclientSecret: secretaccessTokenUri: http://localhost:8081/auth/oauth/tokenuserAuthorizationUri: http://localhost:8081/auth/oauth/authorizeresource:userInfoUri: http://localhost:8081/auth/user/me
spring:thymeleaf:cache: false 

説明すべき点がいくつかあります

  • デフォルトの基本認証を無効にしました

  • accessTokenUri はアクセス トークンを取得するための URI です。

  • userAuthorizationUri は、ユーザーがリダイレクトされる認証 URI です。

  • ユーザー エンドポイント userInfoUri URI は、現在のユーザーの詳細を取得するために使用されます。

なお、この例では自社で構築した認可サーバーを利用しましたが、もちろんFacebookやGitHubなど他のサードパーティプロバイダの認可サーバーを利用することも可能です。

2.3. フロントエンド

次に、クライアント アプリケーションのフロントエンド構成を見てみましょう。これについては以前に説明したため、ここではあまり時間をかけたくありません

クライアント アプリケーションには非常に単純なフロントエンドがあります。

インデックス.html

<h1>Spring Security SSO</h1>
<a href="securedPage">Login</a> 

セキュアページ.html

<h1>Secured Page</h1>
Welcome, <span th:text="${#authentication.name}">Name</span> 

securePage.html ページではユーザー認証が必要です。認証されていないユーザーが securePage.html にアクセスしようとすると、最初にログイン ページにリダイレクトされます。

3. 認証サーバー

それでは、認可サーバーについて話しましょう。

3.1. Maven の依存関係

まず、pom.xml で依存関係を定義します。

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency><groupId>org.springframework.security.oauth</groupId><artifactId>spring-security-oauth2</artifactId>
</dependency> 

3.2. OAuth設定

ここで認可サーバーとリソース サーバーを単一のデプロイ可能なユニットとして一緒に実行している理由を理解することが重要です。

まずはリソース サーバーの構成から始めましょう。

@SpringBootApplication
@EnableResourceServer
public class AuthorizationServerApplication extends SpringBootServletInitializer {public static void main(String[] args) {SpringApplication.run(AuthorizationServerApplication.class, args);}
} 

その後、認可サーバーを構成します。

@Configuration
@EnableAuthorizationServer
public class AuthServerConfig extends AuthorizationServerConfigurerAdapter {@Autowiredprivate AuthenticationManager authenticationManager;
 @Overridepublic void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");}
 @Overridepublic void configure(ClientDetailsServiceConfigurer clients) throws Exception {clients.inMemory().withClient("SampleClientId").secret("secret").authorizedGrantTypes("authorization_code").scopes("user_info").autoApprove(true) ; }
 @Overridepublic void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {endpoints.authenticationManager(authenticationManager);}
} 

単純なクライアントを起動するには、authorization_code 認証タイプを使用することに注意してください。

3.3. セキュリティ設定

まず、application.properties を使用してデフォルトの Basic 認証を無効にします。

server.port=8081
server.context-path=/auth
security.basic.enabled=false 

次に、構成に進み、単純なフォーム ログイン メカニズムを定義しましょう。

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
 @Autowiredprivate AuthenticationManager authenticationManager;
 @Overrideprotected void configure(HttpSecurity http) throws Exception {http.requestMatchers().antMatchers("/login", "/oauth/authorize").and().authorizeRequests().anyRequest().authenticated().and().formLogin().permitAll();}
 @Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.parentAuthenticationManager(authenticationManager).inMemoryAuthentication().withUser("john").password("123").roles("USER");}
} 

ここでは単純なメモリ内認証を使用しましたが、カスタム userDetailsS​​ervice に簡単に置き換えることができることに注意してください。

3.4. ユーザーエンドポイント

最後に、構成の前半で使用したユーザー エンドポイントを作成します。

@RestController
public class UserController {@GetMapping("/user/me")public Principal user(Principal principal) {return principal;}
} 

ユーザーデータは JSON として返されます。

4 結論

このクイック チュートリアルでは、Spring Security Oauth2 と Spring Boot を使用してシングル サインオンを実装しました。

いつものように、完全なソース コードはGitHubで見つけることができます。

オリジナルプロジェクトのサンプルコード

github.com/eugenp/tuto…

おすすめ

転載: blog.csdn.net/qq_44005305/article/details/128561170#comments_25802422