Spring Security OAuth2實現單點登錄


1、概述

在本教程中,我們將討論如何使用 Spring Security OAuth 和 Spring Boot 實現 SSO(單點登錄)。

本示例將使用到三個獨立應用

  • 一個授權服務器(中央認證機制)
  • 兩個客戶端應用(使用到了 SSO 的應用)

簡而言之,當用戶嘗試訪問客戶端應用的安全頁面時,他們首先通過身份驗證服務器重定向進行身份驗證。

我們將使用 OAuth2 中的 Authorization Code 授權類型來驅動授權。

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 { @Override public void configure(HttpSecurity http) throws Exception { http.antMatcher("/**") .authorizeRequests() .antMatchers("/", "/login**") .permitAll() .anyRequest() .authenticated(); } } 

當然,該配置的核心部分是 @EnableOAuth2Sso 注解,我們用它來啟用單點登錄。

請注意,我們需要繼承 WebSecurityConfigurerAdapter — 如果沒有它,所有路徑都將被保護 — 因此用戶在嘗試訪問任何頁面時將被重定向到登錄頁面。 在當前這個示例中,索引頁面和登錄頁面可以在沒有身份驗證的情況下可以訪問。

最后,我們還定義了一個 RequestContextListener bean 來處理請求。

application.yml

server:  port: 8082  context-path: /ui  session:  cookie:  name: UISESSION security:  basic:  enabled: false  oauth2:  client:  clientId: SampleClientId  clientSecret: secret  accessTokenUri: http://localhost:8081/auth/oauth/token  userAuthorizationUri: http://localhost:8081/auth/oauth/authorize  resource:  userInfoUri: http://localhost:8081/auth/user/me spring:  thymeleaf:  cache: false 

有幾點需要說明:

  • 我們禁用了默認的 Basic Authentication
  • accessTokenUri 是獲取訪問令牌的 URI
  • userAuthorizationUri 是用戶將被重定向到的授權 URI
  • 用戶端點 userInfoUri URI 用於獲取當前用戶的詳細信息

另外需要注意,在本例中,我們使用了自己搭建的授權服務器,當然,我們也可以使用其他第三方提供商的授權服務器,例如 Facebook 或 GitHub。

2.3、前端

現在來看看客戶端應用的前端配置。我們不想把太多時間花費在這里,主要是因為之前已經介紹過了

客戶端應用有一個非常簡單的前端:

index.html:

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

securedPage.html:

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

securedPage.html 頁面需要用戶進行身份驗證。 如果未經過身份驗證的用戶嘗試訪問 securedPage.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 { @Autowired private AuthenticationManager authenticationManager; @Override public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception { oauthServer.tokenKeyAccess("permitAll()") .checkTokenAccess("isAuthenticated()"); } @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.inMemory() .withClient("SampleClientId") .secret("secret") .authorizedGrantTypes("authorization_code") .scopes("user_info") .autoApprove(true) ; } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints.authenticationManager(authenticationManager); } } 

需要注意的是我們使用 authorization_code 授權類型來開啟一個簡單的客戶端。

3.3、安全配置

首先,我們將通過 application.properties 禁用默認的 Basic Authentication:

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

現在,讓我們到配置定義一個簡單的表單登錄機制:

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

請注意,雖然我們使用了簡單的內存認證,但可以很簡單地將其替換為自定義的 userDetailsService

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…

 

本文轉載自

原文作者:雲棲路

原文鏈接:https://blog.csdn.net/s573626822/article/details/79870244


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM