IOS_20 _ Weibo OAuth authorization _ Get the user's authorization accessToken, ios_20oauth

Source: Internet
Author: User
Tags oauth

IOS_20 _ Weibo OAuth authorization _ Get the user's authorization accessToken, ios_20oauth

Finally:




OauthViewController. m

//// OauthViewController. m // 20 _ handsome guy no Weibo /// Created by beyond on 14-8-5. // Copyright (c) 2014 com. beyond. all rights reserved. // authorization controller, run only once, get the current user's access_token and uid, archive, switch the main controller of the window # import "OauthViewController. h "@ interface OauthViewController () <UIWebViewDelegate> {// remember to use the UIWebView * _ webView;} @ end @ implementation OauthViewController-(void) in different methods) loadView {// directly make WebView the Controller's view, avoid adding _ webView again = [[UIWebView alloc] init]; self. view = _ webView;}-(void) viewDidLoad {[super viewDidLoad]; // you can set the proxy to the current controller to listen to webView start loading and end loading _ webView. delegate = self; // The address for applying for authentication NSString * oauthURL = [NSString stringWithFormat: @ "https://api.weibo.com/oauth2/authorize? Client_id =%@ & response_type = code & redirect_uri = % @ ", kAppKey, kRedirectURL]; // call the classification method and load the URL for applying for authentication [_ webView loadURLString: oauthURL] ;}# pragma mark-proxy method // start loading-(void) webViewDidStartLoad :( UIWebView *) webView {log (@ "really start loading -- % @", webView. request. URL); // display the progress bar MBProgressHUD * hud = [MBProgressHUD showHUDAddedTo: webView animated: YES]; hud. labelText = @ "loading the page... ";}// whether to start loading a page-(BOOL) webView :( UIWebVi Ew *) webView shouldStartLoadWithRequest :( NSURLRequest *) request navigationType :( UIWebViewNavigationType) navigationType {log (@ "Can I load -- % @", webView. request. URL); return YES;} // page Load completed-(void) webViewDidFinishLoad :( UIWebView *) webView {log (@ "Load completed -- % @", webView. request. URL); // after loading, hide the progress bar [MBProgressHUD hideAllHUDsForView: webView animated: YES]; // After the user agrees to the authorization, the returned URL contains the authorized request_code, such as: http://www.abc.com /? Code = 888888888888 // After the user-authorized request_code page is returned, you need to intercept the code, splice the url, and initiate 3rd requests (this time, POST is required ), finally, the required access_token NSString * reDirectURLContainsCode = _ webView is returned. request. URL. absoluteString; // The classification method, starting from the end of the string marked on the left, truncates the remaining string NSString * code = [reDirectURLContainsCode subStrFromLeftFlagStr :@"? Code = "]; // if it is not the url of the returned code, do not do anything if (code = nil) return; // You are now ready to initiate the last request, concatenate the URL required for 3rd requests. The returned result of this request is the accesen en of the most important user. It also contains the user's uid NSString * accessTokenRequestURLStr = [NSString stringWithFormat: @ "https://api.weibo.com/oauth2/access_token? Client_id =%@ & client_secret =%@ & grant_type = authorization_code & redirect_uri =%@ & code =%@ ", kAppKey, kAppSecret, kRedirectURL, code]; // 1, create url nsurl * accessTokenRequestURL = [NSURL URLWithString: Required]; // 2. Create a post request named * mutRequest = [[delealloc] initWithURL: accessTokenRequestURL cachePolicy: Required timeoutInterval: 10]; // set the request method to post. The default value is GET [mutRequest setHTTPMethod: @ "POST"]; // 3. Connect to the server and receive the returned data NSData * receivedData = [NSURLConnection sendSynchronousRequest: mutRequest returningResponse: nil error: nil]; // convert the data returned by the server to a string (essentially JSON data) NSString * responseStr = [[NSString alloc] initWithData: receivedData encoding: NSUTF8StringEncoding] log (@ "Response json is: % @", responseStr); // 4, get access_token from responseStr (essentially JSON data) // (JSON data) convert to dictionary NSDictionary * dictionary = [NSJSONSerialization JSONObjectWithData: receivedData options: Unknown error: nil]; // obtain access_token NSString * access_token = [dictionary objectForKey: @ "access_token"]; log (@ "access token is: % @", access_token); // obtain the uid NSString * uid = [dictionary objectForKey: @ "uid"]; log (@ "uid is: % @", uid); // authorization successful, switch the root controller to the master controller UIActionSheet * actionSheet = [[UIActionSheet alloc] initWithTitle: @ "Authorization successful" delegate: nil cancelButtonTitle: @ "cancel" destructiveButtonTitle: @ "OK" principal: nil]; [actionSheet showInView: self. view. window];} @ end











Note:

Step 2,

Register as a developer. After verifying the email address, you can create a mobile application,

Write downAPPKey and APPSecret,

In the advanced information of the application information, set the address of the authorization completed callback page.Redirect_URI

Because it is a mobile client, not a web application,

Therefore, when creating an application,Redirect_URIYou can write at will,

However, the same address must be used globally.Redirect_URI








Step 2,

Apply for unauthorized request_code,

The essence is comingWeibo login page, That is, _ webView's first loaded url


The address format is as follows:

Https://api.weibo.com/oauth2/authorize? Client_id = APPKEY & response_type = code & redirect_uri = https://api.weibo.com/oauth2/default.html


APPKEY is the unique application ID automatically generated by the system when an application is created.

Redirect_uri, which must be consistent with the one you entered when creating the application



Step 2,

After entering the account and password, click log on,

The page is automatically redirected to the authorization page,

If you click the authorization button, the page will be redirected to http: // redirectURL /? Codes = 888888888888,

The task is to intercept the code value (Different every time),

This code is actuallyAuthorized request_code,

However, it is only a man-in-the-middle and cannot be used to obtain user information.


The address format is as follows:

Https://api.weibo.com/oauth2/default.html? Code = fa4efb6311611f948423e69adeabec08



Step 2,

Use the code intercepted in step 1 to assemble the url again,

Initiate the last request (must be a POST request ),

In this case, the data returned by the server is a json data,

It contains three key-value pairs

{

"Access_token": "This is the real ACCESS_TOKEN ",

"Remind_in": "157679999 ",

"Expires_in": 157679999,

"Uid": "uid of the authorized user"

}






On Sina Weibo's open platform, how does one apply for the accesstoken and accesstokensecret that have been authenticated by oauth?

I don't know much about java, but in c #, I have been using oauth for authorization. I also have a question: Who can extract the birthday of members on Sina Weibo?

For android, How can I save the oauth authorization with the logged-on user after obtaining the access token?

1. During the first authorization, you can save the token and secret in the SharedPreferences or SQLite database. The next login check reads the check first.
2. Search for "ppy2790 blog" in Baidu, including Sina Weibo Android Development Project, source code, and OAuth certification.

Related Article

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.