Using Java development to implement OAuth security authentication application _java

Source: Internet
Author: User
Tags hmac oauth prepare sha1 urlencode stringbuffer


OAuth Introduction
OAuth was co-sponsored by Blaine Cook, Chris Messina, Larry Halff and David Recordon to provide a safe and open standard for API access authorization.
Based on OAuth authentication authorization has the following characteristics:
Safety. OAuth differs from other licensing methods: OAuth authorization does not allow consumers (Consumer) to touch the user's account information (such as user name and password), but also means that consumers can apply for the authorization of the user's resources without using the user's username and password.
Open. Any consumer can use the OAuth Authentication Service, any service provider (Provider) can achieve its own OAuth certification services.
Simple. Both consumers and service providers are easy to understand and use.
The OAuth solution is shown in the following illustration.
Figure 1. OAuth Solution






As shown in Figure 1, the triangular relationship between users, consumers, and their service providers in the OAuth solution: When a user needs Consumer to provide a service for it, the service involves acquiring the user's protection resources from the service provider. OAuth Guarantee: Only if the user is explicitly authorized (step 4), the consumer can get the user's resources and use it to serve the user.
At the macro level, OAuth works in the following ways:
Consumers have established relationships with different service providers.
The consumer shares a passphrase or a public key to the service provider that the service provider uses to confirm the identity of the consumer.
The consumer redirects the user to the login page based on the service provider.
It is no problem for the user to log in and tell the service provider that the consumer has access to his protected resources.
Back to the top of the page
OAuth Authentication and authorization process
Before understanding the OAuth certification process, let's take a look at some of the basic terms defined in the OAuth protocol:


    • Consumer Key: The consumer is uniquely identified with the service provider's identity.
    • Consumer Secret: Used to confirm the consumer's own relationship to Consumer Key.
    • Request Token: Obtain a user-authorized demand token to Exchange access Token.
    • Access Token: Used to get the protected resources of the user on the service provider.
    • Token Secret: Used to confirm the consumer's own relationship to the token (Request Token and Access Token).


Figure 2. OAuth authorization Process (excerpt from OAuth specification)






For each of the implementation steps in Figure 2, the explanations are as follows:
Consumption direction OAuth The service provider requests an unauthorized request Token.
The OAuth service provider, after verifying the consumer's legitimate request, issues it with a request Token without a user's authorization and its corresponding Token Secret.
The consumer uses the resulting Request Token to guide the user through the URL to the service provider, which should be the behavior of the browser. Next, the user can authorize the request by entering the username/password information in the service provider. Once the authorization is successful, go to the next step.
The service provider leads the user back to the consumer through the URL, which is also the behavior of the browser.
After obtaining the authorized request Token, the consumer uses the authorized request Token to Exchange access Token from the service provider.
The OAuth service provider agrees to the consumer's request and issues Access Token and its corresponding Token Secret.
The consumer uses the access Token returned in the previous step to access a user-authorized resource.
In general, in the OAuth technology system, the service provider needs to provide the following basic functions:
1th, the implementation of three service endpoints, namely: To obtain an unauthorized request Token service address, obtain a user-authorized request Token service address, and the use of authorized request Token in exchange for access Toke The service address of N.
2nd, provide the user authentication based on Form, so that users can login to the service provider to make authorization.
3rd, the authorization of the management, such as users can at any time revoke the authorization has been made.
For consumers, the following basic functions are required:
1th, obtain the customer Key/customer Secret from the service provider.
2nd, provides the service provider between the HTTP based communication mechanism, in exchange for the related token.



Authorization process for OAuth



The application process you develop is as follows:


    • To the application service providers (Sina, Sohu and other micro-blog) request Request_token.
    • After getting Request_token redirect the user to the service provider's authorization page.
    • If the user chooses to authorize you to apply, uses Request_token to request the service provider to Exchange Access_token.
    • Access to restricted resources such as access_token information.


and the corresponding response of the service provider is as follows:


    • Create Request_token to return to the application.
    • Ask the user whether to authorize this application. If the user is authorized to redirect users to the application page.
    • Creates a access_token and returns it to the application.
    • Responds to a restricted resource request and returns relevant information.
    • The popular point of view is "You take your ID card (request_token) to the service provider to enter the user's door key (Access_token), the service provider to ask users and disagree, if the user agreed to give you access to the user door key (access_token) , you can go into the user's home after you get the key.


Java implementation of OAuth authorization



As an open protocol there are currently a number of off-the-shelf OAuth libraries available for developers to use, which can be downloaded here. But have the energy to have the time words or to realize the OAuth authorization process, can very good experience OAuth authentication Agreement principle. The following is my use of Java to achieve OAuth specific steps, the code is very simple, if there is the superfluous place also hope master a smile.



First, get Request_token



First you have to prepare the parameters and their origin:


    • oauth_consumer_key--registration application provided by the application service provider
    • consumer_secret--registration application provided by the application service provider
    • oauth_callback--user-Authorized return address
    • oauth_nonce--random string, make sure to be different every time
    • oauth_timestamp--time Stamp
    • oauth_signature_method--Signature Base String method, currently supports HMAC-SHA1
    • Oauth_version--oauth Protocol version


The following three request addresses are also required (these addresses will be provided to you by any service provider providing OAuth, as shown in the API documentation):


    1. requst_token_url--the request address in step 1th above
    2. authorize_url--The 2nd step above the request address
    3. access_token_url--the 3rd step above the request address


As for how to register the application, Sina Weibo, Tencent Weibo, and so on the website, there is no longer detailed description. After the registration is successful, the Oauth_consumer_key and Consumer_secret two parameters are obtained.



The role of Oauth_callback is to redirect users to this URL when the user is authorized to succeed.



Oauth_nonce is a random string. Below is my generated code:


public string set_nonce () {
string base = ' abcdefghijklmnopqrstuvwxyz0123456789 ';
Random Random = new Random ();
StringBuffer sb = new StringBuffer ();
for (int i = 0; i < i++) {int number
= Random.nextint (Base.length ());
Sb.append (Base.charat (number));
}
return sb.tostring ();
}


Oauth_timestamp is the timestamp of the request, and my code is as follows:


Public String Set_timestamp () {

Date date = new Date ();
Long time = Date.gettime ();
Return (Time + ""). substring (0);
}


The time stamp here is 10-bit instead of 13-bit, so the 0-10 position is intercepted.



The other parameters are specified directly on the line.



Next, you can assemble the base string with these parameters. The purpose of preparing the base string is to get the oauth_signature parameter, which is needed when sending the request to the service provider.



The method of assembling is to use the following 8 parts



POST (or get, depending on which application provider supports).


    • UrlEncode after the Requst_token_url.
    • After Oauth_callback=urlencode your oauth_callback (urlencode parameter is "Utf-8").
    • Oauth_consumer_key = Your Oauth_consumer_key
    • Oauth_nonce = Your oauth_nonce
    • Oauth_signature_method = Your Oauth_signature_method
    • Oauth_timestamp = Your Oauth_timestamp
    • Oauth_version = "1.0"--most OAuth currently use a 1.0 or 1.0a version.


Note that the number of other parameters, except 1 and 2, is as follows: abc= "ABC", and then first of the above 1 and 2 parts with the & number connected to the string A, 3-8 part of & connected to get string B, the following need to be a string B again urlencode get string C, and finally A and C to The & number is connected to a base string. In this process, oauth_callback essentially two times UrlEncode, assembling a base string is very error prone, accidentally missing a quotation mark or a slightly wrong format will make an error.



Here's my Java implementation code:


public string set_basestring () throws unsupportedencodingexception {
string BSS;
BSS = Oauth_request_method + "&"
+ Urlencoder.encode (requst_token_url, "utf-8") + "&";
String bsss = "oauth_callback="
+ urlencoder.encode (oauth_callback, "Utf-8")
+ "&oauth_consumer_key=" + Oauth_consumer_key + "&oauth_nonce="
+ oauth_nonce + "&oauth_signature_method="
+ oauth_signature_ Method + "&oauth_timestamp=" +
Oauth_timestamp + "&oauth_version=" + oauth_version;
BSSs = Urlencoder.encode (BSSs, "Utf-8");
return BSS + bsss;
}


With a base string, you can sign the oauth_signature this parameter, and oauth_signature will use it when requesting request_token. The signature algorithm is HMAC-SHA1, the signature key is the first consumer_secret after adding a & number, the signature algorithm code is as follows:


public string HMACSHA1 (string data, string key) {
byte[] Bytehmac = null;
try {
Mac Mac = mac.getinstance ("HmacSHA1");
Secretkeyspec spec = new Secretkeyspec (Key.getbytes (), "HmacSHA1");
Mac.init (spec);
Bytehmac = Mac.dofinal (Data.getbytes ());
} catch (InvalidKeyException e) {
e.printstacktrace ();
} catch (NoSuchAlgorithmException ignore) {
}
String OAuth = new Base64encoder (). Encode (BYTEHMAC);
return oauth;
}


