/// <summary> /// Responsible to validate the username and password sent to the authorization server’s token endpoint /// </summary> /// <param name="context"></param> /// <returns></returns> public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { var allowedOrigin = context.OwinContext.Get <string>("as:clientAllowedOrigin"); if (allowedOrigin == null) { allowedOrigin = "*"; } context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin }); var userManager = context.OwinContext.GetUserManager <ApplicationUserManager>(); var roleManager = context.OwinContext.GetUserManager <ApplicationRoleManager>(); ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password); if (user == null) { context.SetError("invalid_grant", "The user name or password is incorrect."); return; } if (!user.EmailConfirmed) { context.SetError("invalid_grant", "User did not confirm email."); return; } //generate the identity to pass to the tikcet ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, context.Options.AuthenticationType); oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, context.UserName)); oAuthIdentity.AddClaim(new Claim("sub", context.UserName)); //Add all roles of current user List <Claim> rolesClaims = new List <Claim>(); foreach (var identityUserRole in user.Roles) { var identityRole = await roleManager.FindByIdAsync(identityUserRole.RoleId); rolesClaims.Add(new Claim(ClaimTypes.Role, identityRole.Name)); } oAuthIdentity.AddClaims(rolesClaims); //add specific claims to the identity of the user withc suite some cases //like add FTE (Full time employee) when the JoinDate of the user is greater then 90 days oAuthIdentity.AddClaims(ExtendedClaimsProvider.GetClaims(user)); //add some roles based on some claims oAuthIdentity.AddClaims(RolesFromClaims.CreateRolesBasedOnClaims(oAuthIdentity)); var props = new AuthenticationProperties(new Dictionary <string, string> { { "as:client_id", (context.ClientId == null) ? string.Empty : context.ClientId }, { "userName", context.UserName } }); var ticket = new AuthenticationTicket(oAuthIdentity, props); context.Validated(ticket); }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { var allowedOrigin = "*"; context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin }); var userManager = context.OwinContext.GetUserManager <ApplicationUserManager>(); ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password); if (user == null) { context.SetError("invalid_grant", "The user name or password is incorrect."); return; } if (!user.EmailConfirmed) { context.SetError("invalid_grant", "User did not confirm email."); return; } ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager); oAuthIdentity.AddClaims(ExtendedClaimsProvider.GetClaims(user)); oAuthIdentity.AddClaims(RolesFromClaims.CreateRolesBasedOnClaims(oAuthIdentity)); var ticket = new AuthenticationTicket(oAuthIdentity, null); context.Validated(ticket); }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); var usuario = _usuarioApp.Autenticar(context.UserName, context.Password); if (usuario == null) { context.SetError("invalid_grant", "Usuário ou senha inválidos"); return; } if (!usuario.EstaAtivo) { context.SetError("invalid_grant", "Usuário está inativo."); return; } var identity = new ClaimsIdentity("JWT"); identity.AddClaims(ExtendedClaimsProvider.GetClaims(usuario)); identity.AddClaims(RolesFromClaims.CreateRolesBasedOnClaims(identity)); AuthenticationProperties properties = CreateProperties(usuario.IdPessoa.ToString(), usuario.Funcionario.Imagem, usuario.Funcionario.Estabelecimento.Logo); AuthenticationTicket ticket = new AuthenticationTicket(identity, properties); context.Validated(ticket); }
public async Task <ClaimsIdentity> GetClaimIdentityAsync(ApplicationUser appUser, ApplicationUserManager appUserManager) { ClaimsIdentity oAuthIdentity = await appUser.GenerateUserIdentityAsync(appUserManager, "JWT"); oAuthIdentity.AddClaims(ExtendedClaimsProvider.GetClaims(appUser)); oAuthIdentity.AddClaims(RolesFromClaims.CreateRolesBasedOnClaims(oAuthIdentity)); return(oAuthIdentity); }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { var allowedOrigin = context.OwinContext.Get <string>("as:clientAllowedOrigin"); if (allowedOrigin == null) { allowedOrigin = "*"; } context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin }); var userManager = context.OwinContext.GetUserManager <ApplicationUserManager>(); UserMaster user = await userManager.FindAsync(context.UserName, context.Password); if (user == null) { context.SetError("invalid_grant", "The user name or password is incorrect."); return; } //if (!user.EmailConfirmed) //{ // context.SetError("invalid_grant", "User did not confirm email."); // return; //} ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, "JWT"); oAuthIdentity.AddClaims(ExtendedClaimsProvider.GetClaims(user)); oAuthIdentity.AddClaims(RolesFromClaims.CreateRolesBasedOnClaims(oAuthIdentity)); //var ticket = new AuthenticationTicket(oAuthIdentity, null); var props = new AuthenticationProperties(new Dictionary <string, string> { { "as:client_id", (context.ClientId == null) ? string.Empty : context.ClientId }, { "UserName", context.UserName }, { "level", user.Level.ToString() }, { "firstname", user.FirstName }, { "lastname", user.LastName } }); var ticket = new AuthenticationTicket(oAuthIdentity, props); context.Validated(ticket); }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { var allowedOrigin = "*"; context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin }); var userManager = context.OwinContext.GetUserManager <ApplicationUserManager>(); ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password); var systemUser = await userManager.FindByNameAsync("System"); if (user == null) { context.SetError("invalid_grant", "The user name or password is incorrect."); logger.Error($"Login failed The user name or password is incorrect: {context.UserName}, Id: {user.Id}", systemUser.Id); return; } if ((!user.IsActive.HasValue) || (!user.IsActive.Value)) { context.SetError("invalid_grant", "The user is inactive"); logger.Error($"Login failed The user is inactive: {context.UserName}, Id: {user.Id}", systemUser.Id); return; } //if (!user.EmailConfirmed) //{ // context.SetError("invalid_grant", "User did not confirm email."); // logger.Error($"Login failed User did not confirm email: {context.UserName}, Id: {user.Id}", systemUser.Id); // return; //} ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, "JWT"); oAuthIdentity.AddClaims(ExtendedClaimsProvider.GetClaims(user)); oAuthIdentity.AddClaims(RolesFromClaims.CreateRolesBasedOnClaims(oAuthIdentity)); var ticket = new AuthenticationTicket(oAuthIdentity, null); context.Validated(ticket); if (ticket == null) { logger.Error($"Login failed The user name or password is incorrect: {context.UserName}", systemUser.Id); } else { List <Claim> claimsList = oAuthIdentity.Claims.Where(c => c.Type == ClaimTypes.Role).ToList(); string rolesList = string.Join(",", claimsList.Select(r => r.Value).ToList()); logger.Info($"Login Successful for {context.UserName} Roles: {rolesList}", systemUser.Id); } }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { var allowedOrigin = context.OwinContext.Get <string>("as:clientAllowedOrigin"); if (allowedOrigin == null) { allowedOrigin = "*"; } context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin }); var userManager = context.OwinContext.GetUserManager <ApplicationUserManager>(); ApplicationUser user = await userManager.FindByEmailAsync(context.UserName); if (user == null) { context.SetError("invalid_grant", "The email or passcode is incorrect."); return; } if (user.PasscodeHash != context.Password) { context.SetError("invalid_grant", "The passcode is incorrect."); return; } if (user.LockoutEndDateUtc < DateTime.UtcNow) { context.SetError("invalid_grant", "The passcode has expired."); return; } if (!user.EmailConfirmed) { context.SetError("invalid_grant", "User did not confirm email."); return; } ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, "JWT"); oAuthIdentity.AddClaims(ExtendedClaimsProvider.GetClaims(user)); oAuthIdentity.AddClaims(RolesFromClaims.CreateRolesBasedOnClaims(oAuthIdentity)); var props = new AuthenticationProperties(new Dictionary <string, string> { { "as:client_id", (context.ClientId == null) ? string.Empty : context.ClientId }, { "userName", context.UserName } }); var ticket = new AuthenticationTicket(oAuthIdentity, props); context.Validated(ticket); }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { try { var allowedOrigin = "*"; context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin }); var userManager = context.OwinContext.GetUserManager <ApplicationUserManager>(); ApplicationUser user = null;; try { user = await userManager.FindAsync(context.UserName, context.Password); } catch (Exception ex) { Utilities.LogException(ex); } if (user == null) { context.SetError("invalid_grant", "The user name or password is incorrect."); return; } if (!user.EmailConfirmed) { context.SetError("invalid_grant", "User did not confirm email."); return; } _userType = user.UserType; //ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, "JWT"); ClaimsIdentity oAuthIdentity = userManager.CreateIdentityAsync(user, "JWT").Result; oAuthIdentity.AddClaims(ExtendedClaimsProvider.GetClaims(user)); oAuthIdentity.AddClaims(RolesFromClaims.CreateRolesBasedOnClaims(oAuthIdentity)); List <Claim> roles = oAuthIdentity.Claims.Where(c => c.Type == ClaimTypes.Role).ToList(); AuthenticationProperties properties = CreateProperties(user.UserName, Newtonsoft.Json.JsonConvert.SerializeObject(roles.Select(x => x.Value))); var ticket = new AuthenticationTicket(oAuthIdentity, properties); context.Validated(ticket); } catch (Exception ex) { Utilities.LogException(ex); } }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { // // Setup CORS // var allowedOrigin = "*"; context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new [] { allowedOrigin }); // // Check whether user exists and if the user has confirmed email. If so grant the access token // var userManager = context.OwinContext.GetUserManager <ApplicationUserManager>(); var user = await userManager.FindAsync(context.UserName, context.Password); if (user == null) { context.SetError("invalid_grant", "The username or password is incorrect"); return; } if (user.EmailConfirmed == false) { context.SetError("The user has not verified the email yet"); return; } var oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, "JWT"); // // Get claims for the user // oAuthIdentity.AddClaims(ExtendedClaimsProvider.GetClaims(user)); // // Get role based claims // oAuthIdentity.AddClaims(RolesFromClaims.CreateRolesBasedOnClaims(oAuthIdentity)); var ticket = new AuthenticationTicket(oAuthIdentity, null); context.Validated(ticket); }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { int state = 0; // {0. Basic User; 1. Portal Admin; 2. WSSAdmin } var client = _repo.FindClient(context.ClientId); var customer = ""; var cusId = 0; var allowedOrigin = context.OwinContext.Get <string>("as:clientAllowedOrigin"); if (allowedOrigin == null) { allowedOrigin = "*"; } context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin }); var userManager = context.OwinContext.GetUserManager <ApplicationUserManager>(); var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(new ApplicationDbContext())); ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password); var rolesForUser = await userManager.GetRolesAsync(user.Id); var serialRoles = Newtonsoft.Json.JsonConvert.SerializeObject(rolesForUser); // get the client company var clientUser = _repo.FindClientUserByUserId(user.Id); if (clientUser != null) { var sidClient = await _repo2.FindSidClientId(clientUser.SidClientId); customer = sidClient.Name; cusId = sidClient.Id; } if (user == null) { context.SetError("invalid_grant", "The user name or password is incorrect."); return; } if (!user.EmailConfirmed) { context.SetError("invalid_grant", "User did not confirm email."); return; } var props = new AuthenticationProperties(new Dictionary <string, string> { { "as:client_id", (context.ClientId == null) ? string.Empty : context.ClientId }, { "userName", context.UserName }, { "fullName", user.FirstName + " " + user.LastName }, { "access", (client.IsPublic == false) ? "Public" : "Private" }, { "roles", serialRoles }, { "customer", customer }, { "customerId", cusId.ToString() } }); ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, "JWT"); oAuthIdentity.AddClaims(ExtendedClaimsProvider.GetClaims(user)); oAuthIdentity.AddClaims(RolesFromClaims.CreateRolesBasedOnClaims(oAuthIdentity)); var ticket = new AuthenticationTicket(oAuthIdentity, props); context.Validated(ticket); }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { var allowedOrigin = "*"; try { //context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin }); var userManager = context.OwinContext.GetUserManager <ApplicationUserManager>(); ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password); if (user == null) { context.SetError("invalid_grant", "The user name or password is incorrect."); return; } if (!user.EmailConfirmed) { context.SetError("invalid_grant", "User did not confirm email."); return; } iAuthContext con = new AuthContext(); if (string.IsNullOrEmpty(user.ApkName)) { People p = con.getPersonIdfromEmail(user.Email); int UserId = p.PeopleID; if (!p.Active) { context.SetError("invalid_grant", "Please check your registered email address to validate email address."); return; } if (UserId == 0) { context.SetError("invalid_grant", "The user name or password is incorrect."); return; } ClaimsIdentity identity = await user.GenerateUserIdentityAsync(userManager, "JWT"); identity.AddClaims(ExtendedClaimsProvider.GetClaims(user)); identity.AddClaims(RolesFromClaims.CreateRolesBasedOnClaims(identity)); //UserAccessPermission uap = con.getRoleDetail(p.Permissions); // Get Role Access Detail var rolesIds = user.Roles.Select(x => x.RoleId).ToList(); //var identity = new ClaimsIdentity(context.Options.AuthenticationType); //identity.AddClaims(ExtendedClaimsProvider.GetClaims(user)); identity.AddClaims(RolesFromClaims.CreateRolesBasedOnClaims(identity)); identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName)); identity.AddClaim(new Claim(ClaimTypes.Role, p.Permissions)); identity.AddClaim(new Claim("firsttime", "true")); identity.AddClaim(new Claim("compid", p.CompanyId.ToString())); identity.AddClaim(new Claim("email", user.Email)); identity.AddClaim(new Claim("Email", user.Email.ToString())); identity.AddClaim(new Claim("Level", user.Level.ToString())); identity.AddClaim(new Claim("userid", UserId.ToString())); identity.AddClaim(new Claim("DisplayName", p.DisplayName)); identity.AddClaim(new Claim("username", (p.PeopleFirstName + " " + p.PeopleLastName).ToString())); identity.AddClaim(new Claim("userid", UserId.ToString())); identity.AddClaim(new Claim("Roleids", string.Join(",", rolesIds))); //identity.AddClaim(new Claim("pagePermissions", JsonConvert.SerializeObject(pagePermissions))); User_Id = UserId; ac_Type = p.Permissions; var props = new AuthenticationProperties(new Dictionary <string, string> { }); if (p.Permissions == "HQ Master login") { props = new AuthenticationProperties(new Dictionary <string, string> { { "as:client_id", (context.ClientId == null) ? string.Empty : context.ClientId }, { "userName", context.UserName }, { "compid", p.CompanyId.ToString() }, { "Level", user.Level.ToString() }, { "role", p.Permissions }, { "email", user.Email }, { "userid", UserId.ToString() }, { "LScode", p.LScode }, // { "pagePermissions", JsonConvert.SerializeObject(pagePermissions)} }); } else { props = new AuthenticationProperties(new Dictionary <string, string> { { "as:client_id", (context.ClientId == null) ? string.Empty : context.ClientId }, { "userName", context.UserName }, { "compid", user.PhoneNumber }, { "role", p.Permissions }, { "Level", user.Level.ToString() }, { "email", user.Email }, { "userid", UserId.ToString() }, //{ "pagePermissions", JsonConvert.SerializeObject(pagePermissions)} }); } var ticket = new AuthenticationTicket(identity, props); context.Validated(ticket); } else // Authorize APK { ClaimsIdentity identity = await user.GenerateUserIdentityAsync(userManager, "JWT"); identity.AddClaims(ExtendedClaimsProvider.GetClaims(user)); identity.AddClaims(RolesFromClaims.CreateRolesBasedOnClaims(identity)); identity.AddClaim(new Claim("AppName", user.ApkName)); var props = new AuthenticationProperties(new Dictionary <string, string> { }); props = new AuthenticationProperties(new Dictionary <string, string> { { "as:client_id", (context.ClientId == null) ? string.Empty : context.ClientId }, { "userName", context.UserName }, { "AppName", user.ApkName } }); var ticket = new AuthenticationTicket(identity, props); context.Validated(ticket); } } catch (Exception ex) { logger.Error("Unable to validate user {0}", context.UserName); logger.Error(ex.InnerException != null ? ex.InnerException.ToString() : ex.ToString()); } }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { //var allowedOrigin = context.OwinContext.Get<string>("as:clientAllowedOrigin"); //if (allowedOrigin == null) allowedOrigin = "*"; //context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin }); //context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); //using (AuthRepository _repo = new AuthRepository()) //{ // IdentityUser user = await _repo.FindUser(context.UserName, context.Password); // ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, "JWT"); // oAuthIdentity.AddClaims(ExtendedClaimsProvider.GetClaims(user)); // var ticket = new AuthenticationTicket(oAuthIdentity, null); // context.Validated(ticket); // if (user == null) // { // context.SetError("invalid_grant", "The user name or password is incorrect."); // return; // } //} var allowedOrigin = "*"; context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin }); var userManager = context.OwinContext.GetUserManager <ApplicationUserManager>(); ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password); if (user == null) { context.SetError("invalid_grant", "The user name or password is incorrect."); return; } if (!user.EmailConfirmed) { context.SetError("invalid_grant", "User did not confirm email."); return; } ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, "JWT"); oAuthIdentity.AddClaims(ExtendedClaimsProvider.GetClaims(user)); oAuthIdentity.AddClaims(RolesFromClaims.CreateRolesBasedOnClaims(oAuthIdentity)); var props = new AuthenticationProperties(new Dictionary <string, string> { { "as:client_id", (context.ClientId == null) ? string.Empty : context.ClientId }, { "userName", context.UserName } }); var ticket = new AuthenticationTicket(oAuthIdentity, props); context.Validated(ticket); //var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>(); //ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password); //if (user == null) //{ // context.SetError("invalid_grant", "The user name or password is incorrect."); // return; //} //if (!user.EmailConfirmed) //{ // context.SetError("invalid_grant", "User did not confirm email."); // return; //} //ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, "JWT"); //oAuthIdentity.AddClaims(ExtendedClaimsProvider.GetClaims(user)); //oAuthIdentity.AddClaims(RolesFromClaims.CreateRolesBasedOnClaims(oAuthIdentity)); //var oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType); //oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, context.UserName)); //oAuthIdentity.AddClaim(new Claim("sub", context.UserName)); //oAuthIdentity.AddClaim(new Claim(ClaimTypes.Role, "SuperAdmin")); //var props = new AuthenticationProperties(new Dictionary<string, string> // { // { // "as:client_id", (context.ClientId == null) ? string.Empty : context.ClientId // }, // { // "userName", context.UserName // } // }); //var ticket = new AuthenticationTicket(oAuthIdentity, props); //var ticket = new AuthenticationTicket(oAuthIdentity, null); //context.Validated(ticket); //context.Validated(oAuthIdentity); }