选拔OAuth、Identity创制WebApi认证接口供客户端调用

前言

      今后的web
app基本上皆从前后端分离,以前接触的大多数利用场景最后产品都以布局在同一个站点下,那么随着WebApi(Restful
api)的发展前后端实现的一点壹滴分开,前端不在后端框架的页面基础上支付,也就告别守旧上的Session判断客户端登6用户的场馆。OAuth已公布很久,Asp.Net
 Identity也透露很久。看了几篇朋友写的博客才把那多少个sample写完,也消除了前头自身对上下端完全分离发生的部分吸引。

 

OAuth2.0的4种角色

  • resource
    owner财富全体者:比如twitter用户,他在twitter的多少便是能源,他自个儿正是那些财富的主人
  • resource
    server财富服务器:保存财富的服务器,外人要拜访受限制的财富就要出示
    Access Token(访问另牌)
  • client客户端:3个通过授权后,能够代表财富全部者访问能源服务器上受限制财富的一方。比如
    开发者开发的利用
  • authorization server授权服务器:对
    能源全数者进行求证,认证通过后,向 客户端发放 Access Token(访问另牌

OAuth2.0取得Access Token的4种方式

  • 授权码方式(authorization code)
  • 简化方式(implicit)
  • 密码方式(resource owner password credentials)
  • 客户端方式(client credentials)

使用Owin完结密码情势(OAuth二.0密码方式)

一、使用VS20一五成立二个Empty WebApi项目。

2、使用Nuget导入宗旨命名空间。

    Install-Package Microsoft.AspNet.WebApi.Owin

    Install-Package
Microsoft.Owin.Host.SystemWeb

3、添加Owin入口类

   
 Startup类上平添了OwinStartup属性,代表那些类作为Owin的输入。

[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);
        }
    }
}

  

四、修改WebApiConfig。修改最终两句代码,首要以CamelCase命名法种类化webApi的回来结果。

namespace AspNet_Identity_Demo
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API 配置和服务

            // Web API 路由
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            //用json的方式返回webapi接口返回值
            var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
            jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        }
    }
}

  

伍、删除Global.asax。添加Startup类后权且用不到那些类。

6、添加Asp.Net Identity。先添加Identity类库。

    Install-Package Microsoft.AspNet.Identity.Owin

    Install-Package
Microsoft.AspNet.Identity.EntityFramework

   
第叁个包提供Asp.Net Identity Owin帮忙,第二个则提供了基于EF SQL
Server的Owin完成。那里要提下Microsoft.AspNet.Identity.Core包,那里最首若是Asp.net
Identity达成的相关接口,比如IUser、IRole、IPasswordHasher、IUserStore<TUser>、IUseRoleStore<TUser>、IRoleStore<TUser>、IClamisIdentityFactory<TUser>、UserManager<TUser>、IdentiyResult。 

 
 在其次个包中大家会首先观望IdentityDbContext<TUser>、IdentityUser、IdentityRole、UserStore。你想根据本人的用户系统扩大创立用户类继承IUser大概IdentityUser.
假设想换其余数据库则自定义DbContext。 

 

7、创建AuthContext。 

namespace AspNet_Identity_Demo.Models
{
    public class AuthContext:IdentityDbContext<IdentityUser>
    {
        public AuthContext() : base("AuthContext")
        { }
    }
}

 Web.config中增加connectionString

<add name="AuthContext" connectionString="Data Source=.;User Id=sa;password=111111;Initial Catalog=AspNet_Identity;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />

  

8、在Models文件夹中开创UserModel.cs

public class UserModel
    {
        [Required]
        [Display(Name ="User Name")]
        public string UserName { get; set; }
        [Required]
        [DataType(DataType.Password)]
        [StringLength(100,ErrorMessage ="The {0} must be at least {2} characters long",MinimumLength =6)]
        public string Password { get; set; }

        [Required]
        [DataType(DataType.Password)]
        [Compare("Password",ErrorMessage ="The password and confirmpassword are not matched...")]
        public string ConfirmPassword { get; set; }
    }

 

九、添加Asp.Net Identity 仓储协理类。

   
那里运用了方针形式,把您达成的UserStore.cs作为参数字传送进UserManager构造函数中。

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 IdentityUser()
            {
                UserName = model.UserName
            };

            IdentityResult result = await _userManager.CreateAsync(user,model.Password);

            return result;
        }

        public async Task<IdentityUser> FindUser(UserModel model)
        {
            IdentityUser user = await _userManager.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、添加AccountController.cs

     
 给Controller添加webapi访问前缀,笔者的是apix,访问时也正是http://localhost:8083/apix/account/register。

namespace AspNet_Identity_Demo.Controllers
{
    [RoutePrefix("apix/Account")]
    public class AccountController : ApiController
    {
        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,到了这一步就足以在您的视线之上注册用户了,使用Postman调用接口并调用接口http://localhost:8080/apix/account/register。post方式调用。参数传UserName、Password。
调用成功再次回到接口重回200.打开你的SQL
Server。调用成功的话数据库用到的几张表都会扭转。用户表是dbo.AspNetUsers.

图片 1

 

1一、添加2个数量访问controller,OrdersController。

namespace AspNet_Identity_Demo.Controllers
{
    [Authorize]
    [RoutePrefix("apix/orders")]
    public class OrdersController : ApiController
    {
        [Route]
        public IHttpActionResult Get()
        {
            return Ok(Order.CreateOrders());
        }
    }

    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 = true },
                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 = 10252,CustomerName = "Yasmeen Rami", ShipperCity = "Kuwait", IsShipped = true}
            };

            return OrderList;
        }
    }
}

 

1二、添加OAuth Bearer Token帮助类库 Install-Package Microsoft.Owin.Security.OAuth

壹3、回到Startup。添加创制token方法,首要涉及到了五个类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 OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp=true,
                TokenEndpointPath=new PathString("/token"),
                AccessTokenExpireTimeSpan=TimeSpan.FromDays(1),
                Provider=new SimpleAuthorizationServerProvider()
            };

            app.UseOAuthAuthorizationServer(option);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
        }
    }

    public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
    {
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext 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);
        }
    }
}

  访问http://localhost:8083/token
 http接口生成token。过期岁月2四钟头。SimpleAuthorizationServerProvider
在此类中落到实处用户验证和口令生成。
注意那里的ClamisIdentity。该类在命名空间:System.Security.Claims。
生成token主要是context.Validated(identity);那句代码。

     
OK,今后得以注册用户,也得以生成token了。那么今后有个难点来了,前后端完全分开后,那么肯定要落到实处跨域访问(CO奥迪Q7S)。所以你看来重写GrantResourceOwnerCredentials第三句就是添加Access-Control-Allow-Origin援救。

13、添加Asp.Net WebApi Install-Package Microsoft.Owin.Cors。在Startup.cs Configuration方法中添加app.UseCors(CorsOptions.AllowAll);

1四、生成客户端token。

   
  图片 2

  

一5、获得token后,访问数据接口。注意参数Authorization值有前缀Bearer。

图片 3

    

总结

     
总的来说Owin和Identity的筹划如故有点复杂的,约定的事物多1些。相比较微软早起的Membership则要优雅很多,原理和贯彻背后的细节还要多多挖掘,才能体味到在那之中的吸引力。比如ClamisIdentity、
UserManager、UserStore。

      德姆o下载地址:https://yunpan.cn/c6yNPKhzpQgmx (提取码:0575)

 

参考资料

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

相关文章