博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Authenticating to OAuth2 Services 验证OAuth2服务
阅读量:4046 次
发布时间:2019-05-24

本文共 8123 字,大约阅读时间需要 27 分钟。

In order to securely access an online service, users need to authenticate to the service—they need to provide proof of their identity. For an application that accesses a third-party service, the security problem is even more complicated. Not only does the user need to be authenticated to access the service, but the application also needs to be authorized to act on the user's behalf.

The industry standard way to deal with authentication to third-party services is the OAuth2 protocol. OAuth2 provides a single value, called an auth token, that represents both the user's identity and the application's authorization to act on the user's behalf. This lesson demonstrates connecting to a Google server that supports OAuth2. Although Google services are used as an example, the techniques demonstrated will work on any service that correctly supports the OAuth2 protocol.

Using OAuth2 is good for:

  • Getting permission from the user to access an online service using his or her account.
  • Authenticating to an online service on behalf of the user.
  • Handling authentication errors.

Gather Information

To begin using OAuth2, you need to know a few things about the API you're trying to access:

  • The url of the service you want to access.
  • The auth scope, which is a string that defines the specific type of access your app is asking for. For instance, the auth scope for read-only access to Google Tasks is View your tasks, while the auth scope for read-write access to Google Tasks is Manage Your Tasks.
  • A client id and client secret, which are strings that identify your app to the service. You need to obtain these strings directly from the service owner. Google has a self-service system for obtaining client ids and secrets. The article explains how to use this system to obtain these values for use with the Google Tasks API.

Request an Auth Token

Now you're ready to request an auth token. This is a multi-step process.

To get an auth token you first need to request the to yourmanifest file. To actually do anything useful with the token, you'll also need to add the permission.

...

Once your app has these permissions set, you can call to get the token.

Watch out! Calling methods on can be tricky! Since account operations may involve network communication, most of the methods are asynchronous. This means that instead of doing all of your auth work in one function, you need to implement it as a series of callbacks. For example:

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

In this example, OnTokenAcquired is a class that extends . calls on OnTokenAcquired with an that contains a . If the call succeeded, the token is inside the .

Here's how you can get the token from the :

private class OnTokenAcquired implements AccountManagerCallback
{ @Override public void run(AccountManagerFuture
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); ... }}

If all goes well, the contains a valid token in the key and you're off to the races. Things don't always go that smoothly, though...

Request an Auth Token... Again

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

  • An error in the device or network caused 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.
  • The cached auth token has expired.

Applications can handle the first two cases trivially, usually by simply showing an error message to the user. If the network is down or the user decided not to grant access, there's not much that your application can do about it. The last two cases are a little more complicated, because well-behaved applications are expected to handle these failures automatically.

The third failure case, having insufficient credentials, is communicated via the you receive in your (OnTokenAcquired from the previous example). If the includes an in the key, then the authenticator is telling you that it needs to interact directly with the user before it can give you a valid token.

There may be many reasons for the authenticator to return an . It may be the first time the user has logged in to this account. Perhaps the user's account has expired and they need to log in again, or perhaps their stored credentials are incorrect. Maybe the account requires two-factor authentication or it needs to activate the camera to do a retina scan. It doesn't really matter what the reason is. If you want a valid token, you're going to have to fire off the to get it.

private class OnTokenAcquired implements AccountManagerCallback
{ @Override public void run(AccountManagerFuture
result) { ... Intent launch = (Intent) result.get(AccountManager.KEY_INTENT); if (launch != null) { startActivityForResult(launch, 0); return; } }}

Note that the example uses , so that you can capture the result of the by implementing in your own activity. This is important! If you don't capture the result from the authenticator's response , it's impossible to tell whether the user has successfully authenticated or not. If the result is , then the authenticator has updated the stored credentials so that they are sufficient for the level of access you requested, and you should call again to request the new auth token.

The last case, where the token has expired, it is not actually an failure. The only way to discover whether a token is expired or not is to contact the server, and it would be wasteful and expensive for to continually go online to check the state of all of its tokens. So this is a failure that can only be detected when an application like yours tries to use the auth token to access an online service.

Connect to the Online Service

The example below shows how to connect to a Google server. Since Google uses the industry standard OAuth2 protocol to authenticate requests, the techniques discussed here are broadly applicable. Keep in mind, though, that every server is different. You may find yourself needing to make minor adjustments to these instructions to account for your specific situation.

The Google APIs require you to supply four values with each request: the API key, the client ID, the client secret, and the auth key. The first three come from the Google API Console website. The last is the string value you obtained by calling . You pass these to the Google Server as part of an HTTP request.

URL url = new URL("https://www.googleapis.com/tasks/v1/users/@me/lists?key=" + your_api_key);URLConnection conn = (HttpURLConnection) url.openConnection();conn.addRequestProperty("client_id", your client id);conn.addRequestProperty("client_secret", your client secret);conn.setRequestProperty("Authorization", "OAuth " + token);

If the request returns an HTTP error code of 401, then your token has been denied. As mentioned in the last section, the most common reason for this is that the token has expired. The fix is simple: call and repeat the token acquisition dance one more time.

Because expired tokens are such a common occurrence, and fixing them is so easy, many applications just assume the token has expired before even asking for it. If renewing a token is a cheap operation for your server, you might prefer to call before the first call to , and spare yourself the need to request an auth token twice.

转载地址:http://hagdi.baihongyu.com/

你可能感兴趣的文章
Java的对象驻留
查看>>
JVM并发机制探讨—内存模型、内存可见性和指令重排序
查看>>
如何构建高扩展性网站
查看>>
持续可用与CAP理论 – 一个系统开发者的观点
查看>>
nginx+tomcat+memcached (msm)实现 session同步复制
查看>>
c++字符数组和字符指针区别以及str***函数
查看>>
c++类的操作符重载注意事项
查看>>
c++模板与泛型编程
查看>>
WAV文件解析
查看>>
WPF中PATH使用AI导出SVG的方法
查看>>
WPF UI&控件免费开源库
查看>>
QT打开项目提示no valid settings file could be found
查看>>
Win10+VS+ESP32环境搭建
查看>>
Ubuntu+win10远程桌面
查看>>
flutter-实现圆角带边框的view(android无效)
查看>>
android 代码实现圆角
查看>>
flutter-解析json
查看>>
android中shader的使用
查看>>
java LinkedList与ArrayList迭代器遍历和for遍历对比
查看>>
drat中构造方法
查看>>