IOS _ Weibo OAuth authorization _ getting user authorization accessToken
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. After obtaining the access_token and uid of the current user, archive and switch the main controller of the window # import OauthViewController. h @ interface OauthViewController ()
{// Member variables remember that UIWebView * _ webView should be used in different methods;} @ end @ implementation OauthViewController-(void) loadView {// directly make WebView a controller view, avoid adding _ webView = [[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 requesting 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 page ...;} // whether to start loading a page-(BOOL) webView :( UIWebView *) WebView shouldStartLoadWithRequest :( NSURLRequest *) request navigationType :( UIWebViewNavigationType) navigationType {log (@ Can load -- % @, webView. request. URL); return YES;} // page Load completed-(void) webViewDidFinishLoad :( UIWebView *) webView {log (@ loaded -- % @, 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, as shown in: 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, intercepting 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 preparing to initiate the last request now, 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 failed: receivedData options: Invalid error: nil]; // obtain access_token NSString * access_token = [dictionary objectForKey: @ access_token] through the key; log (@ access token is: % @, access_token); // obtain the uid NSString * uid = [dictionary objectForKey: @ uid] through the key; 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: @ confirm otherButtonTitles: 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.
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
}