1. What
& Why
OAuth
1.1 what isOAuth
?
Specifically, this article is about using OAuth2.0 in WordPress. OAuth2.0 is a secure protocol that enables the use of the same user system in different systems to achieve the protection of resources in different systems.
Specific please refer to ruan Yifeng teacher’s article, the introduction is very good, this article will not spend too much space to discuss the concept.
1.2 Why use itOAuth
?
If we use WordPress as a portal site, a lot of resources are actually stored on WordPress. When we use other systems to access and make statistics on WordPress resources, we need to have permission to access resources on WordPress, so we need to use OAuth to solve this problem.
2. Authorization Code
process
OAuth2 provides four working modes, the most common and most widely used of which is Authorization Code. For details of his workflow and working principle, please refer to this article by Teacher Ruan Yifeng.
In this article, we will cover only a simple process.
2.1 Let’s first explain some nouns to facilitate everyone’s understanding:
Resource Owner
: The owner of the resource, in this caseWordPress
Because theWordPress
Save all the resources we want to access.Authorization Server
: authorization server, that is, implementedOAuth2
Or in this caseWordPress
Because we are going to be inWordPress
Enabled onOAuth2
.Client
: a system to request resources. In this example, we did oneDemo
To get the current loginWordPress
And get some information about the user.
2.2 simpleAuthorization Code
The working process
- The user to access
Client
system - Click on the
Client
The login button in theAuthorization Server
Login page provided - On the login page, go to
Authorization Server
Will jump back toClient
system Client
callAuthroization Server
To provide theapi
To obtainaccess-token
Client
Use to getaccess-token
callResource Owner
On theAPI
To obtain the corresponding resources
3. WordPress
enableOAuth
3.1 installationWP-OAuth-Server
-
Dashboard
->Plugins
->Add New
-
The search request
-
Select Wp-oauth-server, install & Activate
3.2 to modifySettings
-
Dashboard
->OAuth Server
->Settings
-
Enable OAuth Server
3.3 newClient
-
Dashboard
->OAuth Server
->Clients
->Add New Client
-
Fill in the Client Name
-
Check Authorization Code. This is the only option in the free version
3.4 Writing a Client
Dashboard
->OAuth Server
->Clients
- Click on what you just created
Client
- Keep in mind that
ClientID
withClientSecret
, which is needed when writing the client - write
index.html
<html>
<head>
<title>This is a test for WP-OAuth!!</title>
<link rel="stylesheet" href="index.css">
</head>
<body>
<h1>This is a test for WP-OAuth!!</h1>
<! --http://<authorization-server>/oauth/authorize? client_id=<client_id>&redirect_url=<client-site>&response_type=code-->
<a id="hyplinkLogin" href="https://yafeya-ncs.japaneast.cloudapp.azure.com/oauth/authorize?client_id=nU55y6BAEhaxwWn5A72BmiMcsLnPWCoyLyzjIFXa&redi rect_uri=https://yafeya-ncs.japaneast.cloudapp.azure.com/wp-oauth-client-demo/&response_type=code">Login</a>
<button id="btnToken">Get Token</button>
<div id="user_infos" class="hide"></div>
</body>
<script src="axios.min.js"></script>
<script src="index.js"></script>
</html>
Copy the code
The URL corresponding to login is the login page corresponding to the Authorization Server that we want to jump to.
Format is the HTTP (s) : / / < authorization – server > / request/the authorize? client_id=
&redirect_url=
&response_type=code
Authorization-server: indicates the address of wordpress
Client_id: INDICATES the ID of the previously created client
Redirect_url: indicates the url of the page to be redirected to after a successful login
- write
index.js
-
- From the page that jumps back
authorization-code
This is 30s overdue
- From the page that jumps back
-
- use
authorization-code
.client_id
.client_secret
calloauth/token
To obtainaccess-token
- use
-
- use
access-token
You can callresource-api
Get the appropriate resources
- use
-
(function (document) {
const client_id = "nU55y6BAEhaxwWn5A72BmiMcsLnPWCoyLyzjIFXa";
const client_sct = "d13rI1jGYcZHTJmUgAgSzxbXdNIrP1kYgtaKNmnL";
const urlParams = new URLSearchParams(window.location.search);
const code = urlParams.get('code');
loginLink = document.querySelector("#hyplinkLogin");
tokenButton = document.querySelector("#btnToken");
tokenButton.addEventListener("click".async function (e) {
var request = {
"grant_type": "authorization_code"."code": code,
"client_id": client_id,
"client_secret": client_sct,
"redirect_uri": "https://yafeya-ncs.japaneast.cloudapp.azure.com/wp-oauth-client-demo/"
};
var headers = {
"Access-Control-Allow-Origin": "*"."Access-Control-Allow-Headers": "Authorization"."Content-Type": "application/json"
};
try {
var response = await axios.post("https://yafeya-ncs.japaneast.cloudapp.azure.com/oauth/token", request, headers);
if (response.status == 200) {
var token = response.data.access_token;
console.log(`token: ${token}`);
var auth_token = `Bearer ${token}`;
var loginResponse = await axios.get("https://yafeya-ncs.japaneast.cloudapp.azure.com/oauth/me", {
headers: {
"Authorization": auth_token
}
});
if (loginResponse.status == 200) {
var user = loginResponse.data.user_login;
var email = loginResponse.data.user_email;
var roles = loginResponse.data.user_roles;
var infoArea = document.querySelector("#user_infos");
if(infoArea){
infoArea.classList.add("display");
var information = `
user: ${user}<br/>
email: ${email}<br/>
roles: ${roles.join()}<br/>
`; infoArea.innerHTML = information; }}}}catch (error) {
console.log(error); }});if (code) {
loginLink.classList.add("hide");
tokenButton.classList.add("display");
} else {
loginLink.classList.add("display");
tokenButton.classList.add("hide");
}
})(document);
Copy the code
3.5 the deployment
Since this Demo also uses Ajax calls, there is also the problem of CORS, so I deployed this Demo page to the same gateway as WordPress to solve the problem of CORS.
In the figure above, wordpress/data/ HTML is the corresponding folder of wordpress, and Wp-oauth-client-demo is the folder of our demo page. According to the file structure shown in the figure above, modify nginx.conf as follows
server { listen 80; return 301 https://$host$request_uri; } server { listen 443 ssl; server_name _; root /var/www/html; index index.php; access_log /var/log/nginx/hakase-access.log; error_log /var/log/nginx/hakase-error.log; ssl_certificate /etc/ssl/fullchain.pem; ssl_certificate_key /etc/ssl/private.pem; ssl on; ssl_session_cache builtin:1000 shared:SSL:10m; Ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_ciphers HIGH:! aNULL:! eNULL:! EXPORT:! CAMELLIA:! DES:! MD5:! PSK:! RC4; ssl_prefer_server_ciphers on; location / { # First attempt to serve request as file, then # as directory, then fall back to displaying a 404. try_files $uri $uri/ /index.php? $args; } location ~ \.php$ { fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass wordpress:9000; fastcgi_index index.php; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param SCRIPT_NAME $fastcgi_script_name; } location ~* \.(css|gif|ico|jpeg|jpg|js|png)$ { expires max; log_not_found off; } location /wp-oauth-client-demo { index index.html; }}Copy the code
The last location /wp-oauth-client-demo defines the page specified when accessing wp-oauth-client-demo. The effect is as follows: