Authorization and sign-in for OneDrive in Microsoft Graph
要让你的App使用OneDrive API,可以使用Azure AD v2.0或者Azure AD所提供的验证服务。前者比后者新,但是不支持一些企业级别的验证服务。两者的区别可以在App authentication with Microsoft Graph查看。
如果没有特殊特殊需求,直接使用Azure AD v2.0即可。将App在Microsoft Application Registration Portal注册以获得Azure AD v.20所要求的clientID和secret。
整体流程走的是OAuth的流程,支持以下scope:
- offline_access,可以离线访问文件,需要使用OAuth的code-flow
- files.read,获取用户存储在OneDrive所有文件的只读权限
- files.read.all,files.read权限外加可以读取分享给用户的文件
- files.readwrite, 获取用户存储在OneDrive所有文件的读写权限
- files.readwrite.all,外加分享文件的读取权限
一般应用会同时请求files.readwrite offline_access
权限。
常用的验证流程包括Token flow和code flow。
token flow比较简单,但是不支持刷新,其请求URL如下:
GET https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id={client_id}&scope={scope}&response_type=token&redirect_uri={redirect_uri}
Code flow稍微复杂一点,服务端返回的是一个code,而不是token。客户端需要多一步操作,也就是那code换token。Token过期之后,客户端可以通过code来刷新token。
获取code的请求API:
GET https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id={client_id}&scope={scope}&response_type=code&redirect_uri={redirect_uri}
返回之后会把客户端重定向到redirect_uri,示例如下:
https://myapp.com/auth-redirect?code=df6aa589-1080-b241-b410-c4dff65dbf7c
通过code交互token:
POST https://login.microsoftonline.com/common/oauth2/v2.0/token
Content-Type: application/x-www-form-urlencoded
client_id={client_id}&redirect_uri={redirect_uri}&client_secret={client_secret}
&code={code}&grant_type=authorization_code
返回的token如下:
{
"token_type":"bearer",
"expires_in": 3600,
"scope":"wl.basic onedrive.readwrite",
"access_token":"EwCo...AA==",
"refresh_token":"eyJh...9323"
}
access_token用来访问API,refresh_token用来更新access_token(存活时间在expires_in中指示)
如果应用请求了offline_access范围,通过refresh_token可以请求额外的access_token:
POST https://login.microsoftonline.com/common/oauth2/v2.0/token
Content-Type: application/x-www-form-urlencoded
client_id={client_id}&redirect_uri={redirect_uri}&client_secret={client_secret}
&refresh_token={refresh_token}&grant_type=refresh_token
返回的是:
{
"token_type":"bearer",
"expires_in": 3600,
"scope": "wl.basic onedrive.readwrite wl.offline_access",
"access_token":"EwCo...AA==",
"refresh_token":"eyJh...9323"
}
注销用户登录需要执行以下操作:
- 删除access_token以及refresh_token
- 删除本地缓存
- 通过这个URL通知服务器:
GET https://login.microsoftonline.com/common/oauth2/v2.0/logout?post_logout_redirect_uri={redirect-uri}
通过在Microsoft account manage consent,用户可以主动撤销授予的访问。
参考
(未完待续)