Watercress oauth2.0 third-party app authorization for Mobile Platforms

Source: Internet
Author: User

Recently, I was bored looking for resources provided by the open platform and doing some third-party application training.

For Weibo open platforms, it was just a long time ago when I was doing Android, so there was no freshness.

I used to play Douban. I am still interested in some of the Douban community's resources, such as group, comment, and book, film, and music resources.

Although several interfaces have been developed after browsing the API, it is relatively weak to create an extended application.

For example, you can find that Douban has a client.

Doubanbo, like Weibo, has an official client.

At last, I felt that the group with the highest user activity was not provided. Some of the same book and movie reviews only provided an interface for searching.

I would like some, such as popular movies and comments. I finally found that I could only call RSS, and I found that the content of a single piece of information is only a description with no details.

However, since we have already done this, we can use it as a trainer. We have been working on the network layer, logic layer, and data processing of the previous project. This will happen to be very familiar with the UI control.

Next let's take a look at Douban about oauth2.0:

Douban supports three authorization flows for oauth2.0: Authorization flows for JavaScript applications running directly in the browser (User-Agent flow) Authorization flows for Web applications with servers (server-side flow) native-application flow)

Http://developers.douban.com/wiki? Title = oau2douban document.

Because IOS is a mobile client application, we mainly look at the third part. After getting familiar with the general situation, prepare the authorization module.

Let's take a look at the implementation of my client.

1. First, let's take a look at the API description in the document.

The authorization flows of flow and native-application flow are basically the same. You need to obtain the access_token in two steps. Obtain authorization_code to guide user authorization by accessing the following address in a browser, and obtain authorization_codehttps: // authorization. This address must be consistent with the callback address entered during application registration. Response_type is a required parameter. The value can be code or token. In this process, this value is an optional parameter of codescope. The range of permissions applied. If this parameter is not specified, the default scope is used. If you apply for Multiple scopes, use commas (,) to separate them. Optional state parameter. It is an additional string used to maintain the request and callback status. This parameter is appended when the authorization completes the callback. The application can determine the context based on this string. Note: This request must be an http get method such as: https://www.douban.com/service/auth2/auth? Client_id = Response & redirect_uri = https://www.example.com/back& response_type = Code & scope = shuo_basic_r, shuo_basic_w return result: when the user rejects authorization, the browser redirects to redirect_uri and attaches an error message https://www.example.com/back? Error = access_denied when the user agrees to the authorization, the browser redirects to redirect_uri and attaches autorization_codehttps: // www.example.com/back? Code = 9b73a00008

Middleware (application key or something, I believe everyone knows). Therefore, we need to embed a uiwebview control on our own. (Of course, some people will say that it is not enough to jump directly to the browser)

This will be mentioned in detail, because we need to extract a token value.

PS:

Here we mainly talk about the problem of this redirection address parameter: redirect_uri = https://www.example.com/back

This parameter is also used when applying for an application. It means that when we "authorize" or "reject" the authorization page, the browser will automatically redirect to this address page, in addition, some

