微服務操做模型html
基於Spring Cloud和Netflix OSS 構建微服務-Part 1java
基於Spring Cloud和Netflix OSS構建微服務,Part 2git
在本文中,咱們將使用OAuth 2.0,建立一個的安全API,可供外部訪問Part 1和Part 2完成的微服務。github
關於OAuth 2.0的更多信息,能夠訪問介紹文檔:Parecki - OAuth 2 Simplified 和 Jenkov - OAuth 2.0 Tutorial ,或者規範文檔 IETF RFC 6749。web
咱們將建立一個新的微服務,命名爲product-api,做爲一個外部API(OAuth 術語爲資源服務器-Resource Server),並經過以前介紹過的Edge Server暴露爲微服務,做爲Token Relay,也就是轉發Client端的OAuth訪問令牌到資源服務器(Resource Server)。另外添加OAuth Authorization Server和一個OAuth Client,也就是服務消費方。spring
繼續完善Part 2的系統全貌圖,添加新的OAuth組件(標識爲紅色框):api
咱們將演示Client端如何使用4種標準的受權流程,從受權服務器(Authorization Server)獲取訪問令牌(Access Token),接着使用訪問令牌對資源服務器發起安全訪問,如API。瀏覽器
備註:安全
1/ 保護外部API並非微服務的特殊需求,所以本文適用於任何使用OAuth 2.0保護外部API的架構;服務器
2/ 咱們使用的輕量級OAuth受權系統僅適用於開發和測試環境。在實際應用中,須要替換爲一個API平臺,或者委託給社交網絡Facebook或Twitter的登陸、受權流程。
3/ 爲了下降複雜度,咱們特地採用了HTTP協議。在實際的應用中,OAuth通訊須要使用TLS,如HTTPS保護通訊數據。
4/ 在前面的文章中,咱們爲了強調微服務和單體應用的差別性,每個微服務單獨運行在獨立的進程中。
和在Part 2中同樣,咱們使用Java SE 八、Git和Gradle訪問源代碼,並進行編譯:
git clone https://github.com/callistaenterprise/blog-microservices.git
cd blog-microservices
git checkout -b B3 M3.1
./build-all.sh
若是運行在Windows平臺,則執行相應的bat文件-build-all.bat。
在Part 2的基礎中,新增了2個組件源碼,分別爲OAuth Authorization Server,項目名爲auth-server;另外一個爲OAuth Resource Server,項目名爲product-api-service。
編譯輸出10條log消息:
BUILD SUCCESSFUL
查看2個新組件是如何實現的,以及Edge Server是如何更新並支持傳遞OAuth訪問令牌的。咱們也會修改API的URL,以便於使用。
2.1 Gradle 依賴
爲了使用OAuth 2.0,咱們將引入開源項目:spring-cloud-security和spring-security-oauth2,添加以下依賴。
auth-server項目:
compile("org.springframework.boot:spring-boot-starter-security")
compile("org.springframework.security.oauth:spring-security-oauth2:2.0.6.RELEASE")
完整代碼,可查看auth-server/build.gradle文件。
product-api-service項目:
compile("org.springframework.cloud:spring-cloud-starter-security:1.0.0.RELEASE")
compile("org.springframework.security.oauth:spring-security-oauth2:2.0.6.RELEASE")
完整代碼,能夠查看product-api-service/build.gradle文件。
2.2 AUTH-SERVER
受權服務器(Authorization Server)的實現比較簡單直接。可直接使用@EnableAuthorizationServer標註。接着使用一個配置類註冊已批准的Client端應用,指定client-id、client-secret、以及容許的授予流程和範圍:
@EnableAuthorizationServer
protected static class OAuth2Config extends AuthorizationServerConfigurerAdapter {
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("acme")
.secret("acmesecret")
.authorizedGrantTypes("authorization_code", "refresh_token", "implicit", "password", "client_credentials")
.scopes("webshop");
}
}
顯然這一方法僅適用於開發和測試場景模擬Client端應用的註冊流程,實際應用中採用OAuth Authorization Server,如LinkedIn或GitHub。
完整的代碼,能夠查看AuthserverApplication.java。
模擬真實環境中Identity Provider的用戶註冊(OAuth術語稱爲Resource Owner),經過在文件application.properties中,爲每個用戶添加一行文本,如:
security.user.password=password
完整代碼,能夠查看application.properties文件。
實現代碼也提供了2個簡單的web用戶界面,用於用戶認證和用戶准許,詳細能夠查看源代碼:
2.3 PRODUCT-API-SERVICE
爲了讓API代碼實現OAuth Resource Server的功能,咱們只須要在main方法上添加@EnableOAuth2Resource標註:
@EnableOAuth2Resource
public class ProductApiServiceApplication {
完整代碼,能夠查看ProductApiServiceApplication.java。
API服務代碼的實現和Part 2中的組合服務代碼的實現很類似。爲了驗證OAuth工做正常,咱們添加了user-id和access token的日誌輸出:
@RequestMapping("/{productId}")
@HystrixCommand(fallbackMethod = "defaultProductComposite")
public ResponseEntity<String> getProductComposite(
@PathVariable int productId,
@RequestHeader(value="Authorization") String authorizationHeader,
Principal currentUser) {
LOG.info("ProductApi: User={}, Auth={}, called with productId={}",
currentUser.getName(), authorizationHeader, productId);
...
備註:
1/ Spring MVC 將自動填充額外的參數,如current user和authorization header。
2/ 爲了URL更簡潔,咱們從@RequestMapping中移除了/product。當使用Edge Server時,它會自動添加一個/product前綴,並將請求路由到正確的服務。
3/ 在實際的應用中,不建議在log中輸出訪問令牌(access token)。
2.4 更新Edge Server
最後,咱們須要讓Edge Server轉發OAuth訪問令牌到API服務。很是幸運的是,這是默認的行爲,咱們沒必要作任何事情。
爲了讓URL更簡潔,咱們修改了Part 2中的路由配置:
zuul:
ignoredServices: "*"
prefix: /api
routes:
productapi: /product/**
這樣,可使用URL:http://localhost:8765/api/product/123,而沒必要像前面使用的URL:http://localhost:8765/productapi/product/123。
咱們也替換了到composite-service的路由爲到api-service的路由。
完整的代碼,能夠查看application.yml文件。
首先啓動RabbitMQ:
$ ~/Applications/rabbitmq_server-3.4.3/sbin/rabbitmq-server
如在Windows平臺,須要確認RabbitMQ服務已經啓動。
接着啓動基礎設施微服務:
$ cd support/auth-server; ./gradlew bootRun
$ cd support/discovery-server; ./gradlew bootRun
$ cd support/edge-server; ./gradlew bootRun
$ cd support/monitor-dashboard; ./gradlew bootRun
$ cd support/turbine; ./gradlew bootRun
最後,啓動業務微服務:
$ cd core/product-service; ./gradlew bootRun
$ cd core/recommendation-service; ./gradlew bootRun
$ cd core/review-service; ./gradlew bootRun
$ cd composite/product-composite-service; ./gradlew bootRun
$ cd api/product-api-service; ./gradlew bootRun
如在Windows平臺,能夠執行相應的bat文件-start-all.bat。
一旦微服務啓動完成,並註冊到服務發現服務器(Service Discovery Server),會輸出以下日誌:
DiscoveryClient ... - registration status: 204
如今已經準備好嘗試獲取訪問令牌,並使用它安全地調用API接口。
OAuth 2.0規範定義了4種授予方式,獲取訪問令牌:
更詳細信息,可查看Jenkov - OAuth 2.0 Authorization。
備註:Authorization Code 和Implicit是最經常使用的2種方式。如前面2種方式不使用,其餘2種適用於一個特殊場景。
接下來看看每個授予流程是如何獲取訪問令牌的。
4.1 受權代碼許可(Authorization Code Grant)
首先,咱們經過瀏覽器獲取一個代碼許可:
http://localhost:9999/uaa/oauth/authorize? response_type=code& client_id=acme& redirect_uri=http://example.com& scope=webshop& state=97536
先登陸(user/password),接着重定向到相似以下URL:
http://example.com/?
code=IyJh4Y&
state=97536
備註:在請求中state參數設置爲一個隨機值,在響應中進行檢查,避免cross-site request forgery攻擊。
從重定向的URL中獲取code參數,並保存在環境變量中:
CODE=IyJh4Y
如今做爲一個安全的web服務器,使用code grant獲取訪問令牌:
curl acme:acmesecret@localhost:9999/uaa/oauth/token \
-d grant_type=authorization_code \
-d client_id=acme \
-d redirect_uri=http://example.com \
-d code=$CODE -s | jq .
{
"access_token": "eba6a974-3c33-48fb-9c2e-5978217ae727",
"token_type": "bearer",
"refresh_token": "0eebc878-145d-4df5-a1bc-69a7ef5a0bc3",
"expires_in": 43105,
"scope": "webshop"
}
在環境變量中保存訪問令牌,爲隨後訪問API時使用:
TOKEN=eba6a974-3c33-48fb-9c2e-5978217ae727
再次嘗試使用相同的代碼獲取訪問令牌,應該會失敗。由於code其實是一次性密碼的工做方式。
curl acme:acmesecret@localhost:9999/uaa/oauth/token \
-d grant_type=authorization_code \
-d client_id=acme \
-d redirect_uri=http://example.com \
-d code=$CODE -s | jq .
{
"error": "invalid_grant",
"error_description": "Invalid authorization code: IyJh4Y"
}
4.2 隱式許可(Implicit Grant)
經過Implicit Grant,能夠跳過前面的Code Grant。可經過瀏覽器直接請求訪問令牌。在瀏覽器中使用以下URL地址:
http://localhost:9999/uaa/oauth/authorize? response_type=token& client_id=acme& redirect_uri=http://example.com& scope=webshop& state=48532
登陸(user/password)並驗證經過,瀏覽器重定向到相似以下URL:
http://example.com/#
access_token=00d182dc-9f41-41cd-b37e-59de8f882703&
token_type=bearer&
state=48532&
expires_in=42704
備註:在請求中state參數應該設置爲一個隨機,以便在響應中檢查,避免cross-site request forgery攻擊。
在環境變量中保存訪問令牌,以便隨後訪問API時使用:
TOKEN=00d182dc-9f41-41cd-b37e-59de8f882703
4.3 資源全部者密碼憑證許可(Resource Owner Password Credentials Grant)
在這一場景下,用戶沒必要訪問web瀏覽器,用戶在Client端應用中輸入憑證,經過該憑證獲取訪問令牌(從安全角度而言,若是你不信任Client端應用,這不是一個好的辦法):
curl -s acme:acmesecret@localhost:9999/uaa/oauth/token \
-d grant_type=password \
-d client_id=acme \
-d scope=webshop \
-d username=user \
-d password=password | jq .
{
"access_token": "62ca1eb0-b2a1-4f66-bcf4-2c0171bbb593",
"token_type": "bearer",
"refresh_token": "920fd8e6-1407-41cd-87ad-e7a07bd6337a",
"expires_in": 43173,
"scope": "webshop"
}
在環境變量中保存訪問令牌,以便在隨後訪問API時使用:
TOKEN=62ca1eb0-b2a1-4f66-bcf4-2c0171bbb593
4.4 Client端憑證許可(Client Credentials Grant)
在最後一種狀況下,咱們假定用戶沒必要准許就能夠訪問API。在這種狀況下,Client端應用進行驗證本身的受權服務器,並獲取訪問令牌:
curl -s acme:acmesecret@localhost:9999/uaa/oauth/token \
-d grant_type=client_credentials \
-d scope=webshop | jq .
{
"access_token": "8265eee1-1309-4481-a734-24a2a4f19299",
"token_type": "bearer",
"expires_in": 43189,
"scope": "webshop"
}
在環境變量中保存訪問令牌,以便在隨後訪問API時使用:
TOKEN=8265eee1-1309-4481-a734-24a2a4f19299
如今,咱們已經獲取到了訪問令牌,能夠開始訪問實際的API了。
首先在沒有獲取到訪問令牌時,嘗試訪問API,將會失敗:
curl 'http://localhost:8765/api/product/123' -s | jq .
{
"error": "unauthorized",
"error_description": "Full authentication is required to access this resource"
}
OK,這符合咱們的預期。
接着,咱們嘗試使用一個無效的訪問令牌,仍然會失敗:
curl 'http://localhost:8765/api/product/123' \
-H "Authorization: Bearer invalid-access-token" -s | jq .
{
"error": "access_denied",
"error_description": "Unable to obtain a new access token for resource 'null'. The provider manager is not configured to support it."
}
再一次如期地拒絕了訪問請求。
如今,咱們嘗試使用許可流程返回的訪問令牌,執行正確的請求:
curl 'http://localhost:8765/api/product/123' \
-H "Authorization: Bearer $TOKEN" -s | jq .
{
"productId": 123,
"name": "name",
"weight": 123,
"recommendations": [...],
"reviews": [... ]
}
OK,此次工做正常了!
能夠查看一下api-service(product-api-service)輸出的日誌記錄。
2015-04-23 18:39:59.014 INFO 79321 --- [ XNIO-2 task-20] o.s.c.s.o.r.UserInfoTokenServices : Getting user info from: http://localhost:9999/uaa/user
2015-04-23 18:39:59.030 INFO 79321 --- [ctApiService-10] s.c.m.a.p.service.ProductApiService : ProductApi: User=user, Auth=Bearer a0f91d9e-00a6-4b61-a59f-9a084936e474, called with productId=123
2015-04-23 18:39:59.381 INFO 79321 --- [ctApiService-10] s.c.m.a.p.service.ProductApiService : GetProductComposite http-status: 200
咱們看到API 聯繫Authorization Server,獲取用戶信息,並在log中打印出用戶名和訪問令牌。
最後,咱們嘗試使訪問令牌失效,模擬它過時了。能夠經過重啓auth-server(僅在內存中存儲了該信息)來進行模擬,接着再次執行前面的請求:
curl 'http://localhost:8765/api/product/123' \
-H "Authorization: Bearer $TOKEN" -s | jq .
{
"error": "access_denied",
"error_description": "Unable to obtain a new access token for resource 'null'. The provider manager is not configured to support it."
}
如咱們的預期同樣,以前能夠接受的訪問令牌如今被拒絕了。
多謝開源項目spring-cloud-security和spring-security-auth,咱們能夠基於OAuth 2.0輕鬆設置安全API。而後,請記住咱們使用的Authorization Server僅適用於開發和測試環境。
在隨後的文章中,將使用ELK 技術棧(Elasticsearch、LogStash和Kibana)實現集中的log管理。
英文原文連接:
構建微服務(Blog Series - Building Microservices)
http://callistaenterprise.se/blogg/teknik/2015/05/20/blog-series-building-microservices/