WeChat public platform development: OAuth2.0 description

Source: Internet
Author: User
This article mainly introduces public platform development: OAuth2.0 description

Understanding OAuth2.0

First, let's take a picture of the OAuth2.0 operating mode:

We can see that the entire process is "handshaking" twice, and finally a series of requests are performed using the authorized AccessToken. the related process is described as follows:

A: A client sends A verification request to the server. These parameters are usually carried in the request.

ID, for example, appId

URL to jump to after verification (redirectUrl)

Status parameter (optional)

Scope of authorization (optional)

Response type (optional)

B: The server returns a grant authorization identifier (code by default), similar to a one-time temporary string key. If redirectUrl is provided in A, the server will perform A jump here and access redirectUrl with the grant and status parameters.

C: The page corresponding to the redirectUrl of the client. the request is initiated again with grant. this request usually carries some sensitive information:

ID

Password

Grant string (code)

Grant type (optional, the default value is code)

D: after the server verifies that the ID, password, and grant are correct, the AccessToken is returned. (note that the AccessToken here is irrelevant to the AccessToken introduced by the common and advanced interfaces and cannot be used together)

E: the client uses the AccessToken to request a series of Apis. in this process, sensitive information such as appId, Secret, and grant is no longer carried.

F: The server returns the request result.

OAuth2.0 usage

After learning about the basic principles of OAuth2.0, let's take a look at how OAuth2.0 is used in.

Assume that a user enters a public account and then opens a game webpage in the embedded browser through a link in the message. The game requires the user to log on and record the game score.

In this case, we have two processing methods:

Allow users to register and log on to the webpage (and every time they open the webpage, they may need to log on again, because the cookie stored in the built-in browser takes a very short time ), of course, this is a very poor design.

Use OAuth2.0. When a user enters this page, the user first checks whether the user is logged on. if not, the user automatically jumps to the OAuth2.0 authorization page, which then automatically performs a series of verification on the above ABCD, then, use EF to obtain the user's OpenId or even more detailed information (including the profile picture), automatically complete the login (or necessary registration) process, and then the user enters the game directly in the login status.

It can be seen that the use of OAuth2.0 greatly improves the user experience, and can be automatically bound to identify the user's OpenId.

Note that the "OAuth2.0 authorization page" mentioned above has two forms:

When the Scope in request A is snsapi_base, the entire authorization process is automatically completed, and the user's client will not display any intermediate pages, however, the authorization result can only obtain the user's OpenId (whether or not the user is concerned, of course, if the user is concerned with the user, use the user information interface in the advanced interface again, you can also use OpenId to obtain user information, but there are several corners)

When the Scope in request A is snsapi_userinfo, you need to provide an authorization page (similar to the authorization for many websites to log in using Weibo accounts and QQ accounts). only after the user agrees, get the details of the user immediately. here, the user can follow the user, or the user is not followed, and the returned content is consistent.

That is to say, the snsapi_base method can obtain the user's OpenId without knowing it. the logon registration process is fully automated, but the amount of information is limited. snsapi_userinfo requires the user to automatically complete the entire process after authorization on the specified interface, this authorization has a time period, and you need to ask the user again after the time is exceeded.

Senparc. Weixin. MP OAuth2.0 interface

SOURCE file folder: Senparc. Weixin. MP/AdvancedAPIs/OAuth

The relevant methods in source code are as follows:

Namespace Senparc. Weixin. MP. AdvancedAPIs {// Official documentation: http://mp.weixin.qq.com/wiki/index.php? Title = % E7 % BD % 91% E9 % A1 % B5 % E6 % 8E % 88% E6 % 9D % 83% E8 % 8E % B7 % E5 % 8F % 96% E7 % 94% A8 % e6 % 88% B7 % E5 % 9F % BA % E6 % 9C % AC % E4 % BF % A1 % E6 % 81% AF #. e7.AC. AC. e4.B8.80. e6.AD. a5.EF. BC.9A. e7.94.A8. e6.88.B7. e5.90.8C. e6.84.8F. e6.8E. 88. e6.9D. 83. EF. BC.8C. e8.8E. b7.E5.8F. 96 code ////// Application authorization scope ///Public enum OAuthScope {////// The Authorization page does not pop up. you can directly jump to the page and only obtain the user's openid ///Snsapi_base ,////// The Authorization page is displayed. you can obtain the nickname, gender, and location through openid. In addition, the user can obtain the user's information even if the user is not concerned, as long as the user is authorized ///Snsapi_userinfo} public static class OAuth {////// Obtain the authentication address /////////////////////
 Public static string GetAuthorizeUrl (string appId, string redirectUrl, string state, OAuthScope scope, string responseType = "code") {var url = string. Format ("https://open.weixin.qq.com/connect/oauth2/authorize? Appid = {0} & redirect_uri = {1} & response_type = {2} & scope = {3} & state = {4} # wechat_redirect ", appId, redirectUrl. urlEncode (), responseType, scope, state);/* after this step is sent, the customer will get the authorization page and return the redirectUrl page regardless of consent or rejection. * If the user agrees to the authorization, the page will jump to redirect_uri /? Code = CODE & state = STATE. The code here is used in exchange for access_token (and the access_token of the general interface is not universal) * if the user prohibits authorization, the code parameter is not included after the redirection, but the state parameter redirect_uri? State = STATE */return url ;}////// Obtain the AccessToken ////////////Code is used as the ticket for access_token. the code for each user authorization is different. the code can only be used once and will automatically expire if it is not used for 5 minutes.//////
 Public static OAuthAccessTokenResult GetAccessToken (string appId, string secret, string code, string grantType = "authorization_code") {var url = string. Format ("https://api.weixin.qq.com/sns/oauth2/access_token? Appid = {0} & secret = {1} & code = {2} & grant_type = {3} ", appId, secret, code, grantType); return CommonJsonSend. Send
 
  
(Null, url, null, CommonJsonSendType. GET );}///
  /// Refresh access_token (if needed )//////
  ///
  Enter the refresh_token parameter obtained through access_token.///
  ///
  Public static OAuthAccessTokenResult RefreshToken (string appId, string refreshToken, string grantType = "refresh_token") {var url = string. Format ("https://api.weixin.qq.com/sns/oauth2/refresh_token? Appid = {0} & grant_type = {1} & refresh_token = {2} ", appId, grantType, refreshToken); return CommonJsonSend. Send
  
   
(Null, url, null, CommonJsonSendType. GET) ;}public static OAuthUserInfo GetUserInfo (string accessToken, string openId) {var url = string. Format ("https://api.weixin.qq.com/sns/userinfo? Access_token = {0} & openid = {1} ", accessToken, openId); return CommonJsonSend. Send
   
    
(Null, url, null, CommonJsonSendType. GET );}}}
   
  
 

For detailed examples, see Senparc. Weixin. MP. Sample/Controllers/OAuth2Controller. cs and the code of the corresponding view.

Notes

You must use an authenticated service number to use the OAuth interface.

The AccessToken used in the interface and the AccessToken used in the advanced interface (including General interfaces) are irrelevant, even if they are obtained through the same AppId and Secret.

Currently, the official authorization page is not 100% stable, and sometimes it may take several times to pass. if such a situation is found, you need to make some judgments and make repeated requests, at least on the surface, so that users are not allowed to see the error page.

For security reasons, before using OAuth2.0, you need to go to "my services" in the background to set the domain name on the callback page:

For more public platform development, see OAuth2.0!

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.