Home  >  Article  >  WeChat Applet  >  Force.com WeChat development series OAuth2.0 web authorization

Force.com WeChat development series OAuth2.0 web authorization

高洛峰
高洛峰Original
2017-02-25 17:18:211899browse

OAuth is an open protocol that allows users to let third-party applications obtain the user's private resources (such as user personal information, photos, videos, contact lists) stored on a website in a secure and standard manner without requiring Provide username and password to third-party applications. This article will introduce in detail the OAuth protocol and its specific implementation in WeChat.

OAuth2.0 protocol introduction

OAuth2.0 is the next version of the OAuth protocol, but it is not backward compatible with OAuth 1.0. OAuth 2.0 focuses on simplicity for client developers, while providing specialized authentication flows for web applications, desktop applications and mobile, and living room devices. OAuth 2.0 allows users to provide a token instead of a username and password to access their data stored with a specific service provider. Each token authorizes a specific website (for example, a video editing website) to access a specific resource (for example, just the videos in a certain album) within a specific period of time (for example, within the next 2 hours). In this way, OAuth allows users to authorize third-party websites to access their information stored on another service provider without sharing their access permissions or the entire contents of their data.

The specific process of OAuth2.0 authentication and authorization:

The three parties involved in the process of Oauth2.0 authentication and authorization include:

1 . Service provider, which users use to store protected resources such as photos, videos, and contact lists.

2. User, the owner of protected resources stored on the service provider.

3. Client, a third-party application that wants to access the service provider's resources, usually a website, such as a website that provides photo printing services. Before the authentication process, the client must apply for a client identity from the service provider.

The process of using OAuth for authentication and authorization is as follows:

1. The user accesses the client's website and wants to operate the user's resources stored on the service provider;

2. The client requests a temporary token from the service provider;

3. After the service provider verifies the client's identity, it grants a temporary token;

4. After the client obtains the temporary token, it directs the user to the service provider's authorization page to request user authorization. In this process, the temporary token and the client's callback connection are sent to the service provider;

5. The user enters the username and password on the service provider's web page, and then authorizes the client to access the requested resource. ;

6. After the authorization is successful, the service provider guides the user to return to the client's web page;

7. The client obtains the access token from the service provider based on the temporary token;

8. The service provider grants the client an access token based on the temporary token and the user's authorization;

9. The client uses the obtained access token to access protected files stored on the service provider. H.


WeChat webpage OAuth2.0 authorization:

If the user accesses the third-party webpage of the official account in WeChat (except Web WeChat), the official account developer can obtain the current Basic user information (including nickname, gender, city, country). Using user information, you can realize functions such as experience optimization, user source statistics, account binding, and user identity authentication.

It should be noted that the interface for obtaining basic user information (which will be introduced in the blog post later) can only obtain the user's basic information based on the user's OpenID when the user interacts with the public account, and the user's basic information can be obtained through web page authorization. For the user's basic information, there is no need for message interaction. As long as the user enters the official account's webpage, an interface requesting user authorization will pop up. After the user authorizes it, his or her basic information can be obtained (this process does not even require the user to have followed the official account.)

Below we will show the detailed development process through a specific example.

Configure the authorization callback domain name:

Before the WeChat official account requests user webpage authorization, the developer needs to first Configure the authorization callback name on the My Service page of the public platform website. It should be noted that the domain name here does not include http:// or https://. In addition, the authorization callback domain name configuration specification is the full domain name. For example, the domain name that requires web page authorization is: www.qq.com. After configuration, all pages under this domain name, such as http://www.qq.com/music.html, http: //www.qq.com/login.html can perform OAuth2.0 authentication. However, http://pay.qq.com and http://music.qq.com cannot perform OAuth2.0 authentication.

To this end, enter the service page (use the official service account or certified subscription account and find it through my service. If it is a test account, you can find it directly on the homepage) and find the OAuth2.0 web page authorization. Click the modify link on the right:

Force.com WeChat development series OAuth2.0 web authorization

Enter the domain name in the pop-up window and click the OK button to save:

Force.com WeChat development series OAuth2.0 web authorization

User Agree to authorize and obtain Code:

This step is equivalent to the second step of the OAuth2.0 authentication process introduced earlier "The client requests a temporary token from the service provider". The Code here is the temporary token. For this purpose, you can request WeChat's OAuth2 .0 interface to obtain the Code. A callback page URL needs to be specified in the parameters of this interface. For this we need to create an Apex Page. For this purpose, log in to Force.com and find the domain name. The domain name usually accessed from China is https:// ap1.salesforce.com, enter https://ap1.salesforce.com/apex/oauth2test in the browser address bar, Force.com will prompt that the page does not exist, click the "Create Page oauth2test" link to create the page:

