oauth2.0

原理图
流程图

1 四个角色

  • Client:客户端,这里指的是新浪微盘SDK demo;
  • Resource Owner:资源拥有者,这里指的是授权登录账户;
  • Authorization Server:授权服务器;
  • Resource Server:资源服务器,提供资源发服务器,这些资源比如用户名、相册等。

2 OAuth2.0六个流程

  • 如上图:
  • A:客户端发起授权请求,其实就是打开一个授权页面;
  • B:用户(资源拥有者)授权后,跳转回调页,回传code值。
  • C:发起授权请求,获取access_token,其实就是使用B中的code,调用接口,获取access_token。
  • D:授权服务器验证,如果通过返回access_token。
  • E:使用获得access_token申请获取资源。
  • F:资源服务器返回资源,如下图返回用户信息:
    <manifest ... >
        <uses-permission android:name="android.permission.ACCOUNT_MANAGER" />
        <uses-permission android:name="android.permission.INTERNET" />
        ...
    </manifest>

调用方法AccountManager很棘手!由于帐户操作可能涉及网络通信,大多数的方法都是异步AccountManager。这意味着,而不是做你所有的认证工作的一个功能,你需要一系列的回调函数实现。例如:

AccountManager am = AccountManager.get(this);
Bundle options = new Bundle();

am.getAuthToken(
myAccount_,                     // Account retrieved using getAccountsByType()
"Manage your tasks",            // Auth scope
options,                        // Authenticator-specific options
this,                           // Your activity
new OnTokenAcquired(),          // Callback called when a token is successfully acquired
new Handler(new OnError()));    // Callback called if an error occurs

Your first request for an auth token might fail for several reasons:

  • An error in the device or network caused AccountManager to fail.
  • The user decided not to grant your app access to the account.
  • The stored account credentials aren't sufficient to gain access to the account.

In this example, OnTokenAcquired is a class that implements AccountManagerCallback. AccountManager calls run() on OnTokenAcquired with an AccountManagerFuture that contains a Bundle. If the call succeeded, the token is inside the Bundle.

    private class OnTokenAcquired implements AccountManagerCallback<Bundle> {
    @Override
    public void run(AccountManagerFuture<Bundle> result) {
    // Get the result of the operation from the AccountManagerFuture.
    Bundle bundle = result.getResult();

    // The token is a named value in the bundle. The name of the value
    // is stored in the constant AccountManager.KEY_AUTHTOKEN.
    token = bundle.getString(AccountManager.KEY_AUTHTOKEN);
        ...
     }
    }
  • The cached auth token has expired.
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容