public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { try { var loginResult = await AccountsMgr.LogInAsync(context.UserName, context.Password); var identity = new ClaimsIdentity(context.Options.AuthenticationType, "accountId", "role"); identity.AddClaim(new Claim("token", loginResult.Item1.ToString())); identity.AddClaims((await AccountsMgr.GetRolesAsync(loginResult.Item2)).Select(r => new Claim("role", r))); identity.AddClaims((await AccountsMgr.GetPermissionsAsync(loginResult.Item2)).Select(p => new Claim("permission", p))); context.Validated(identity); } catch (Exception ex) { context.SetError(ex.GetType().ToString()); } }
public async System.Threading.Tasks.Task AuthenticateAsync(HttpAuthenticationContext context, System.Threading.CancellationToken cancellationToken) { // Even if a token is valid from the OAuth perspective, I want to verify that's still active var identity = (ClaimsIdentity)context.Principal.Identity; var claim = identity.Claims.Where(c => c.Type == "token").FirstOrDefault(); if (claim != null) { var realAccountId = await AccountsMgr.GetAccountIdAsync(claim.Value); if (realAccountId.HasValue) { var accountId = realAccountId.Value; identity.AddClaim(new Claim("realAccountId", accountId.ToString())); if (context.Request.Headers.Any(h => h.Key == "Acting-As")) { var actingAs = context.Request.Headers.GetValues("Acting-As").FirstOrDefault(); if (actingAs != null && identity.HasClaim("permission", "act-as")) { if (int.TryParse(actingAs, out accountId)) { //refresh the roles and permissions with the user's foreach (var currentClaim in identity.Claims.Where(c => c.Type == "role" || c.Type == "permission").ToList()) { identity.RemoveClaim(currentClaim); } identity.AddClaims((await AccountsMgr.GetRolesAsync(accountId)).Select(r => new Claim("role", r))); identity.AddClaims((await AccountsMgr.GetPermissionsAsync(accountId)).Select(p => new Claim("permission", p))); } } } identity.AddClaim(new Claim("accountId", accountId.ToString())); } else { context.ErrorResult = new UnauthorizedResult(new AuthenticationHeaderValue[0], context.Request); } } }