怎样使用OAuth2集成应用进cloud foundry
本文介绍如何使用Cloud foundry APIs 通过应用程序使用内建的身份认证管理解决方案(UAA).
OAuth2简单介绍
OAuth2是个协议包含四个部分:
- 客户端应用,通常是个web应用程序
- 资源拥有者,通常是一个用户
- 资源服务器,另外一个web应用或者web service
- 鉴权服务器 Authorization Server
流程:
- 客户端重定向用户到Authorization Server
/oauth/authorize
- Authorization Server鉴权用户,获取到许可然后重定向到Client并提供一个一次性的鉴权码
- Client直接与Authorization Server 交互
/oauth/token
,交换一次性健全码为Access Token - Client使用Access Token向资源服务器请求资源
Client Application的任务
- 注册UAA获取客户id和secret。
- 不要去收集用户证书,让login Server去做这件事。
- 每个请求发送一个单独的状态参数给
/oauth/authorize
,在回调时检查。 - 不能泄漏每个token和相关持续更新的token
- 注意资源服务器拒绝接受的回应,采取适当的处理
- 如果有登录服务器,那么使用之
- 不要在cloud foundry外面记录用户,除非真的有需要。
使用UAA注册
客户端程序必须和UAA已经存在一个关系。 这是标准的OAuth2特性,必须保证平台可以控制用户通过和给用户记录空间,记录一些用户访问数据和应用的控制信息。
客户端在UAA中注册,客户端的开发者提供一个或几个回调URL去接受UAA的回调,会获得id和secret,列出用户允许访问的作用域。
{
"client_id": "app",
"client_secret": "appclientsecret",
"scope": ["cloud_controller.read",
"cloud_controller.write",
"openid", ...],
"redirect_uri": ["http://localhost"]
}
scope
字段允许客户端操作Cloud Controller(读/写)和获取用户profile数据(openid
)。
生产环境中一定要设置redirect_uri
防止黑客窃取authorization code 或者 access tokens(CSRF)
空的redirect_uri
允许用户重定向到任意uri。
鉴权
注册完的Client会获得一个id和一个secrect,在任何需要鉴权的时候都需要使用。原则上会在OAuth2 token端 /oauth/token
,token endpoint需要客户端通过标准的HTTP拿id和secrect换取token.
POST /oauth/token HTTP/1.1
Authorization: Basic YXBwOmFwcGNsaWVudHNlY3JldA==
{
access_token: FUYGKRWFG.jhdfgair7fylzshjg.o98q47tgh.fljgh,
expires_in: 43200,
client_id: app,
scope: openid,cloud_controller.read
}
设置参数
为了防止跨站请求伪造(CSRF)
使用Access Token
一旦有了token Client应用的请求中包含这个token,这样就可以保护平台上的资源。
GET /userinfo HTTP/1.1
Authorization: Bearer eYFDLKJHLKJ.DYOGFKHDLJDF.uIOFDUF
HTTP/1.1 200 OK
{
"user_id":"ec5797e2-24dd-44c9-9e92-f03d0ef9d11e",
"user_name":"marissa",
"given_name":"Marissa",
"family_name":"Bloggs",
"name":"Marissa Bloggs",
"email":"[email protected]"
}
token放在首部,不要放在表单或者参数中。
回应未鉴权或Access Denied Errors
无效或者过期的token,会得到一个401的回应。
GET /userinfo HTTP/1.1
Authorization: Bearer GARBAGE
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="UAA/oauth", error="invalid_token", error_description="Invalid access token: GARBAGE"
{
"error":"invalid_token",
"error_description":"Invalid access token: "
}
两种情况都可以重新获取token如果只是过期可以选择更新一下token。
如果访问了作用域以外的资源会得到403回应
GET /Users HTTP/1.1
Authorization: Bearer eYFDLKJHLKJ.DYOGFKHDLJDF.uIOFDUF
HTTP/1.1 403 FORBIDDEN
WWW-Authenticate: Bearer error="insufficient_scope", error_description="Insufficient scope for this resource", scope="scim.read"
{
"error":"insufficient_scope",
"error_description":"Insufficient scope for this resource","scope":"scim.read"
}
为token请求作用域
登录服务器
是UAA的UI。
登出
客户端应用样例
- Authorization Server = UAA
- Resource Server = Cloud Controller(or a locally deployed fake)
- Client = the sample application
这个样例实现以下功能
- 一个鉴权过滤器只允许有效的CF用户使用剩余的应用
- 一个主页面显示已经鉴权了的用户
/apps
页面列出当前用户部署在CF上的应用/logout
清理本地的session,给用户一个是否登出Cloud foundry的选择。