using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Owin.Security.OAuth; using Step.Database.Controllers; using Step.Model; using System.Security.Claims; using static Step.Utils.Constants; namespace Step.Provider { public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider { public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) { // Validate client context.Validated(); } public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { using (UsersController usersController = new UsersController()) { // Check if credentials are correct UserModel user = usersController.Find(context.UserName, context.Password); // If not if (user == null) { // Return 401 bad request context.SetError("invalid_grant", "The user name or password is incorrect."); return; } // Create a new Identity and insert custom claims var identity = new ClaimsIdentity(context.Options.AuthenticationType); identity.AddClaim(new Claim(USERNAME_KEY, user.Username)); identity.AddClaim(new Claim(ROLE_LEVEL_KEY, user.Role.Level.ToString())); // Create Token with identity data context.Validated(identity); await base.GrantResourceOwnerCredentials(context); return; } } } }