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 mywebapiOauth.OAuth { public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider { List<User> users = new List<User>() { new User(){ Name="admin",Password="admin",Role="Administrator" }, new User(){ Name="zhangsan",Password="zhangsan",Role="Admin" }, new User(){ Name="lisi",Password="admin",Role="user" } }; 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[] { "*" }); User user = users.Where(p => p.Name == context.UserName && p.Password == context.Password).FirstOrDefault (); if (user == null) { 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.Role )); identity.AddClaim(new Claim(ClaimTypes.Role, user.Role)); context.Validated(identity); } } 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); } } } } |