基于令牌的身份验证主要区别于之前经常使用的经常使用的基于cookie的身份验证,基于cookie的身份验证在B/S架构中使用比较多,可是在Web Api中因其特殊性,基于cookie的身份验证已经不适合了,由于并非每个调用api的客户端都是从浏览器发起,咱们面临的客户端多是手机、平板、或者app。html
使用基于Token令牌的身份验证有一些好处:前端
为了进行代码演示,建立一个相对比较干净的环境,咱们新建一个项目演示本次功能,本文使用Visual Studio 2017和 .NTE Framework 4.7。angularjs
在Vs中选择新建项目,选择ASP.NET Web 应用程序(.NET Framework) ,命名为OauthExample或者随便你喜欢的名字,而后下一步,选择空模板。okweb
项目右键,管理Nuget程序包,分别安装后端
Microsoft.AspNet.WebApi.Owinapi
Microsoft.Owin.Host.SystemWeb跨域
也能够在程序包管理器输入以下代码安装:浏览器
Install-Package Microsoft.AspNet.WebApi.Owin
Install-Package Microsoft.Owin.Host.SystemWeb
等待安装完成。服务器
右键项目,移除Global.asax,右键项目,添加OWIN StartUp 类,而后修改代码以下:cookie
using System.Web.Http; using Microsoft.Owin; using Owin; [assembly: OwinStartup(typeof(OAuthExample.Startup))] namespace OAuthExample { public class Startup { public void Configuration(IAppBuilder app) { // 有关如何配置应用程序的详细信息,请访问 https://go.microsoft.com/fwlink/?LinkID=316888 HttpConfiguration config = new HttpConfiguration(); WebApiConfig.Register(config); app.UseWebApi(config); } } }
简要说明
完成后编译一下,检查是否能经过,若是有问题检查一下Nuget包是否安装正确。
安装Owin包,Microsoft.Owin.Security.OAuth,再次打开StartUp文件,修改代码以下(斜体):
using System; using System.Web.Http; using Microsoft.Owin; using Microsoft.Owin.Security.OAuth; using Owin; [assembly: OwinStartup(typeof(OAuthExample.Startup))] namespace OAuthExample { public class Startup { public void Configuration(IAppBuilder app) { // 有关如何配置应用程序的详细信息,请访问 https://go.microsoft.com/fwlink/?LinkID=316888 OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions() { AllowInsecureHttp = true, TokenEndpointPath = new PathString("/oauth/token"), AccessTokenExpireTimeSpan = TimeSpan.FromDays(1), Provider = new CustomAuthorizationServerProvider() }; // Token Generation app.UseOAuthAuthorizationServer(OAuthServerOptions); app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()); HttpConfiguration config = new HttpConfiguration(); WebApiConfig.Register(config); app.UseWebApi(config); } } }
在这里,咱们从类“OAuthAuthorizationServerOptions”建立了新实例,并设置选项以下:
最后咱们将此选项传递给扩展方法“ UseOAuthAuthorizationServer”,以便将身份验证中间件添加到管道中。
在项目中添加名为“ Providers”的新文件夹,而后添加名为“ SimpleAuthorizationServerProvider”的新类,在下面粘贴代码片断:
using System.Security.Claims; using System.Threading.Tasks; using Microsoft.Owin.Security.OAuth; namespace OAuthExample.Providers { public class CustomAuthorizationServerProvider : OAuthAuthorizationServerProvider { /// <summary> /// Called to validate that the origin of the request is a registered "client_id", and that the correct credentials for that client are /// present on the request. If the web application accepts Basic authentication credentials, /// context.TryGetBasicCredentials(out clientId, out clientSecret) may be called to acquire those values if present in the request header. If the web /// application accepts "client_id" and "client_secret" as form encoded POST parameters, /// context.TryGetFormCredentials(out clientId, out clientSecret) may be called to acquire those values if present in the request body. /// If context.Validated is not called the request will not proceed further. /// </summary> /// <param name="context">The context of the event carries information in and results out.</param> public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) { context.Validated(); } /// <summary> /// Called when a request to the Token endpoint arrives with a "grant_type" of "password". This occurs when the user has provided name and password /// credentials directly into the client application's user interface, and the client application is using those to acquire an "access_token" and /// optional "refresh_token". If the web application supports the /// resource owner credentials grant type it must validate the context.Username and context.Password as appropriate. To issue an /// access token the context.Validated must be called with a new ticket containing the claims about the resource owner which should be associated /// with the access token. The application should take appropriate measures to ensure that the endpoint isn’t abused by malicious callers. /// The default behavior is to reject this grant type. /// See also http://tools.ietf.org/html/rfc6749#section-4.3.2 /// </summary> /// <param name="context">The context of the event carries information in and results out.</param> public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); //这里是验证用户名和密码,能够根据项目状况本身实现 if (!(context.UserName == "zhangsan" && context.Password == "123456")) { context.SetError("invalid_grant", "The user name 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); } } }
使用nuget安装程序包,Install-Package Microsoft.Owin.Cors
而后在Startup类中添加以下代码,最终代码以下:
using System; using System.Web.Http; using Microsoft.Owin; using Microsoft.Owin.Security.OAuth; using OAuthExample.Providers; using Owin; [assembly: OwinStartup(typeof(OAuthExample.Startup))] namespace OAuthExample { public class Startup { public void Configuration(IAppBuilder app) { // 有关如何配置应用程序的详细信息,请访问 https://go.microsoft.com/fwlink/?LinkID=316888 OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions() { AllowInsecureHttp = true, TokenEndpointPath = new PathString("/token"), AccessTokenExpireTimeSpan = TimeSpan.FromDays(1), Provider = new CustomAuthorizationServerProvider() }; // Token Generation app.UseOAuthAuthorizationServer(OAuthServerOptions); app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()); HttpConfiguration config = new HttpConfiguration(); WebApiConfig.Register(config); app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); app.UseWebApi(config); } } }
咱们添加一个测试空的Order控制,用来测试一下上面的实现:
[RoutePrefix("api/Orders")] public class OrdersController : ApiController { [Authorize] [Route("")] public IHttpActionResult Get() { return Ok(Order.CreateOrders()); } } #region Helpers 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; } } #endregion
下面使用PostMan进行模拟测试.
在未受权时,直接访问 http://localhost:56638/api/orders获得以下结果:
模拟受权访问,先获取令牌:
将令牌附加到Order请求,再次尝试访问:
能够看到已经能正常获取到数据,打开调试,看一下方法中的变量以下:
一直以为WebApi和MVC不少都同样的东西,在实际应用中仍是有很多区别,关于OAuth、JWT等等在WebApi中使用较多,本文是参照文末链接作的一个总结,细看下原po的时间都已是14年的文章了。立刻要aspnet core 3.2都要发布了,如今却还在补之前的知识,惭愧的很!
Token Based Authentication using ASP.NET Web API 2, Owin, and Identity
Enable OAuth Refresh Tokens in AngularJS App using ASP .NET Web API 2, and Owin