您好,登錄后才能下訂單哦!
OAuth是一個(gè)關(guān)于授權(quán)(authorization)的開(kāi)放網(wǎng)絡(luò)標(biāo)準(zhǔn),在全世界得到廣泛應(yīng)用,目前的版本是2.0版。
本文對(duì)OAuth 2.0的設(shè)計(jì)思路和運(yùn)行流程,做一個(gè)簡(jiǎn)明通俗的解釋?zhuān)饕獏⒖疾牧蠟镽FC 6749。
OAuth 簡(jiǎn)介
OAuth 是由 Blaine Cook、Chris Messina、Larry Halff 及 David Recordon 共同發(fā)起的,目的在于為 API 訪(fǎng)問(wèn)授權(quán)提供一個(gè)安全、開(kāi)放的標(biāo)準(zhǔn)。
基于 OAuth 認(rèn)證授權(quán)具有以下特點(diǎn):
安全。OAuth 與別的授權(quán)方式不同之處在于:OAuth 的授權(quán)不會(huì)使消費(fèi)方(Consumer)觸及到用戶(hù)的帳號(hào)信息(如用戶(hù)名與密碼),也是是說(shuō),消費(fèi)方無(wú)需使用用戶(hù)的用戶(hù)名與密碼就可以申請(qǐng)獲得該用戶(hù)資源的授權(quán)。
開(kāi)放。任何消費(fèi)方都可以使用 OAuth 認(rèn)證服務(wù),任何服務(wù)提供方 (Service Provider) 都可以實(shí)現(xiàn)自身的 OAuth 認(rèn)證服務(wù)。
簡(jiǎn)單。不管是消費(fèi)方還是服務(wù)提供方,都很容易于理解與使用。
OAuth 的解決方案如下圖所示。
圖 1. OAuth Solution
如 圖 1 所示 OAuth 解決方案中用戶(hù)、消費(fèi)方及其服務(wù)提供方之間的三角關(guān)系:當(dāng)用戶(hù)需要 Consumer 為其提供某種服務(wù)時(shí),該服務(wù)涉及到需要從服務(wù)提供方那里獲取該用戶(hù)的保護(hù)資源。OAuth 保證:只有在用戶(hù)顯式授權(quán)的情況下(步驟 4),消費(fèi)方才可以獲取該用戶(hù)的資源,并用來(lái)服務(wù)于該用戶(hù)。
從宏觀(guān)層次來(lái)看,OAuth 按以下方式工作:
消費(fèi)方與不同的服務(wù)提供方建立了關(guān)系。
消費(fèi)方共享一個(gè)密碼短語(yǔ)或者是公鑰給服務(wù)提供方,服務(wù)提供方使用該公鑰來(lái)確認(rèn)消費(fèi)方的身份。
消費(fèi)方根據(jù)服務(wù)提供方將用戶(hù)重定向到登錄頁(yè)面。
該用戶(hù)登錄后告訴服務(wù)提供方該消費(fèi)方訪(fǎng)問(wèn)他的保護(hù)資源是沒(méi)問(wèn)題的。 前提
閱讀本文之前,你需要了解:
Spring Boot
Spring MVC
Spring Security
Google 瀏覽器插件Postman
pom.xml文件如下
<?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>cn.iigrowing.study.oauth3</groupId> <artifactId>demo01</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>my.oauth01</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.2.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</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.security.oauth</groupId> <artifactId>spring-security-oauth3</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
本項(xiàng)目需要添加的依賴(lài)非常簡(jiǎn)單,一共只有兩個(gè),一個(gè)是Spring Web,另一個(gè)是Spring OAuth3。
接下來(lái)是本文的核心,一共三個(gè)配置類(lèi)。
SecurityConfig
package cn.iigrowing.study.oauth3.demo01; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("user").password("123456").authorities("ROLE_USER"); } @Override protected void configure(HttpSecurity http) throws Exception { http.httpBasic() .and().csrf().disable() .authorizeRequests() .antMatchers("/login").permitAll() .anyRequest().authenticated() .and() .formLogin() .and() .logout().permitAll(); } @Override @Bean public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } }
此處主要做了兩件事情:
配置系統(tǒng)用戶(hù),這里使用內(nèi)存存儲(chǔ),添加了用戶(hù)名為 user
,角色為 USER
的用戶(hù)
@Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("user").password("123456").authorities("ROLE_USER"); }
配置了默認(rèn)表單登陸以及禁用了 csrf
功能,并開(kāi)啟了 httpBasic
認(rèn)證
@Override protected void configure(HttpSecurity http) throws Exception { http.httpBasic() .and().csrf().disable() .authorizeRequests() .antMatchers("/login").permitAll() .anyRequest().authenticated() .and() .formLogin() .and() .logout().permitAll(); }
AuthorizationServerConfig
package cn.iigrowing.study.oauth3.demo01; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.oauth3.config.annotation.configurers.ClientDetailsServiceConfigurer; import org.springframework.security.oauth3.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; import org.springframework.security.oauth3.config.annotation.web.configuration.EnableAuthorizationServer; import org.springframework.security.oauth3.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; @Configuration @EnableAuthorizationServer public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { @Autowired @Qualifier("authenticationManagerBean") private AuthenticationManager authenticationManager; @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.inMemory() .withClient("client").secret("123456").scopes("read") .authorizedGrantTypes("authorization_code") .redirectUris("https://www.getpostman.com/oauth3/callback"); } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints.authenticationManager(authenticationManager); } }
這個(gè)類(lèi)是OAuth3認(rèn)證的核心配置類(lèi),在這個(gè)類(lèi)中,配置了OAuth Client的信息,這里有幾個(gè)地方需要注意:
@EnableAuthorizationServer
這個(gè)注解告訴 Spring 這個(gè)應(yīng)用是 OAuth3 的授權(quán)服務(wù)器
必須配置 authorizedGrantTypes
,它代表了OAuth Client允許認(rèn)證的類(lèi)型,其值主要有:
authorization_code
password
client_credentials
implicit refresh_token
這個(gè)配置項(xiàng)接受的類(lèi)型是個(gè)數(shù)組,允許配置多個(gè);關(guān)于這幾種類(lèi)型的區(qū)別,請(qǐng)查看這里不再贅述
redirectUris
關(guān)于這個(gè)配置項(xiàng),是在 OAuth3協(xié)議中,認(rèn)證成功后的回調(diào)地址,因?yàn)樯院笪覀儠?huì)使用 Postman
作為測(cè)試工具,故此處值固定為 https://www.getpostman.com/oauth3/callback
,此值同樣可以配置多個(gè) ResourceServerConfig
package cn.iigrowing.study.oauth3.demo01; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.oauth3.config.annotation.web.configuration.EnableResourceServer; import org.springframework.security.oauth3.config.annotation.web.configuration.ResourceServerConfigurerAdapter; import org.springframework.security.oauth3.config.annotation.web.configurers.ResourceServerSecurityConfigurer; @Configuration @EnableResourceServer public class ResourceServerConfig extends ResourceServerConfigurerAdapter { @Override public void configure(ResourceServerSecurityConfigurer resources) { resources.resourceId(“users-info”); } @Override public void configure(HttpSecurity http) throws Exception { http .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .requestMatchers() .antMatchers(“/users/**”) .and().authorizeRequests() .antMatchers(“/users/**”) .authenticated(); } }
這個(gè)類(lèi)表明了此應(yīng)用是OAuth3 的資源服務(wù)器,此處主要指定了受資源服務(wù)器保護(hù)的資源鏈接,我們將提供以下的資源:
@RestController @RequestMapping("users") public class UserController { @GetMapping("me") public Principal me(Principal principal) { return principal; } }
注:
資源服務(wù)器可以和授權(quán)服務(wù)器是同一個(gè),也可以分開(kāi)部署
最后,我們還需添加 application.yml
, 配置資源服務(wù)器的filter的順序
server: port: 8043 context-path: /uaa logging: level: org.springframework.security: DEBUG spring: application: name: oauth-server security: oauth3: resource: serviceId: ${PREFIX:}resource # refer to: https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-1.5-Release-Notes#oauth-2-resource-filter filter-order: 3
此處的 filter-order
非常重要,因?yàn)樽許pring Boot 1.5.* 之后,resource server 的 filter 的順序默認(rèn)在 basic authentication filter chain
之后,所以如果不配置此項(xiàng),將會(huì)導(dǎo)致使用 access_token
訪(fǎng)問(wèn) resource server 的時(shí)候返回 401
狀態(tài)碼。
好了,所有的開(kāi)發(fā)工作已經(jīng)完成,無(wú)需任何其他配置,現(xiàn)在我們啟動(dòng)服務(wù)器,并通過(guò) Postman
訪(fǎng)問(wèn) http://localhost:8043/uaa/users/me
因?yàn)楝F(xiàn)在還沒(méi)通過(guò)認(rèn)證,所以服務(wù)器將返回 401
的狀態(tài)碼,并返回以上的錯(cuò)誤信息。
現(xiàn)在我們使用 Postman
來(lái)獲取 access_token
,首先選擇 Authorization
Tab, 然后選擇 Type
為 OAuth3.0
,最后點(diǎn)擊 Get New Access Token
按鈕:
此時(shí)將彈出以下界面:
我們填入對(duì)應(yīng)的信息:
Token Name: access_token
Auth URL: http://localhost:8043/uaa/oauth/authorize
Access Token URL: http://localhost:8043/uaa/oauth/token
Client ID: client
Client Secret: 123456
Grant Type: Authorization Code
此處配置的client相關(guān)信息對(duì)應(yīng)了我們?cè)?AuthorizationServerConfig
里面的配置,之前配置的回調(diào)地址也來(lái)自于此處的 Callback URL
。
接下來(lái)點(diǎn)擊 Request Token
按鈕,在彈出的登陸界面中輸入我們之前在 SecurityConfig
中配置的用戶(hù)信息,選擇 Approval
并點(diǎn)擊 Authorize
按鈕,即可獲取 access_token
:
到這里我們就成功的獲取了 token,此時(shí)再次調(diào)用 users/me
Api,如無(wú)意外,將會(huì)得到以下的結(jié)果:
這個(gè)項(xiàng)目實(shí)現(xiàn)了以下的功能:
使用 JWT Token進(jìn)行認(rèn)證
多Resource Sever
使用數(shù)據(jù)庫(kù)存儲(chǔ)用戶(hù)以及OAuth Client信息
提供相關(guān)的Rest API進(jìn)行用戶(hù)及 Client的管理
結(jié)合了Spring Cloud
源代碼:my.oauth01
小結(jié)
OAuth 協(xié)議作為一種開(kāi)放的,基于用戶(hù)登錄的授權(quán)認(rèn)證方式,目前互聯(lián)網(wǎng)很多 Open API 都對(duì) OAuth 提供了支持,這包括 Google, Yahoo,Twitter 等。本文以 Google 為例子,介紹了 Java 桌面程序如何開(kāi)發(fā) OAuth 認(rèn)證應(yīng)用。在開(kāi)發(fā)桌面應(yīng)用訪(fǎng)問(wèn) Web 資源這樣一類(lèi)程序時(shí),一般通行的步驟是:使用 OAuth 做認(rèn)證,然后使用獲得的 OAuth Access Token,通過(guò) REST API 訪(fǎng)問(wèn)用戶(hù)在服務(wù)提供方的資源。
事實(shí)上,目前 OAuth 正通過(guò)許多實(shí)現(xiàn)(包括針對(duì) Java、C#、Objective-C、Perl、PHP 及 Ruby 語(yǔ)言的實(shí)現(xiàn))獲得巨大的動(dòng)力。大部分實(shí)現(xiàn)都由 OAuth 項(xiàng)目維護(hù)并放在 Google 代碼庫(kù) (http://oauth.googlecode.com/svn/) 上。開(kāi)發(fā)者可以利用這些 OAuth 類(lèi)庫(kù)編寫(xiě)自己需要的 OAuth 應(yīng)用。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。