The base64encoder of this class can be Google one.



When you get oauth_signature, you start sending requests to Requst_token_url, and the OAuth specification defines three ways to pass OAuth parameters:


    1. In Httpheader
    2. In the URL
    3. In post form


Domestic major micro-BO support situation is: Sina Httpheader available, NetEase Httpheader available, Tencent only support in the URL, Sohu because there is no appkey so haven't tried.



If you use Httpheader to pass the parameter header names to "Authorization", the value is the following format, and the value is changed to its own application.


OAuth oauth_nonce= "9zwh6qe0qg7lc1telcn7fhublyvdjeal3mo5uhxn8", oauth_signature_method= "HMAC-SHA1", oauth_ Timestamp= "1272323047", oauth_consumer_key= "gddmiqh6jhtmluypg82g", oauth_token= " 8LDIZYXQEVRFZXFOZH5TAWJ6VZJYULQPL0WUEYTWC ", oauth_verifier=" Pdng57prohapmbhv25rnf75lvrd6jdsni1ajjidyoty ", oauth_ Signature= "Puw%2fdha4fnljym6rhxk5iu%2f0fcc%3d", oauth_version= "1.0"

 
 


The URL and post form two methods of parameter names and parameter values are also above, exactly the same.



When the request is sent successfully, the response is as follows:


oauth_token=8ldizyxqevrfzxfozh5tawj6vzjyulqpl0wueytwc&oauth_token_secret= X6qprnlemw9jbqn4pqvvevg8zlpex6a0toebgwcua&oauth_callback_confirmed=true

 
 


You can see that the response already contains Oauth_token and Oauth_token_secret, which are stored for later use.



Second, the user authentication



After you get the Oauth_token, you need the user to oauth_token the authorization, also is to your application authorization, the concrete way is sends the Oauth_token to the service provider and requests the user to this Oauth_token authorization: realizes the method to Oauth_ Token and oauth_callback the code in the request Oauthorize_url,servlet for the parameter is as follows:



Resp.sendredirect (oauthorize_url+ "oauth_token=" +oauth_token+ "&oauth_callback=" +oauth_callback);



This is where the user is taken to the application authorization page and can choose whether to authorize the application. If the user is authorized, it will be taken to the Oauth_callback address. At the same time, if the service chamber is required to give Oauth_callback a parameter named Oauth_verifier (this parameter is used for desktop applications that cannot be jumped, not necessarily every microblogging platform will return), our Oauth_token has been authorized by the user.



Third, in exchange for Access_token with Oauth_token



This step is basically the same as the first step "get Request_token", and you need to prepare a base string to sign it, and then send the request, you can refer to the first step of the code implementation: But the corresponding parameters are not, specifically, the first step to assemble the base string The URL in the second part of the 8 section is changed to Access_token_url and removed Oauth_callback plus oauth_token (if there is a oauth_verifier it also needs to be added), When assembled, the signature is required to get oauth_signature, and the signature is the same as last time, but the key becomes Consumer_secret and Oauth_token_secret with a string of & connections.



You need to send a request to Access_token_url, which includes all parameters in base string except for the request method (post or get) and the request address, and the value and the oauth_signature generated after the signature. Examples are as follows:


OAuth oauth_nonce= "9zwh6qe0qg7lc1telcn7fhublyvdjeal3mo5uhxn8", oauth_signature_method= "HMAC-SHA1", oauth_ Timestamp= "1272323047", oauth_consumer_key= "gddmiqh6jhtmluypg82g", oauth_token= " 8LDIZYXQEVRFZXFOZH5TAWJ6VZJYULQPL0WUEYTWC ", oauth_verifier=" Pdng57prohapmbhv25rnf75lvrd6jdsni1ajjidyoty ", oauth_ Signature= "Puw%2fdha4fnljym6rhxk5iu%2f0fcc%3d", oauth_version= "1.0" "

 
 


The request will be successful service providers will return to Oauth_token and Oaut_token_secret, where Oauth_token and Oaut_token_secret is the real access to resources to use the Access_token.



It also needs to be explained that the above process only has to be done once, that is, you get the Access_token will not expire, unless the user manually will be authorized to recover, so as Access_token Oauth_token and Oaut_token_secret to save, Can be used directly in the future when accessing restricted resources. As for how to access the restricted resources, and so on after the time to fill.


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.