Using OAuth, identity to create a WEBAPI authentication interface for client invocation

Source: Internet
Author: User
Tags oauth

Objective

Today's web App is basically a front-end separation, most of the previously contacted application scenario end products are deployed under the same site, then with the development of WEBAPI (Restful API) Implementation of the full separation, the front end is not on the back-end framework of the page based on development, Also say goodbye to the traditional session of the client to determine the situation of landing users. OAuth has been released for a long time and the ASP has been released for a long time. Read a few friends to write the blog to write these several sample, but also resolved before I have a complete separation of the front and back of some doubts.

The 4 roles of OAuth2.0
    • Resource owner: For example, Twitter users, his Twitter data is a resource, and he is the owner of those resources.
    • Resource Server resource server: The server that holds the resource, the person who wants to access the restricted resource will show access token (access to another card)
    • Client clients: A party that is authorized to access restricted resources on the resource server on behalf of the resource owner. For example, developer-developed applications
    • Authorization Server Licensing servers: Authenticate the resource owner, and after authentication passes, issue access tokens to the client (accessing a different
OAuth2.0 4 ways to get access tokens
    • Authorization Code mode (authorization code)
    • Simplified mode (implicit)
    • Password Mode (resource owner password credentials)
    • Client mode (credentials)
Using Owin to implement password mode (OAuth2.0 password mode)

1. Create an empty WEBAPI project using VS2015.

2. Use NuGet to import the core namespace.

install-package Microsoft. AspNet. WebApi. Owin

install-package Microsoft. Owin. Host. Systemweb
3. Add Owin Entry classThe owinstartup attribute is added to the Startup class, representing the class as the Owin entry.
[Assembly:owinstartup (typeof (Aspnet_identity_demo.startup))]namespace aspnet_identity_demo{public    class Startup    {public        void Configuration (Iappbuilder app)        {            httpconfiguration config = new Httpconfiguration ();              Webapiconfig.register (config);            App. Usewebapi (config);}}}    

  

4, modify the Webapiconfig. Modifies the last two lines of code, primarily serializing the return result of the WEBAPI with the CamelCase naming method.

namespace aspnet_identity_demo{public    static class Webapiconfig    {public        static void Register ( Httpconfiguration config)        {            //Web API Configuration and service            //Web API Routing            config. Maphttpattributeroutes ();            Config. Routes.maphttproute (                name: "Defaultapi",                routetemplate: "Api/{controller}/{id}",                defaults:new {id = Routeparameter.optional}            );            Returns the Webapi interface return value            var jsonformatter = config in json mode. Formatters.oftype<jsonmediatypeformatter> (). First ();            JsonFormatter.SerializerSettings.ContractResolver = new Camelcasepropertynamescontractresolver ();}}    }

  

5, delete global.asax. This class is temporarily unavailable after adding the startup class.

6. Add the ASP. Add the Identity class library first.

install-package Microsoft. AspNet. Identity. Owin

install-package Microsoft. AspNet. Identity. EntityFramework
The first package provides ASP. Owin support, and the second provides an EF SQL Server-based Owin implementation. Here to mention the Microsoft.AspNet.Identity.Core package, which is mainly the implementation of the ASP. NET Identity interface, such as Iuser, Irole, Ipasswordhasher, iuserstore< Tuser>, iuserolestore<tuser>, irolestore<tuser>, iclamisidentityfactory<tuser>, UserManager <TUser>, Identiyresult. in the second package we will first see identitydbcontext<tuser>, Identityuser, Identityrole, Userstore. You want to create user classes that inherit Iuser or Identityuser based on your own user system extensions. If you want to swap other databases, customize the DbContext. 7, create Authcontext.
namespace aspnet_identity_demo.models{public    class authcontext:identitydbcontext<identityuser>    { Public        Authcontext (): Base ("Authcontext")        { }    }}

Add connectionstring in Web. config

<add name= "Authcontext" connectionstring= "Data source=.; User id=sa;password=111111;initial catalog=aspnet_identity;integrated security=sspi; "ProviderName=" System.Data.SqlClient "/>

  

8. Create the UserModel.cs in the Models folder

public class Usermodel    {        [Required]        [Display (Name = ' User name ')] public        string UserName {get; set;}        [Required]        [DataType (Datatype.password)]        [Stringlength (100,errormessage = "The {0} must is at least {2} characters long", Minimumlength =6)]        public string Password {get; set;}        [Required]        [DataType (Datatype.password)]        [Compare ("Password", errormessage = "The Password and ConfirmPassword is not matched ...")]        public string ConfirmPassword {get; set;}    }

9. Add the ASP. NET Identity warehousing support class.

The strategy mode is used here, and the UserStore.cs you implement is passed into the Usermanager constructor as a parameter.

Namespace aspnet_identity_demo.models{public class Authrepository:idisposable {private Authcontext _ctx;        Private usermanager<identityuser> _usermanager;            Public Authrepository () {_ctx = new authcontext ();        _usermanager = new Usermanager<identityuser> (new Userstore<identityuser> (_CTX)); } public Async task<identityresult> Register (Usermodel model) {Identityuser user = new Ide Ntityuser () {UserName = model.            UserName}; Identityresult result = await _usermanager.createasync (User,model.            Password);        return result; } public Async task<identityuser> Finduser (Usermodel model) {Identityuser user = await _us Ermanager.findasync (model. UserName, model.            Password);        return user; } public Async task<identityuser> Finduserbyname (string username) {IDentityuser user = await _usermanager.findbynameasync (username);        return user; public void Dispose () {_ctx.            Dispose ();        _usermanager.dispose (); }    }}

  

10. Add AccountController.cs

Add the Webapi access prefix to the controller, mine is Apix, the access is also http://localhost:8083/apix/account/register.

namespace aspnet_identity_demo.controllers{[Routeprefix ("Apix/account")] public class Accountcontroller:apicontro        Ller {private Authrepository _authrepo;        Public AccountController () {_authrepo = new authrepository (); } [allowanonymous] [Route ("Register")] public async task<ihttpactionresult> Register (Usermodel Model) {if (!            Modelstate.isvalid) {return badrequest (modelstate);            } identityresult result = await _authrepo.register (model);            Ihttpactionresult Errorresult = GetError (result);            if (Errorresult! = null) {return errorresult;        } return Ok ();                } private Ihttpactionresult GetError (identityresult result) {if (result = = null) {            return Internalservererror (); } if (!result.     Succeeded) {           foreach (string err in result.)                Errors) {Modelstate.addmodelerror ("", err);                } if (Modelstate.isvalid) {return badrequest ();            } return Badrequest (Modelstate);        } return null; }    }}

OK, at this point you can register the user on your line of sight, use Postman to invoke the interface and call interface Http://localhost:8080/apix/account/register. The Post method is called. Parameter transmission username, Password. The call returned successfully to the interface returns 200. Open your SQL Server. The number of tables used by the database will be generated when the call succeeds. The user table is dbo. Aspnetusers.

11. Add a data access Controller,orderscontroller.

namespace aspnet_identity_demo.controllers{[Authorize] [Routeprefix ("Apix/orders")] public class Orderscontrolle R:apicontroller {[Route] public ihttpactionresult Get () {return Ok (Order.createorde        RS ());        }} public class Order {public int OrderID {get; set;}        public string CustomerName {get; set;}        public string Shippercity {get; set;}        Public Boolean isshipped {get; set;}            public static list<order> Createorders () {list<order> orderlist = new list<order> {new Order {OrderID = 10248, CustomerName = "Taiseer Joudeh", shippercity = "Amman", isshipped = t                 Rue}, new Order {OrderID = 10249, CustomerName = "Ahmad Hasan", shippercity = "Dubai", isshipped = false},                New Order {OrderID = 10250,customername = "Tamer Yaser", shippercity = "Jeddah", isshipped = false}, New Order {OrderID =10251,customername = "Lina Majed", shippercity = "Abu Dhabi", isshipped = false}, new Order {OrderID = 1025            2,customername = "Yasmeen Rami", shippercity = "Kuwait", isshipped = true};        return orderlist; }    }}

12. Add OAuth Bearer token support class library install-package Microsoft. Owin. Security. OAuth

13, back to startup. Add the Create token method, mainly related to the two classes Simpleauthorizationserverprovider, Oauthauthorizationserveroptions.

[Assembly:owinstartup (typeof (Aspnet_identity_demo.startup))]namespace aspnet_identity_demo{public class Startup {            public void Configuration (Iappbuilder app) {httpconfiguration config = new httpconfiguration ();            Configauth (APP);            Webapiconfig.register (config); App.            Usecors (Corsoptions.allowall); App.        Usewebapi (config); } public void Configauth (Iappbuilder app) {oauthauthorizationserveroptions option = new Oauthaut Horizationserveroptions () {allowinsecurehttp=true, tokenendpointpath=new pathstr ING ("/token"), Accesstokenexpiretimespan=timespan.fromdays (1), Provider=new Simpleauthorizat            Ionserverprovider ()}; App.            Useoauthauthorizationserver (option); App.        Useoauthbearerauthentication (New Oauthbearerauthenticationoptions ()); }} public class Simpleauthorizationserverprovider : oauthauthorizationserverprovider {public override async Task Validateclientauthentication (Oauthvalidateclien Tauthenticationcontext context) {context.        Validated ();        } public override Async Task Grantresourceownercredentials (Oauthgrantresourceownercredentialscontext context) {context.            OWINCONTEXT.RESPONSE.HEADERS.ADD ("Access-control-allow-origin", new[] {"*"}); using (authrepository _repo = new Authrepository ()) {Identityuser user =await _repo. Finduser (New Usermodel () {Username=context. Username,password=context.                Password}); if (user = = null) {context.                    SetError ("Invalid_grant", "The username or password is incorrect");                Return }} var identity = new Claimsidentity (context.            Options.authenticationtype); Identity. Addclaim (New Claim ("sub", context. UserName));            Identity.            Addclaim (New Claim ("Role", "user")); Context.        Validated (identity); }    }}

Access the Http://localhost:8083/token HTTP interface to generate tokens. The expiration time is 24 hours. Simpleauthorizationserverprovider implements user authentication and password generation in this class. Pay attention to the clamisidentity here. The class is in the namespace: System.Security.Claims. Generating tokens is mainly the context. Validated (identity); this code.

OK, now you can register the user, you can also generate tokens. So now there's a problem here, after the front and back end is completely detached, then be sure to implement cross-domain access (CORS). So you see rewrite grantresourceownercredentials the first sentence is to add access-control-allow-origin support.

13. Add the ASP . WebApi install-package Microsoft. Owin. Cors. Add App.usecors (Corsoptions.allowall) to the Startup.cs configuration method;

14, generate the client token.

15. After receiving token, access the data interface. Note The parameter authorization value has a prefix of bearer.

Summarize

In general, the design of Owin and identity is a bit complicated, the agreement of something more. Compared to Microsoft's early membership is a lot more elegant, the principle and implementation of the details behind the excavation, in order to realize the charm of one. such as Clamisidentity, Usermanager, Userstore.

Resources

Http://www.cnblogs.com/richieyang/p/4918819.html

http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/

http://www.haomou.net/2014/08/13/2014_bare_token/

Http://www.cnblogs.com/pengyingh/articles/2377968.html

Http://www.cnblogs.com/keepfool/p/5665953.html

Use OAuth, identity to create WEBAPI authentication interface for client invocation

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.