Spring Security OAuth2實現單點登陸

一、概述

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

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

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

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

咱們將使用 OAuth2 中的 Authorization Code 受權類型來驅動受權。git

二、客戶端應用

先從客戶端應用下手,使用 Spring Boot 來最小化配置:github

2.一、Maven 依賴

首先,須要在 pom.xml 中添加如下依賴:web

<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.二、安全配置

接下來,最重要的部分就是客戶端應用的安全配置:spring

@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 — 若是沒有它,全部路徑都將被保護 — 所以用戶在嘗試訪問任何頁面時將被重定向到登陸頁面。 在當前這個示例中,索引頁面和登陸頁面能夠在沒有身份驗證的狀況下能夠訪問。ruby

最後,咱們還定義了一個 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.三、前端

如今來看看客戶端應用的前端配置。咱們不想把太多時間花費在這裏,主要是由於以前已經介紹過了

客戶端應用有一個很是簡單的前端:

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.一、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.二、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.三、安全配置

首先,咱們將經過 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.四、用戶端點

最後,咱們將建立以前在配置中使用到的用戶端點:

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

用戶數據將以 JSON 形式返回。

四、結論

在這篇快速教程中,咱們使用 Spring Security Oauth2 和 Spring Boot 實現了單點登陸。

一如既往,您能夠在 GitHub 上找到完整的源碼。

原文項目示例代碼

github.com/eugenp/tuto…

 

本文轉載自

原文做者:雲棲路

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

相關文章
相關標籤/搜索