/// <summary> /// 授予资源所有者凭据 /// 当客户端请求为 grant_type=password 时触发 /// </summary> /// <param name="arg"></param> /// <returns></returns> private System.Threading.Tasks.Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext arg) { //这里需要验证用户登录信息以及客户端信息 DSCMA user = null; YFPLUS_Client client = null; using (DSCSYSEntities context = new DSCSYSEntities()) { user = new UserService().GetUser(arg.UserName, arg.Password); client = context.YFPLUS_Client.AsNoTracking().FirstOrDefault(s => s.ClientIdentify == arg.ClientId); } if (user != null) { List <Claim> claims = new List <Claim>(); claims.Add(new Claim("ClientID", client.ID + "")); claims.AddRange(arg.Scope.Select(x => new Claim("urn:oauth:scope", x))); claims.Add(new Claim("UserID", user.MA001 + "")); var identity = new ClaimsIdentity( new GenericIdentity(user.MA001, OAuthDefaults.AuthenticationType), claims); arg.Validated(identity); } return(Task.FromResult(0)); }
/// <summary> /// 专给OAUTH用的,不想引用注入框架了 /// </summary> /// <param name="username"></param> /// <param name="password"></param> /// <returns></returns> public DSCMA GetUser(string username, string password) { using (dbContext = new DSCSYSEntities()) { string pwd = Encode(EnUser(username.ToCharArray()), password.ToCharArray()); DSCMA dscma = dbContext.DSCMA.Where(o => o.MA001.Equals(username) && o.MA003.Equals(pwd)) .FirstOrDefault(); return(dscma); } }
// GET: OAuth public ActionResult Authorize() { if (Response.StatusCode != 200) { return(View("AuthorizeError")); } var authentication = HttpContext.GetOwinContext().Authentication; var ticket = authentication.AuthenticateAsync("Application").Result; var identity = ticket != null ? ticket.Identity : null; if (identity == null) { authentication.Challenge("Application"); return(new HttpUnauthorizedResult()); } var scopes = (Request.QueryString.Get("scope") ?? "").Split(' '); if (Request.HttpMethod == "POST") { if (!string.IsNullOrEmpty(Request.Form.Get("submit.Grant"))) { identity = new ClaimsIdentity(identity.Claims, "Bearer", identity.NameClaimType, identity.RoleClaimType); foreach (var scope in scopes) { identity.AddClaim(new Claim("urn:oauth:scope", scope)); } string client_id = Request.QueryString["client_id"]; using (DSCSYSEntities context = new DSCSYSEntities()) { var client = context.YFPLUS_Client.AsNoTracking().AsQueryable().FirstOrDefault(s => s.ClientIdentify == client_id); client_id = client.ID + ""; } identity.AddClaim(new Claim("ClientID", client_id)); authentication.SignIn(identity); } if (!string.IsNullOrEmpty(Request.Form.Get("submit.Login"))) { authentication.SignOut("Application"); authentication.Challenge("Application"); return(new HttpUnauthorizedResult()); } } return(View()); }
/// <summary> /// 收到刷新令牌 /// </summary> /// <param name="obj"></param> private Task ReceiveRefreshTokenAsync(AuthenticationTokenReceiveContext arg) { YFPLUS_RefreshToken model = null; Guid ID = Guid.Parse(arg.Token); using (DSCSYSEntities context = new DSCSYSEntities()) { model = context.YFPLUS_RefreshToken.Find(ID); if (model == null) { return(Task.FromResult(0)); } context.YFPLUS_RefreshToken.Remove(model); context.SaveChanges(); } //解码保护资源 arg.DeserializeTicket(model.ProtectedTicket); //因为原 Ticket 已经失效,所以才要刷新,这里需要新生成一个 Ticket 。 DateTime now = DateTime.UtcNow; Dictionary <string, string> param = new Dictionary <string, string>(); foreach (var kv in arg.Ticket.Properties.Dictionary) { if (kv.Key != ".issued" && kv.Key != ".expires") { param.Add(kv.Key, kv.Value); } } param.Add(".issued", now.ToString("R")); param.Add(".expires", (now + AccessTokenExpireTimeSpan).ToString("R")); AuthenticationTicket ticket = new AuthenticationTicket(arg.Ticket.Identity, new AuthenticationProperties(param)); arg.SetTicket(ticket); return(Task.FromResult(0)); }
/// <summary> /// 当客户端请求类型为 "grant_type=client_credentials" 时触发 /// </summary> /// <param name="arg"></param> /// <returns></returns> private System.Threading.Tasks.Task GrantClientCredetails(OAuthGrantClientCredentialsContext arg) { YFPLUS_Client client = null; using (DSCSYSEntities context = new DSCSYSEntities()) { client = context.YFPLUS_Client.AsNoTracking().AsQueryable().SingleOrDefault(s => s.ClientIdentify == arg.ClientId); } var claims = new List <Claim>(); claims.Add(new Claim("ClientID", client.ID + "")); claims.AddRange(arg.Scope.Select(x => new Claim("urn:oauth:scope", x))); var identity = new ClaimsIdentity(new GenericIdentity(client.Name, OAuthDefaults.AuthenticationType), claims); arg.Validated(identity); return(Task.FromResult(0)); }
/// <summary> /// 将核心信息保存到数据库中,并返回 RefreshTokenID /// </summary> /// <param name="client_id"></param> /// <param name="user_id"></param> /// <param name="ticket"></param> /// <returns></returns> private static string GetRefreshToken(int client_id, int?user_id, string ticket) { var now = DateTime.UtcNow; YFPLUS_RefreshToken refreshTokenModel = new YFPLUS_RefreshToken() { ClientID = client_id, UserID = user_id, IssuedUtc = now, ExpiresUtc = now.AddHours(3), ProtectedTicket = ticket }; using (DSCSYSEntities context = new DSCSYSEntities()) { context.YFPLUS_RefreshToken.Add(refreshTokenModel); context.SaveChanges(); } string refreshToken = refreshTokenModel.ID.ToString("N"); return(refreshToken); }
/// <summary> /// 验证客户端回调URL /// </summary> /// <param name="arg"></param> /// <returns></returns> private System.Threading.Tasks.Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext arg) { try { using (DSCSYSEntities context = new DSCSYSEntities()) { var client = context.YFPLUS_Client.AsNoTracking().AsQueryable().FirstOrDefault(s => s.ClientIdentify == arg.ClientId); if (client == null) { arg.SetError("客户端失效", "客户端失效"); } else { arg.Validated(client.RedirectUrl); } } } catch (Exception ex) { arg.SetError("unknow error", ex.Message); } return(Task.FromResult(0)); }
/// <summary> /// 验证客户端认证信息 /// </summary> /// <param name="arg"></param> /// <returns></returns> private System.Threading.Tasks.Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext arg) { try { string clientId; string clientSecret; if (arg.TryGetBasicCredentials(out clientId, out clientSecret)) { using (DSCSYSEntities context = new DSCSYSEntities()) { if (context.YFPLUS_Client.AsNoTracking().AsQueryable().Any(s => s.ClientIdentify == clientId && s.ClientSecret == clientSecret)) { arg.Validated(); } } } } catch (Exception ex) { arg.SetError("unknow error", ex.Message); } return(Task.FromResult(0)); }