Callback information, which is also mentioned above (for example you click to reject, https://www.example.com/back? Error = access_denied: Click authorization. If authorization succeeds, the token value is returned)

In fact, the significance of this redirection parameter is more I think it is actually set for a web application, because the most basic container of a Web application is a browser. After authorization or rejection, leaving the authorization page,

We must provide a new address for the browser to jump to. However, this is not necessary in mobile apps.

Therefore, you will see some information indicating that mobile clients can fill in "OOB" or something, and the best authorization method for mobile clients is also the case. A redirection address is not required and the return value is directly returned.

It doesn't feel better. Now let's take a look at the API process.

After talking about this for a long time, please fill in this parameter in the end. (This parameter is required when you apply for Douban, And it will automatically check the format, which must be a URL address ).

Considering that our mobile apps are not actually useful for this redirection address, we only need to return some additional information as a carrier.

So I wrote a "https://www.nono _ lilith.com" according to my hobby ";

Okay. For other parameters, see the document for details.

For example, the result of my authorized URL address + parameter:

    NSString *urlpath = [NSString stringWithFormat:@"https://www.douban.com/service/auth2/auth?client_id=%@&redirect_uri=%@&response_type=token&display=popup",_api_key,_redirect];.

2. Then, the response is returned after the operation is authorized or denied.

According to our client philosophy, if the authorization is successful, we take the obtained authorization code and save it, and display a prompt box Indicating the authorization is successful to the user to close the authorization interface.

Similarly, denial is the same. When we get the added value and determine that the operation is denied by the user, we also prompt or close the interface.

Here we will talk about the core points of the entire article and intercept the additional parameters returned by the redirection.

# Pragma mark uiwebviewdelegate methods-(bool) webview :( uiwebview *) webview preview :( nsurlrequest *) Request navigationtype :( uiwebviewnavigationtype) navigationtype {bool B = yes; nsstring * TargetUrl = request. URL. absolutestring; If ([_ douban_register isequaltostring: TargetUrl]) {// register and directly jump to the browser [[uiapplication sharedapplication] Openurl: [nsurl urlwithstring: _ douban_register]; B = no;} else if ([TargetUrl isequaltostring: _ resure_url]) {// deny authorization B = no; [self back];} nsange range = [TargetUrl rangeofstring: @ "https://www.nono _ lilith.com/javasaccess_token="]; If (range. length> 0) {// click authorization, and nsstring * tokenmore = [TargetUrl substringfromindex: range. location + range. length]; nsstring * token = [[tokenmore componentsseparatedbystring: @ "&"] objectatindex: 0]; nslog (@ "obtained token = % @", token ); _ delegate = (nlappdelegate *) [[uiapplication sharedapplication] Delegate]; _ delegate. islogin = yes; _ delegate. token = token; B = no; [self back];} return B;}-(void) webviewdidstartload :( uiwebview *) webview {}-(void) webviewdidfinishload :( uiwebview *) webview {// nsstring * url = webview. request. URL. absolutestring;}-(void) webview :( uiwebview *) webview didfailloadwitherror :( nserror *) error {}-(void) back {[self. navigationcontroller popviewcontrolleranimated: Yes];}

Here, we use the webview proxy method to achieve interception and redirection.

The main operations are in the first proxy method.

This method returns a bool value to control whether a webview request is required.

NSString *targetUrl = request.URL.absoluteString;

You can obtain the URL address of the webview to be loaded.

First, skip the comments of the first few lines to determine what to register. This mainly refers to intercepting the Redirection URL and its additional values.

Nsange range = [TargetUrl rangeofstring: @ "https://www.nono _ lilith.com/?access_token="]; If (range. length> 0) {// click authorization, and nsstring * tokenmore = [TargetUrl substringfromindex: range. location + range. length]; nsstring * token = [[tokenmore componentsseparatedbystring: @ "&"] objectatindex: 0]; nslog (@ "obtained token = % @", token ); _ delegate = (nlappdelegate *) [[uiapplication sharedapplication] Delegate]; _ delegate. islogin = yes; _ delegate. token = token; B = no; [self back];}

The specific method to intercept data is actually a few micro operations, depending on your own ideas. As long as it can be implemented.

This code is actually capturing redirection and intercepting tokencode. Then set bool to no, that is, you do not need to jump, or directly pop or cancel the interface.

Then the user's denial of operation is judged

Else if ([TargetUrl isequaltostring: _ resure_url]) {// deny authorization B = no; [self back];} Here's nsstring * _ resure_url = @ "https://www.nono _ lilith.com /? Error = access_denied ";

The operation is basically the same as above.

The above is basically a process authorized by Douban oauth2.0.

We can make some minor improvements here.

The page shows the two operations that we can click.

1. Douban Open Platform terms. If you click it, you will jump to the Douban homepage (currently tested). Because our webview does not return any buttons, you will want to authorize it after you have read the terms,

I found that I couldn't go back to the authorized webpage page ~~

Also, the registration operation will jump to the Douban registration interface. First of all, we will encounter the above mentioned. More importantly, when Douban registration chooses the place of residence, our embedded webview cannot provide interaction

(What attributes or parameters may be enabled, remember to start JS attributes and so on in Android). Therefore, the best and easy way is to jump to the Safari browser to perform related operations.

Therefore, I capture the URL and perform the jump operation.

The above is a processing method for authorizing the mobile client of Douban oauth2.0, because I have read a lot of APIs that are actually being improved and tested.

Finally, I want to say that the Group API is not open for Mao.

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.