Use OAuth to build WEBAPI authentication services for your own clients (ii)

Source: Internet
Author: User
Tags oauth

In the previous article, "Using OAuth to build WEBAPI authentication services for your own clients", we implemented a WEBAPI server with OAuth process 3-cipher mode (resource owner password credentials). Today we are going to implement a js+html version of the client.

First, angular client

Angular version of client code from HTTP://BITOFTECH.NET/2014/06/01/ token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/, Next we do a simple comb, convenient for everyone to use in the project.

1, a new angular module, we use Ngroute to implement a single-page program, Localstoragemodule used to store token information locally, Angular-loading-bar is a page loading progress bar.

var app = Angular.module (' Angularauthapp ', [' Ngroute ', ' localstoragemodule ', ' Angular-loading-bar ']);

2. The new constant in a constant,angular can be injected into any service and factory, and is a good helper for storing global variables.

App.constant (' Ngauthsettings ', {    apiservicebaseuri: ' http://localhost:56646/',    clientId: ' Ngauthapp '});

Address: http://localhost:56646/is our own WEBAPI address.

3, Authservice defines the login and logout logic, the login logic is we use the OAuth2.0 process 3 to obtain token of the process, once we get token also means that we log on successfully.

var _login = function (logindata) {var data = "Grant_type=password&username=" + logindata.username + "&pas        sword= "+ Logindata.password;        var deferred = $q. Defer (); $http. Post (serviceBase + ' token ', data, {headers: {' content-type ': ' Application/x-www-form-urlencoded '}}). Success ( Function (response) {if (Logindata.userefreshtokens) {localstorageservice.set (' Authorizationda Ta ', {token:response.access_token, userName:loginData.userName, RefreshToken:response.refresh_token,            Userefreshtokens:true}); } else {localstorageservice.set (' Authorizationdata ', {token:response.access_token, userName:            Logindata.username, Refreshtoken: "", userefreshtokens:false});            } _authentication.isauth = true;            _authentication.username = Logindata.username;            _authentication.userefreshtokens = Logindata.userefreshtokens;        Deferred.resolve (response); }).Error (Function (err, status) {_logout ();        Deferred.reject (ERR);        });    return deferred.promise; };

We follow the OAuth2.0 in the process of the post data, get token information saved in Localstorageservice.

3. Start Angularclient.web Project try logging in

Because of the origin policy, we need to enable cors on the WEBAPI server and open the startup class to configure Cors:

4. Once the login success means that we have the token, we can access the restricted resources by token, such as http://localhost:56646/api/orders. Just add Authorization:bearer {{token}} to each request header.

We can use angular's interception function, only need to intercept each request in the $http service, add token to the request header.

App. Config (function ($httpProvider) {    $httpProvider. Interceptors.push (' Authinterceptorservice ');});

The provider in angular is configurable, as the code above adds a Authinterceptorservice interception service.

The interception logic is also simple: if you read token in Localstorageservice, add a header.

var _request = function (config) {        config.headers = Config.headers | | {};               var authdata = localstorageservice.get (' Authorizationdata ');        if (authdata) {            config.headers.Authorization = ' Bearer ' + Authdata.token;        }        return config;    }

5, log in again, when the successful login successful call to the Http://localhost:56646/api/orders service

Ii. jquery Client

The jquery client implements the same idea, first sending a POST request for token:

var Apiservicebaseuri = ' http://localhost:56646/'; $ (' #login '). Click (function () {var data = {' Grant_type ': ' Password ', ' username ')            : $ (' #userName '). Val (), ' Password ': $ (' #password '). Val ()};                $.ajax ({Url:apiservicebaseuri + ' token ', type: "POST", Data:data, DataType: ' JSON ', success:function (data) {$.cookie ("token", Data.access_token)                    ;                GetOrders (); }, Error:function (XMLHttpRequest) {$ ("#message"). HTML (xmlHttpRequest.responseJSON.err                    Or_description);                $ ("#message"). Show (); }            });

Tokens are saved in a cookie once they have been successfully acquired. Next take token to access the Restricted service:

var getorders = function () {            $.ajax ({                beforesend:function (xhr) {                    xhr.setrequestheader (' Authorization ', ' Bearer ' + $.cookie ("token"))                ,                Url:apiservicebaseuri + ' api/orders ',                type: ' GET ',                dataType: ' JSON ' ,                success:function (data) {                    showordertable (data);}}            );        }

Through Xhr.setrequestheader (' Authorization ', ' Bearer ' + $.cookie ("token")); The way to add tokens to the request header, relatively angular interception scheme, this scheme is more cumbersome, each HTTP request has to add this line of code.

All code synchronization updates in Https://git.oschina.net/richieyangs/OAuthPractice.git

Use OAuth to build WEBAPI authentication services for your own clients (ii)

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.