Force.com WeChat development series OAuth2.0 web authorization

The created page is as follows. If the developer mode is enabled, the page is divided into upper and lower parts. The upper part is the display effect, and the lower part is the source code editing window. By default Force.com will apply its own top navigation, left navigation, and CSS styles to the newly created page:

Force.com WeChat development series OAuth2.0 web authorization

We tell Force by adding the following code to the first line .com do not use the default CSS style, do not display the top and left navigation bars, and the last controller attribute specifies the controller class corresponding to the apex page, similar to the aspx.cs class corresponding to the aspx page, and the mouse remains in the edit bar window, hold down the Ctrl + S key combination to save the edited code:

At this time, the corresponding oauth2testcontroller class does not exist, and the browser will report the following error:

Force.com WeChat development series OAuth2.0 web authorization

Click here The two links "Create Apex class 'public class oauth2testcontroller'" automatically create the controller class. Note that the only difference between these two links is the "with sharing" keyword. This keyword specifies that the current class has the same access rights to various objects (equivalent to data tables), fields, etc. as the currently logged in user. If not specified, Apex The page will have access to all objects and fields. After creation, there will be an additional controller class Tab in the code editing bar below:

Force.com WeChat development series OAuth2.0 web authorization

Add the code in this class as follows:

public class oauth2testcontroller { 
    public String code {get; set;} 
    public oauth2testcontroller(){ 
        code = ApexPages.currentPage().getParameters().get('code'); 
        if(String.isBlank(code)){ 
            code = 'No Code'; 
        } 
    } 
}


The 2nd line of this code defines a public attribute code. The 4th line obtains the code parameter in the URL through the ApexPages object, and then determines whether the code value is empty. If it is empty, it will prompt No. Code. Below we will see that when WeChat authorization successfully calls back this URL, the code parameter will be added to the URL.

Next, slightly modify the front page and display the obtained code value on the page:

 <apex:page standardstylesheets="false" showHeader="false" sidebar="false" controller="oauth2testcontroller"> 
     {!code} 
 </apex:page>

{!Object name} is the syntax used to display object values ​​in the Force.com Visualforce page, then Next, we need to configure the page to be accessible through the public network. To do this, after logging in to Force.com, enter Setup –> Develop –> Sites, and click on the Site Label corresponding to the site as shown below:

Force.com WeChat development series OAuth2.0 web authorization

After entering the detailed configuration page, find "Site Visualforce Page" and click the Edit button on the right:

Force.com WeChat development series OAuth2.0 web authorization

Find the oauth2test page in the left list and add it Go to the right and save the changes:

Force.com WeChat development series OAuth2.0 web authorization

You can now access it through the http://johnson0001-developer-edition.ap1.force.com/oauth2test public network address The page created earlier. Next, we can use the OAuth2 authentication interface of the WeChat platform to compose the URL and guide users to access it through WeChat. The format of the interface is as follows:

https://open.weixin.qq.com/connect/oauth2/ authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect

若提示“该链接无法访问”,请检查参数是否填写错误,是否拥有scope参数对应的授权作用域权限,其中每个参数的详细说明如下:

Force.com WeChat development series OAuth2.0 web authorization

在我们的例子里URL如下,其中scope我们指定为snsapi_userinfo,弹出授权页面:

https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx3b3aef2c09447269&redirect_uri=http://johnson0001-developer-edition.ap1.force.com/oauth2test&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect

兴许是测试账号的关系,虽然微信接口文档里提到在制定scope为snsapi_userinfo的情况下会弹出如下图左所示的授权页面,但反复尝试(乃至删除并重新关注账号)中也没有看到该页面,不过重点是我们得到了临时令牌,如下图右所示。右图实际是http://johnson0001-developer-edition.ap1.force.com/oauth2test页面,用户同意授权后跳转到(或者我遇到的实际情况是直接跳转)到redirect_uri/?CODE&state=STATE。若用户禁止授权,则重定向后不会带上code参数,仅会带上state参数redirect_uri?state=STATE。

另外特别需要说明的是,code作为换取access_token的临时票据,每次用户授权带上的code都不一样,code只能使用一次,5分钟未被使用自动过期。

Force.com WeChat development series OAuth2.0 web authorizationForce.com WeChat development series OAuth2.0 web authorization

通过Code换取网页授权access_token:

