一,二文章我们讲了WebApi的创建,部署,下面我们来点干货Oauth身份认证
1.安装所需的NuGet包:
1.Microsoft.AspNet.WebApi.Owin
2.Microsoft.Owin.Host.SystemWeb
3.Microsoft.AspNet.Identity.Owin
4.Microsoft.Owin.Cors
5.Microsoft.Owin.Security
6.Microsoft.Owin.Security.OAuth
2.在根目录添加 SimpleAuthorizationServerProvider.cs
using Microsoft.Owin.Security.OAuth; using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using System.Web; namespace WebApplication4 { /// <summary> /// Token验证 /// </summary> public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider { public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) { await Task.Factory.StartNew(() => context.Validated()); } public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { await Task.Factory.StartNew(() => context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" })); // 对用户名、密码进行数据校验 string UserName = context.UserName; string Password = context.Password; if (UserName!= "zhuzhi" || Password != "123456") { context.SetError("invalid_grant", "用户名和密码错误!"); return; } var identity = new ClaimsIdentity(context.Options.AuthenticationType); identity.AddClaim(new Claim("sub", context.UserName)); identity.AddClaim(new Claim("role", "user")); context.Validated(identity); } } }
3.在根目录添加 SimpleRefreshTokenProvider.cs
using Microsoft.Owin.Security.Infrastructure; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Web; namespace WebApplication4 { public class SimpleRefreshTokenProvider : AuthenticationTokenProvider { private static ConcurrentDictionary<string, string> _refreshTokens = new ConcurrentDictionary<string, string>(); /// <summary> /// 生成 refresh_token /// </summary> public override void Create(AuthenticationTokenCreateContext context) { context.Ticket.Properties.IssuedUtc = DateTime.UtcNow; context.Ticket.Properties.ExpiresUtc = DateTime.UtcNow.AddDays(60); context.SetToken(Guid.NewGuid().ToString("n")); _refreshTokens[context.Token] = context.SerializeTicket(); } /// <summary> /// 由 refresh_token 解析成 access_token /// </summary> public override void Receive(AuthenticationTokenReceiveContext context) { string value; if (_refreshTokens.TryRemove(context.Token, out value)) { context.DeserializeTicket(value); } } } }
4.在根目录添加 Startup.cs
using Microsoft.Owin; using Microsoft.Owin.Security.OAuth; using Owin; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; [assembly: OwinStartup(typeof(WebApplication4.Startup))] namespace WebApplication4 { public class Startup { public void Configuration(IAppBuilder app) { HttpConfiguration config = new HttpConfiguration(); //ConfigureOAuth(app); ConfigAuth(app); WebApiConfig.Register(config); app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); app.UseWebApi(config); } /// <summary> /// 普通方法 /// </summary> /// <param name="app"></param> public void ConfigureOAuth(IAppBuilder app) { OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions() { AllowInsecureHttp = true, TokenEndpointPath = new PathString("/token"), AccessTokenExpireTimeSpan = TimeSpan.FromDays(1), Provider = new SimpleAuthorizationServerProvider() }; app.UseOAuthAuthorizationServer(OAuthServerOptions); app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()); } /// <summary> /// access_token 过期 /// </summary> /// <param name="app"></param> public void ConfigAuth(IAppBuilder app) { OAuthAuthorizationServerOptions option = new OAuthAuthorizationServerOptions() { AllowInsecureHttp = true, TokenEndpointPath = new PathString("/token"), //获取 access_token 授权服务请求地址 AccessTokenExpireTimeSpan = TimeSpan.FromDays(1), //access_token 过期时间 Provider = new SimpleAuthorizationServerProvider(), //access_token 相关授权服务 RefreshTokenProvider = new SimpleRefreshTokenProvider() //refresh_token 授权服务 }; app.UseOAuthAuthorizationServer(option); app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()); } } }
5.普通调用不加认证
6.加认证给方法的头部加一个[Authorize]
7.通过postman获取token(调用的时候webapi的时候上面的网站不能关闭)