Get token and Refresh token examples via JS and Ajax

Source: Internet
Author: User
Tags oauth

Authorization code mode based on Oauth2.0 protocol

Authorization Code Mode Workflow:

(A) browser access to the JS client, JS will redirect the Web page to the authentication server (/oauth/authorize), carry ClientID and other information

(B) The user chooses whether to grant the client authorization (automatic authorization)

(C) The authentication server redirects the browser to the redirect Uri (redirection URI) with an authorization code

(D) The browser gets the authorization code and attaches an earlier "redirect Uri" to request a token from the authentication server (/oauth/token)

(E) authentication server checks authorization code and redirect URI, sends access token to client and updates token (refresh token)

In step A, the client requests the URI for authentication, which contains the following parameters:

    • Response_type: Denotes authorization type, mandatory option, where the value is fixed to "code"
    • CLIENT_ID: Indicates the ID of the client, required option
    • Redirect_uri: Represents the redirect Uri, optional
    • Scope: Represents the permission range for the request, optional
    • State: Typically randomly generated to identify the client's current status, and the authentication server returns the value as it is.

Use the JS Ajax interceptor to get token and refresh token examples for the front and back end of the project to separate the authorization.

Auth.js

Const Full_charter = ' abcdefghijklmnopqrstuvwxyzabcdefghijklmnopgrstuvwxyz '; Const Oauth_server= ' Http://localhost:9000/server '; Const Redirect_uri= ' http://localhost:8002/client-front/'; Const CLIENT_ID= ' Demo '; Const Client_secret= ' Demo '; Const Token_storage= Localstorage;//SessionstoragefunctionAjaxsetup () {$.ajaxsetup ({timeout:30000, Beforesend:function(XHR) {if( This. Url.endswith ('/oauth/token ')){                return true; }            if(GetAuth () = =NULL) {Fetchtoken (); }            varAuth =GetAuth (); if(Auth! =NULL) {Xhr.setrequestheader ("Authorization", Auth.token_type + "+Auth.access_token); } Else {                return false; }            return true; }, Complete:function(XHR, ts) {if(Xhr.status = = 401 && xhr.responseJSON.error = = ' Invalid_token ') {Refreshtoken (); }        }    });}functionGetAuth () {Let auth= Token_storage.getitem (' auth '); returnJson.parse (auth);}functionSaveauth (sresponse) {Token_storage.setitem ("Auth", Json.stringify (Sresponse));}functionClearauth () {Token_storage.removeitem (' Auth ');}functionlogout () {Token_storage.removeitem (' Auth '); Window.location.href= oauth_server+ "/logout?redirect_uri=" +Redirect_uri;}functionGetCode () {varState= "; for(vara=0;a<6;a++) { state+=full_charter[math.floor (Math.random () * 52)];}varurl = oauth_server+ "/oauth/authorize?client_id=" +client_id+ "&client_secret=" +client_secret+ "&response_ty Pe=code&state= "+state+" &redirect_uri= "+Redirect_uri; window.location=URL;//window.open (URL);}functionFetchtoken () {Let URL=window.location.toString (); if(!url.includes (' Code ') ) {GetCode (); }    if(Url.includes (' Code ') {Let code=url.substr (Url.indexof (' code= ') +5,6); Let State=url.substr (Url.indexof (' state= ') +6,6); varData={        ' Code ': Code,' State ': State,' Grant_type ': ' Authorization_code ',        ' Redirect_uri ': Redirect_uri}; $.ajax ({url:oauth_server+ "/oauth/token", type:"POST", Data:data, async:false, ContentType:' Application/x-www-form-urlencoded ', Beforesend:function(XHR) {Xhr.setrequestheader ("Authorization", ' Basic ' + base64.encode (client_id+ ': ' +Client_secret)); }, Success:function(sresponse) {Saveauth (sresponse); Console.log (' Fetch_token OK: ' + sresponse.access_token+ ' expires_in: ' +sresponse.expires_in); //window.location.href = Redirect_uri;}, Error:function(a,b,c) {Console.log (A, B, c);    }    }); }}functionRefreshtoken () {varAuth =GetAuth (); varData={            ' client_id ': client_id,' Client_secret ': Client_secret,' Grant_type ': ' Refresh_token ',            ' Refresh_token ': Auth.refresh_token}; $.ajax ({url:oauth_server+ "/oauth/token", type:"POST", Data:data, async:false, ContentType:' Application/x-www-form-urlencoded ', Success:function(sresponse) {Saveauth (sresponse); Console.log (' Refresh_token OK: ' + sresponse.access_token+ ' expires_in: ' +sresponse.expires_in); }, Error:function(a,b,c) {if(a.status==400 && a.responsejson.error== ' invalid_grant ') {Console.log (' Refresh token invalid ');            Clearauth (); }           }        });}functionChecktoken () {$.ajax ({url:oauth_server+ "/oauth/check_token", type:"Get", Async:false, data: {' token ': GetAuth (). Access_token}, ContentType:' Application/x-www-form-urlencoded ', Success:function(sresponse) {Console.log (' Check_token: ' +sresponse); }, Error:function(a,b,c) {console.log (A.responsejson); }            });}functionGetserverdata () {$.get (Oauth_server+ "/msg",function(data) {$ ("#user"). HTML (data); });} $(function() {Ajaxsetup ();});

---

Base64.js is used, the interface is as follows, click the Get Data button will send/MSG request to the authorization server to obtain a piece of text.

All browser requests are as follows:

First access/msg, return 401 no permissions, then the browser goes to/oauth/authorize to get code, then the authorization server returns 302 Redirect to the authorization login page, the user fill in the user name password after the post to/login, The authorization server is then redirected to Rediret_url, the end of which is spliced with code, the code,post sends the/oauth/token request, the authorization server returns the token information as follows, and is saved in Localstorage.

Take token information in/MSG request after obtaining token, bearer as token type

Because the data is requested across domains, the options request is sent first, requiring the server to support cross-domain:

Refresh token:

When the server returns 401, and Responsemsg is Invalid_token, token is invalidated, post the following information to/oauth/token, refresh token expiration time

Checktoken: Requires server Permitall () the request

Log out:

Slightly

Token in the authorization server:

End

Get token and Refresh token examples via JS and Ajax

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.