1. 环境:vs2013,Framework 4.5
2. 文件结构
3. 需引入的dll
Microsoft.AspNet.Identity.Owin.dll |
2.2.1.40403|2.2.1.40403 |
|
Microsoft.Owin.Cors.dll |
2.020911.395|2.0.0 |
|
Microsoft.Owin.dll |
3.0.40213.64|3.0.1 |
编译或调试时添加的 |
Microsoft.Owin.Host.SystemWeb.dll |
3.0.40213.64|3.0.1 |
|
Microsoft.Owin.Security.Cookies.dll |
3.0.40213.64|3.0.1 |
|
Microsoft.Owin.Security.dll |
3.0.10213.64|3.0.1 |
编译或调试时添加的 |
Microsoft.Owin.Security.OAuth.dll |
3.0.40213.64|3.0.1 |
|
Newtonsoft.Json.dll |
6.0.4.17603|6.04.17603 |
默认添加的版本大致为4.5,运行后会报错 |
Owin.dll |
1.0.0.0|1.0 |
|
4. 代码
1) 添加Owin Startup类
using System; using System.Threading.Tasks; using System.Web.Http; using Microsoft.Owin; using Microsoft.Owin.Cors; using Microsoft.Owin.Security.OAuth; using Owin; using WebApi4.OAuth; [assembly: OwinStartup(typeof(WebApi4.Startup))] namespace WebApi4 { public class Startup { public void Configuration(IAppBuilder app) { // 有关如何配置应用程序的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkID=316888 ConfigAuth(app); HttpConfiguration config = new HttpConfiguration(); 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"), //获取 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()); } } }
2) 添加验证类SimpleAuthorizationServerProvider
using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using System.Web; using Microsoft.Owin.Security.OAuth; namespace WebApi4.OAuth { public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider { public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) { context.Validated(); return Task.FromResult<object>(null); } public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); //验证逻辑 //AccountService accService = new AccountService(); //string md5Pwd = LogHelper.MD5CryptoPasswd(context.Password); //IList<object[]> ul = accService.Login(context.UserName, md5Pwd); //if (ul.Count() == 0) //{ // 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); } } }
3) 添加SimpleRefreshTokenProvider类
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Web; using Microsoft.Owin.Security.Infrastructure; namespace WebApi4.OAuth { 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) 添加业务代码
a) 控制器
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; using WebApi4.Models; namespace WebApi4.Controllers { [Authorize] public class EmployeeController : ApiController { //查询所有员工 [HttpGet] public IList<UC_Employee> GetAllEmps() { return new List<UC_Employee>(); } } }
b) 添加模型类
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace WebApi4.Models { public class UC_Employee { } }
5) 修改Web.config配置文件(
5. 调试
1) 无验证情况访问
2) 授权
3) 验证成功
6. 参考资料
1) https://www.cnblogs.com/lnice/p/6857203.html