首先请注意,这里通过code换取的网页授权access_token,与基础支持中的access_token不同。公众号可通过下述接口来获取网页授权access_token。如果网页授权的作用域为snsapi_base,则本步骤中获取到网页授权access_token的同时,也获取到了 openid,snsapi_base式的网页授权流程即到此为止。 获取code后,可以通过以下接口获取access_token:

https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code

这里的CODE即为通过前面方式获得的临时令牌(票据),参数的具体说明如下:

Force.com WeChat development series OAuth2.0 web authorization

将URL直接输入到浏览器地址栏即可得到返回数据,当然真实场景里更多通过后台代码来请求,正确返回时的JSON数据包如下:

{
   "access_token":"ACCESS_TOKEN",
   "expires_in":7200,
   "refresh_token":"REFRESH_TOKEN",
   "openid":"OPENID",
   "scope":"SCOPE"
}

参数的具体说明如下:

Force.com WeChat development series OAuth2.0 web authorization

错误时微信会返回JSON数据包如下(示例为Code无效错误):

{"errcode":40029,"errmsg":"invalid code"}


在本例中获得的access_token实例如下:

{"access_token":"OezXcEiiBSKSxW0eoylIeMEUA_AZuBDY8AO0IIw270MMsvemqLvgx1HqemeXIZfzXW2d6yHCPy9cA1yHZ1jHCkwlH5Ct5Jfa1jOQm88M9LzU_O8BCKMNhN7yLlHJfOFLuf4lLTNGOOsoWYxQzYVNGw","expires_in":7200,"refresh_token":"OezXcEiiBSKSxW0eoylIeMEUA_AZuBDY8AO0IIw270MMsvemqLvgx1HqemeXIZfz_Vj5pJZlv2V5wK9EzWmxQmM07cqIAwMXOdqzlQs-NY4hiyENP4WhO4Twpko-3iY_pAPZRnGGmAVt3DirZaWIyg","openid":"ou-37t936RNZEcW0mI75RN2pdxkc","scope":"snsapi_userinfo"}

可以看到上面access_token的默认失效时间是7200秒,也就是2小时,当access_token超时后,可以通过refresh_token进行刷新,refresh_token拥有较长的有效期(7天、30天、60天、90天),当refresh_token失效后,需要用户重新授权,简化理解起见,我们在本文的最后再介绍相关技术。

 

拉取用户信息(需Scope为snasapi_userinfo):

通过access_token获取用户信息的接口如下,使用GET方法:

https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN

参数具体说明如下:

Force.com WeChat development series OAuth2.0 web authorization

本例的URL如下:

https://api.weixin.qq.com/sns/userinfo?access_token=OezXcEiiBSKSxW0eoylIeMEUA_AZuBDY8AO0IIw270MMsvemqLvgx1HqemeXIZfzXW2d6yHCPy9cA1yHZ1jHCkwlH5Ct5Jfa1jOQm88M9LzU_O8BCKMNhN7yLlHJfOFLuf4lLTNGOOsoWYxQzYVNGw&openid=ou-37t936RNZEcW0mI75RN2pdxkc&lang=zh_CN

输入浏览器访问即可得到相应的用户信息:

{"openid":"ou-37t936RNZEcW0mI75RN2pdxkc","nickname":"王浩","sex":1,"language":"zh_CN","city":"松江","province":"上海","country":"中国","headimgurl":"http:\/\/wx.qlogo.cn\/mmopen\/lqsZNvDqcXe8nBKHBPsp9YHuZXPtkzOD1uq3r3xxDicuDLKGlicNd1b371ODnn9xNBB9y9ChBSfL7tuX6m9FS8koY9Ex1iaJRDI\/0","privilege":[]}

刷新access_token:

可以通过前面在“通过Code换取网页授权access_token”小节中获得的refresh_token来调用刷新Token接口获取更新的access_token,微信在API文档里介绍refresh_token拥有较长的有效期(7天、30天、60天、90天),但实际微信的refresh_token的有效期是多长没有具体说明,如果有具体经验的朋友欢迎分享。微信刷新access_token的接口如下:

https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN

接口的具体参数定义如下:

Force.com WeChat development series OAuth2.0 web authorization

正确时返回的JSON数据包如下:

{
   "access_token":"ACCESS_TOKEN",
   "expires_in":7200,
   "refresh_token":"REFRESH_TOKEN",
   "openid":"OPENID",
   "scope":"SCOPE"
}

数据包的具体定义如下:

Force.com WeChat development series OAuth2.0 web authorization

错误时微信会返回JSON数据包如下(示例为Code无效错误):

{"errcode":40029,"errmsg":"invalid code"}

更多Force.com WeChat development series OAuth2.0 web authorization相关文章请关注PHP中文网!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn