使用SpringSecurity 實現 OAuth2 資源伺服器認證伺服器分離( 註冊碼模式)
前言
要解決的問題:不暴露客戶密碼的情況下授權三方服務訪問客戶資源
角色:資源擁有者,客戶端應用(三方服務),授權伺服器,資源伺服器
模式:授權碼模式:需要客戶授權得到授權碼後再次通過三方服務的密碼取得token,雙重校驗,最安全,最複雜
簡易模式:無需授權碼對使用者暴露返回的Token,不安全
密碼模式:客戶端應用需要資源擁有者密碼。全鏈路可信情況下使用
客戶端模式:無需資源擁有者密碼,只需要客戶端應用密碼進行校驗,伺服器對伺服器使用
本試驗主要演示註冊碼模式,分為授權伺服器和資源伺服器倆個應用,後續會持續擴充套件為單個授權伺服器和多個資源伺服器。
試驗步驟
按照以下截圖建立授權伺服器,授權伺服器包結構如下
1 使用pom檔案匯入相應依賴,主要匯入了以下依賴包
1)SpringBoot的security和web,
2)SpringSecurity的OAuth2
pom檔案如下
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>io.spring2go</groupId> <artifactId>authcode-server</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>authcode-server</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.10.RELEASE</version> <relativePath /> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- for OAuth 2.0 --> <dependency> <groupId>org.springframework.security.oauth</groupId> <artifactId>spring-security-oauth2</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
2 修改application.properties設定使用者登入密碼
# Spring Security Setting security.user.name=bobo security.user.password=xyz
3 製作SpringBoot的啟動檔案
package com.test.authcodeserver; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class AuthCodeServerApplication { public static void main(String[] args) { SpringApplication.run(AuthCodeServerApplication.class, args); } }4 設定授權服務程式碼
package com.test.authcodeserver.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; import org.springframework.security.oauth2.provider.token.DefaultTokenServices; import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore; import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore; @Configuration @EnableAuthorizationServer public class AuthCodeServerConfig extends AuthorizationServerConfigurerAdapter { @Override public void configure(final AuthorizationServerSecurityConfigurer oauthServer) throws Exception { oauthServer.tokenKeyAccess("permitAll()") .checkTokenAccess("isAuthenticated()"); } @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { //JdbcClientDetailsService可以動態管理資料庫中客戶端資料 //http://localhost:8080/oauth/authorize?client_id=testclientid&redirect_uri=http://localhost:9001/authCodeCallback&response_type=code&scope=read_userinfo clients.inMemory() .withClient("testclientid")//clientId:(必須的)用來標識客戶的Id。 .secret("1234")//secret:(需要值得信任的客戶端)客戶端安全碼,如果有的話。 .redirectUris("http://localhost:9001/authCodeCallback")//客戶端應用負責獲取授權碼的endpoint .authorizedGrantTypes("authorization_code")// 授權碼模式 .scopes("read_userinfo", "read_contacts");//scope:用來限制客戶端的訪問範圍,如果為空(預設)的話,那麼客戶端擁有全部的訪問範圍。 } }
5 啟動SpringBoot服務
6 客戶端服務訪問授權伺服器,銅鼓訪問如下url取得授權碼
http://localhost:8080/oauth/authorize?client_id=testclientid&redirect_uri=http://localhost:9001/authCodeCallback&response_type=code&scope=read_userinfo
訪問完成後會redirect回客戶端伺服器並將授權碼作為引數傳回,其中localhost:9001即為客戶端應用
7 客戶端使用返回的授權碼獲取訪問令牌
傳送請求引數如下
url:http://localhost:8080/oauth/token
code=ifz2BV&grant_type=authorization_code&redirect_uri=http%3A%2F%2Flocalhost%3A9001%2FauthCodeCallback&scope=read_userinfo
得到的令牌資料
{access_token: "554338cd-cab0-4ba0-b5bf-3ebd55db3196"token_type: "bearer"expires_in: 43199scope: "read_userinfo"}
以上授權伺服器就簡單完成了,下面將製作資源伺服器
--------------------------------------------------------------------------------------------------
資源伺服器
0 資源伺服器的包結構
1 資源伺服器配置,使用RemoteTokenServices調取認證伺服器的認證方法來對Token進行認證
package com.test.resourceserver.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.core.AuthenticationException; import org.springframework.security.oauth2.common.OAuth2AccessToken; import org.springframework.security.oauth2.common.exceptions.InvalidTokenException; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer; import org.springframework.security.oauth2.provider.OAuth2Authentication; import org.springframework.security.oauth2.provider.token.DefaultTokenServices; import org.springframework.security.oauth2.provider.token.RemoteTokenServices; import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices; import org.springframework.security.web.AuthenticationEntryPoint; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; //資源服務配置 @Configuration @EnableResourceServer public class OAuth2ResourceConfig extends ResourceServerConfigurerAdapter { @Primary @Bean public RemoteTokenServices tokenServices() { final RemoteTokenServices tokenService = new RemoteTokenServices(); tokenService.setCheckTokenEndpointUrl("http://localhost:8080/oauth/check_token"); tokenService.setClientId("testclientid"); tokenService.setClientSecret("1234"); return tokenService; } @Override public void configure(HttpSecurity http) throws Exception { // http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED) // .and() // .authorizeRequests() // .anyRequest() // .authenticated() // .and() // .requestMatchers() // .antMatchers("/api/**"); http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED) .and() .authorizeRequests().anyRequest().permitAll(); } }
2 提供對外的API介面
package com.test.resourceserver.api; import org.springframework.http.ResponseEntity; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.User; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class UserController { // 資源API @RequestMapping("/api/userinfo") public ResponseEntity<UserInfo> getUserInfo() { String user = (String) SecurityContextHolder.getContext() .getAuthentication().getPrincipal(); String email = user+ "@test.com"; UserInfo userInfo = new UserInfo(); userInfo.setName(user); userInfo.setEmail(email); return ResponseEntity.ok(userInfo); } }呼叫getUserInfo
http://localhost:8004/api/userinfo
authorization: Bearer 638aa01c-4ccd-4873-ab86-d46f22aea091
呼叫後返回資源伺服器的結果
至此一個資源伺服器和認證伺服器分離的資源呼叫就結束了。