Ios-oauth Certification

Source: Internet
Author: User
Tags oauth

OAuth authorization

OAuth authorization is divided into four steps:

In the first step, the application requests a request token from the service provider, and the service provider validates the token back after passing. This step is initiated on the app's server because it involves an app account password, so this step is transparent to the user.

In the second step, the app uses the request token to redirect the browser to the service provider for login verification and authorization. The service provider verifies the request token and displays the information of the third party to the user, prompting the user to choose to agree or reject the authorization. If the user agrees to authorize, issue the authorized token and direct the user to the registered address of the current app. This step does not participate in the user authentication and authorization process from the start of redirection until the boot back to the registered address, ensuring that a third party cannot obtain the user's real account password.

In the third step, the service provider is exchanged for Atok with the authorized token. Third-party applications need to initiate requests on the server, with account passwords and previous tokens for Atok, a step that is transparent to the user. If the first two steps are for the service provider to authenticate the application and the user, this step is to re-authenticate the third-party application with the user and the service provider. Because the user browser redirects the result of the second step to the third step, it ensures that the redirect is to a legitimate address unless the user's DNS is hijacked. Once I was confused after the user authorization why not return directly to the Atok and need to exchange, is estimated to atok security considerations, the user browser at one end there are too many possibilities to let atok leak, the safest way is to let the third party server to obtain and custody of Atok.

Fourth, use Atok as the token to access the protected resource. Many times, permissions are available in a variety of categories. Atok contains a user's authorization credentials for an app, and, to be precise, atok a collection of the set of permissions assigned to the user when authorized. So in this step, in addition to verifying the legality of the Atok, the service provider also needs to judge whether the Atok has sufficient permissions to perform the protected operation.

Why OAuth authentication?

(Quote someone else's words)

If you drive to a hotel for dinner, you will often suffer from the lack of parking space and delay a lot of time. Is there a good way to avoid this problem? Some, I heard that some car owners are not worried about this problem. Luxury cars are generally equipped with two key types: Master key and parking key. When you get to the hotel, just give the parking key to the waiter and the waiter will take care of the parking thing. The use of this type of parking key is limited when compared to the master key: it can only start the engine and allow the car to travel for a limited distance, lock the car, but cannot open the trunk and cannot use other equipment in the vehicle. Here is a simple concept of "open authorization": With a parking key, the owner can delegate some of the car's use functions (such as starting the engine, driving a limited distance) to the waiter.

Request Token URL: Obtain an unauthorized request token service address;User Authorization URL: Gets the request token service address authorized by users;access token URL: The service address of access token in exchange for the authorized request token;Application of Sina Weibo OAuth in iOS client

NSString *string = [NSString stringwithformat:@ "https://api.weibo.com/oauth2/authorize?client_id=%@&redirect_ Uri=%@&display=mobile ", Appkey,redirect_url]; Nsurl *url = [nsurl urlwithstring:string];//user authorization request Nsurlrequest *request = [Nsurlrequest Requestwithurl:url]; Load Request interface [_webview Loadrequest:request];

Execute the above code and we'll pull up the interface below.

Enter your account information and click Login:

When you click Authorize, we can print the URL of the request object in the proxy method.

-(BOOL) WebView: (UIWebView *) WebView shouldstartloadwithrequest: (nsurlrequest *) Request Navigationtype: ( Uiwebviewnavigationtype) navigationtype{    NSLog ("Load this method when Web page load request");    According to the request object, get the request URL    //absolutestring convert the URL into a string    nsstring *string = Request. url.absolutestring;    NSLog (@ "%@", string);    return YES;}

The printing information is:

2015-09-22 13:12:14.339 weibo[1907:60b] http://www.cnblogs.com/wangyaoguo?code=16cca5f05d27854d0341c76cb334390e

We can extract the code information.

Then, according to code, initiate a request, obtain Access_token, and then initiate a request based on Access_token to obtain the microblog data.

The following code is a snippet of code that sends a Weibo message:

#import "ViewController.h" #import "ASIFormDataRequest.h" #define APPKEY @ "861851961" #define Appsecret @ " 875E13AF3AA6CB99C69A037BE7257ECF "#define Redirect_url @" Http://www.cnblogs.com/wangyaoguo "@interface    Viewcontroller () @end @implementation viewcontroller//can be loaded into the authorization interface-(void) viewdidload{[Super Viewdidload]; Stitching request Address NSString *string = [NSString stringwithformat:@ "https://api.weibo.com/oauth2/authorize?client_id=%@&    Redirect_uri=%@&display=mobile ", Appkey,redirect_url];    Convert string to URL nsurl *url = [Nsurl urlwithstring:string];    User authorization request Nsurlrequest *request = [Nsurlrequest Requestwithurl:url];    Loading the request interface, loading the interface of the input password [_webview loadrequest:request]; _webview.delegate = self;} After clicking on authorization, you can obtain the code value and initiate a request based on code-(BOOL) WebView: (UIWebView *) WebView shouldstartloadwithrequest: (Nsurlrequest *) Request Navigationtype: (uiwebviewnavigationtype) navigationtype{//According to the request object, get the URL//absolutestring convert to a string//user Grant Right, remove the code from the return value, and according to code, obtain the access token nsstring *string = Request. Url.absolutestring;    Nsrange range = [string rangeofstring:@ "code"]; if (range.location! = nsnotfound) {//String delimited with code= strings nsstring *code =[string componentsseparatedbystr        ing:@ "code="][1];        Code = [code stringbyaddingpercentescapesusingencoding:nsutf8stringencoding];                Get the license server, get the pass nsurl *url = [Nsurl urlwithstring:@ "Https://api.weibo.com/oauth2/access_token"];        Asiformdatarequest *formrequest = [Asiformdatarequest Requestwithurl:url];        Formrequest.tag = 11;        [Formrequest setpostvalue:appkey forkey:@ "client_id"];        [Formrequest setpostvalue:appsecret forkey:@ "Client_secret"];        [Formrequest setpostvalue:@ "Authorization_code" forkey:@ "Grant_type"];        [Formrequest setpostvalue:code forkey:@ "code"];        [Formrequest setpostvalue:redirect_url forkey:@ "Redirect_uri"];        Initiates an asynchronous request formrequest.delegate = self;    [Formrequest startasynchronous]; } return YES; From the returned information, extract the Access_tokeN, then send a Weibo-(void) requestfinished according to Access_token: (ASIHTTPRequest *) request; {if (Request.tag = =) {Nsdictionary *dic = [Nsjsonserialization JSONObjectWithData:request.responseData o        Ptions:nsjsonreadingmutablecontainers Error:nil];        Passport to obtain data (token) _accesstoken = [dic objectforkey:@ "Access_token"];        NSString *expirein = [dic objectforkey:@ "expires_in"];        Pass life cycle (expiry time, 5 years)//NSDate *date = [NSDate Datewithtimeintervalsincenow:[expirein doublevalue]];        NSLog (@ "date:%@", date);    Use the obtained pass to send Weibo [self sendsinaweibo]; }}//Sina Weibo-(void) sendsinaweibo{//Use a token to publish a microblog asiformdatarequest *sendrequest = [Asiformdatarequest requestwithurl:[ns    URL urlwithstring:@ "Https://api.weibo.com/2/statuses/update.json"];    Sendrequest.tag = 12;    [SendRequest setpostvalue:_accesstoken forkey:@ "Access_token"];    [SendRequest setpostvalue:@ "iOS client my first Weibo" forkey:@ "status"]; [SendRequest startasynchronous];}

Ios-oauth Certification

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.