Authenticating to oau2services verify oau2service

Source: Internet
Author: User
Tags oauth

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
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 oau2protocol. oau2provides a single value, called
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 oau2protocol.

Using oau2is good:

  • 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 oau2, you need to know a few things about the API you're trying to access:

  • The URL of the service you want to access.
  • TheAuth 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.
  • AClient IDAndClient 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
    Getting started with the tasks API and oauth 2.0 on Android 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 requestACCOUNT_MANAGERTo yourmanifest file. to actually do anything useful with the Token, you'll also need to add
INTERNETPermission.

<manifest ... >    <uses-permission android:name="android.permission.ACCOUNT_MANAGER" />    <uses-permission android:name="android.permission.INTERNET" />    ...</manifest>

Once your app has these permissions set, you can callAccountManager.getAuthToken()To get the token.

Watch out! Calling methods onAccountManagerCan be tricky! Since account operations may involve network communication, most of
AccountManagerMethods 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,OnTokenAcquiredIs a class that extendsAccountManagerCallback.
AccountManagerCILSrun()On
OnTokenAcquiredWithAccountManagerFutureThat contains
Bundle. If the call succeeded, the token is inside
Bundle.

Here's how you can get the token fromBundle:

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);        ...    }}

If all goes well,BundleContains a valid token in
KEY_AUTHTOKENKey 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 causedAccountManagerTo 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
BundleYou receive in yourAccountManagerCallback(OnTokenAcquiredFrom the previous example). If
BundleSchemdesIntentIn
KEY_INTENTKey, 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 allowed reasons for the authenticator to returnIntent. 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
IntentTo get it.

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

Note that the example usesstartActivityForResult(), So that you can capture the result of
IntentBy implementingonActivityResult()In your own activity. This is important! If you don't capture the result from the authenticator's response
Intent, It's impossible to tell whether the user has successfully authenticated or not. If the result is
RESULT_OK, Then the authenticator has updated the stored credentials so that they are sufficient for the level of access you requested, And You shoshould call
AccountManager.getAuthToken()Again to request the new auth token.

The last case, where the token has expired, it is not actuallyAccountManagerFailure. The only way to discover whether a token is expired or not is to contact the server, and it wocould be wasteful and expensive
AccountManagerTo 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 oau2protocol 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
AccountManager.getAuthToken(). 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
AccountManager.invalidateAuthToken()And repeat the token acquisition dance one more time.

Because expired tokens are such a common occurrence, and fixing them is so easy, please 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
AccountManager.invalidateAuthToken()Before the first call
AccountManager.getAuthToken(), And spare yourself the need to request an auth token twice.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.