public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); try { var user = _service.Authenticate(context.UserName, context.Password); if (user == null) { context.SetError("invalid_grant", "E-mail ou senha inválidos."); return; } var identity = new ClaimsIdentity(context.Options.AuthenticationType); identity.AddClaim(new Claim(ClaimTypes.Name, user.Email)); identity.AddClaim(new Claim(ClaimTypes.GivenName, user.Name)); GenericPrincipal principal = new GenericPrincipal(identity, null); Thread.CurrentPrincipal = principal; context.Validated(identity); } catch (Exception) { context.SetError("invalid_grant", "E-mail ou senha inválidos."); } }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>(); User user = await userManager.FindAsync(context.UserName, context.Password); if (user == null) { context.SetError("invalid_grant", "The user name or password is incorrect."); return; } if (await userManager.IsLockedOutAsync(user.Id)) { context.SetError("lock_out", "The account is locked."); return; } ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, context.Options.AuthenticationType); ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager, DefaultAuthenticationTypes.ApplicationCookie); AuthenticationProperties properties = CreateProperties(user); AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties); context.Validated(ticket); context.Request.Context.Authentication.SignIn(cookiesIdentity); }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); using (var db = new EmployeeContext()) { var user = db.Users.FirstOrDefault(x => x.Email.Equals(context.UserName)); if (user == null) { context.SetError("invalid_grant", "The user name or password is incorrect."); return; } if (!PasswordHashHelper.ValidatePassword(context.Password, user.PasswordHash)) { context.SetError("invalid_grant", "The user name or password is incorrect."); return; } var identity = new ClaimsIdentity(context.Options.AuthenticationType); var roles = db.UserRoles.Where(x => x.UserId.Equals(user.Id)).Select(x => x.RoleName).ToList(); identity.AddClaim(new Claim(ClaimTypes.Email, context.UserName)); identity.AddClaim(roles.Contains(Role.Admin) ? new Claim(ClaimTypes.Role, Role.Admin) : new Claim(ClaimTypes.Role, Role.User)); context.Validated(identity); } }
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, "JWT"); var ticket = new AuthenticationTicket(oAuthIdentity, null); context.Validated(ticket); }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { // http://www.codeproject.com/Articles/742532/Using-Web-API-Individual-User-Account-plus-CORS-En // This article helped me track down the issue that even though CORS is enabled application-wide, // it still doesn't affect this OWIN component, so we have to enable it here also. string origins = AppSettingsConfig.CorsPolicyOrigins; context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new string[] { origins }); 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; } // I needed to add this in order to check if the email was confirmed when a user log on. if (!user.EmailConfirmed) { context.SetError("email_not_confirmed", "User did not confirm email."); return; } ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, OAuthDefaults.AuthenticationType); ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager, CookieAuthenticationDefaults.AuthenticationType); AuthenticationProperties properties = CreateProperties(user.UserName); AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties); context.Validated(ticket); context.Request.Context.Authentication.SignIn(cookiesIdentity); }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>(); try { ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password); if (user == null) { context.SetError("invalid_grant", "The user name or password is incorrect."); return; } ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, OAuthDefaults.AuthenticationType); ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager, CookieAuthenticationDefaults.AuthenticationType); AuthenticationProperties properties = CreateProperties(user.UserName); AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties); context.Validated(ticket); context.Request.Context.Authentication.SignIn(cookiesIdentity); } catch (InvalidOperationException e) { context.SetError("invalid_grant", "The user name or password is incorrect. This should not happen"); return; } }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { 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.IsApproved) { context.SetError("user_not_approved", "User is not approved. Please contact administrator."); return; } ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, OAuthDefaults.AuthenticationType); ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager, CookieAuthenticationDefaults.AuthenticationType); AuthenticationProperties properties = CreateProperties(user.UserName); AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties); context.Validated(ticket); context.Request.Context.Authentication.SignIn(cookiesIdentity); }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { try { context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); Usuario user = _usuarioAppService.Get(el => el.Login == context.UserName && el.Senha == context.Password); if (user == null) { context.SetError("invalid_grant", "Usuário ou Senha inválidos."); return; } var identity = new ClaimsIdentity(context.Options.AuthenticationType); identity.AddClaim(new Claim(ClaimTypes.Name, user.NomeUsuario)); var roles = new List<string>(); roles.Add("User"); foreach (var item in roles) identity.AddClaim(new Claim(ClaimTypes.Role, item)); GenericPrincipal principal = new GenericPrincipal(identity, roles.ToArray()); Thread.CurrentPrincipal = principal; context.Validated(identity); } catch (Exception ex) { context.SetError("invalid_grant", ex.Message); return; } }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { try { context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); //認証処理 //LDAPに対して uid + password で認証を行う var userManager = new LdapUserManager(new LdapUserStore()); var ldapUser = await userManager.FindAsync(context.UserName, context.Password); if (ldapUser == null) { //認証失敗 context.SetError("invalid_grant", "The username or password is incorrect."); return; } //ユーザーを表す ClaimsIdentity を作成する var identity = await userManager.CreateIdentityAsync(ldapUser, context.Options.AuthenticationType); identity.AddClaim(new Claim("dn", ldapUser.DistinguishedName)); identity.AddClaim(new Claim("uid", ldapUser.Id)); context.Validated(identity); //認証登録 context.Request.Context.Authentication.SignIn(identity); } catch (Exception e) { context.SetError("Application Error", e.Message); } }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); Models.User user; using (var db = new Models.CalendarContext()) { user = db.Users.SingleOrDefault(u => u.PhoneNumber == context.UserName); if (user == null) { context.SetError("invalid_grant", "username"); return; } if (!Crypto.VerifyHashedPassword(user.Password, context.Password)) { context.SetError("invalid_grant", "password"); return; } } var identity = new ClaimsIdentity(context.Options.AuthenticationType); identity.AddClaim(new Claim(ClaimTypes.Name, user.Id.ToString())); identity.AddClaim(new Claim(ClaimTypes.Role, "user")); context.Validated(identity); }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); User user = userService.Login(context.UserName, context.Password); if (user == null) { context.SetError("invalid_grant", "The user name or password is incorrect."); return; } if (user.IsBanned) { context.SetError("invalid_grant", "This account has been banned."); return; } var identity = new ClaimsIdentity(context.Options.AuthenticationType); identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName)); identity.AddClaim(new Claim(ClaimTypes.Role, user.Role)); identity.AddClaim(new Claim("id", user.Id)); context.Validated(identity); }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] {"*"}); using (AuthRepository repo = new AuthRepository()) { var email = await repo.FindByEmailAsync(context.UserName); if (email == null) { context.SetError("invalid_grant", "The user name or password is incorrect."); context.OwinContext.Response.Headers["error"] = $"{"Invalid UserName or Password"}"; return; } IdentityUser user = await repo.FindUser(email.Name, context.Password); if (user == null) { context.SetError("invalid_grant", "The user name or password is incorrect."); context.OwinContext.Response.Headers["error"] = $"{"Invalid UserName or Password"}"; return; } context.OwinContext.Response.Headers["Keys"] = $"{user.Id}"; } var identity = new ClaimsIdentity(context.Options.AuthenticationType); identity.AddClaim(new Claim("sub", context.UserName)); identity.AddClaim(new Claim("role", "user")); context.Validated(identity); }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); ApplicationContext.User = new UnauthenticatedPrincipal(); // set it here because at this moment CSLA user is not set at all and will cause null-ref exceptions. if (MQ1Principal.Login(context.UserName, context.Password)) { var mq1Identity = (MQ1Identity)ApplicationContext.User.Identity; if (mq1Identity.ErrorInfo != null && !string.IsNullOrWhiteSpace(mq1Identity.ErrorInfo.ErrorMessage)) { context.SetError(mq1Identity.ErrorInfo.ErrorMessage); return; } var identity = new ClaimsIdentity(context.Options.AuthenticationType); identity.AddClaim(new Claim("userName", mq1Identity.Name)); // this can be used only on server side, if we need more data from tooken identity.AddClaim(new Claim("fullName", mq1Identity.IsAdmin ? "Admin" : mq1Identity.FullName, "self")); identity.AddClaim(new Claim("isAdmin", mq1Identity.IsAdmin.ToString().ToLowerInvariant(), "self")); // these properties can be used on client, to get more information about logged in user. context.Validated(identity); return; } context.SetError("Authentication failed."); }
// Context.Username represents the user's email, since that is used instead of a login username. public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { //context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>(); var user = await userManager.FindByEmailAsync(context.UserName.ToLower()); //User user = await userManager.FindAsync(context.UserName, context.Password); if (user == null) { context.SetError("invalid_grant", "The user name or password is incorrect."); return; } var isPasswordValid = await userManager.CheckPasswordAsync(user, context.Password); if (!isPasswordValid) { context.SetError("invalid_grant", "The user name or password is incorrect."); return; } ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, OAuthDefaults.AuthenticationType); ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager, CookieAuthenticationDefaults.AuthenticationType); AuthenticationProperties properties = CreateProperties(user.UserName); AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties); context.Validated(ticket); context.Request.Context.Authentication.SignIn(cookiesIdentity); }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { 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 ticket = new AuthenticationTicket(oAuthIdentity, null); context.Validated(ticket); }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { var userManager = context.OwinContext.GetUserManager<IdentityUserManager>(); IdentityUser 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", "Please confirm your email."); return; } ClaimsIdentity oAuthIdentity = await userManager.CreateIdentityAsync(user, OAuthDefaults.AuthenticationType); AuthenticationProperties properties = CreateProperties(user.UserName); AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties); context.Validated(ticket); }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>(); if (context.UserName.IsEmpty() || context.Password.IsEmpty()) { context.SetError("error_parameter", "The user name or password cannot be null."); return; } ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password); if (user == null) { context.SetError("invalid_grant", "The user name or password is incorrect."); return; } ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, OAuthDefaults.AuthenticationType); oAuthIdentity.AddClaim(new Claim("scope", "isLogged")); ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager, CookieAuthenticationDefaults.AuthenticationType); AuthenticationProperties properties = CreateProperties(user.UserName); AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties); context.Validated(ticket); context.Request.Context.Authentication.SignIn(cookiesIdentity); }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { UserManager<IdentityUser> userManager = context.OwinContext.GetUserManager<UserManager<IdentityUser>>(); IdentityUser user; try { user = await userManager.FindAsync(context.UserName, context.Password); } catch { // Could not retrieve the user due to error. context.SetError("server_error"); context.Rejected(); return; } if (user != null) { ClaimsIdentity identity = await userManager.CreateIdentityAsync( user, DefaultAuthenticationTypes.ExternalBearer); context.Validated(identity); } else { context.SetError("invalid_grant", "Invalid UserId or password'"); context.Rejected(); } }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { if (context.UserName == null || context.Password == null) { context.SetError("invalid_grant", "Login lub hasło niepoprawne."); return; } var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>(); ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password); if (user == null) { context.SetError("invalid_grant", "Login lub hasło niepoprawne."); return; } ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, OAuthDefaults.AuthenticationType); ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager, CookieAuthenticationDefaults.AuthenticationType); AuthenticationProperties properties = CreateProperties(user.UserName); AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties); context.Validated(ticket); context.Request.Context.Authentication.SignIn(cookiesIdentity); }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { using (var userPasswordStore = _userPasswordStoreFactory()) { var user = await userPasswordStore.FindByNameAsync(context.UserName); if (user == null) { context.SetError("invalid_grant", "No user by that user name exists."); return; } var passwordHash = await userPasswordStore.GetPasswordHashAsync(user); if (_passwordHasher.VerifyHashedPassword(passwordHash, context.Password) == PasswordVerificationResult.Failed) { context.SetError("invalid_grant", "The password is incorrect."); return; } ClaimsIdentity oauthIdentity = user.CreateIdentity(OAuthDefaults.AuthenticationType); ClaimsIdentity cookiesIdentity = user.CreateIdentity(CookieAuthenticationDefaults.AuthenticationType); var properties = new AuthenticationProperties(new Dictionary<string, string> { { "userName", user.UserName } }); var ticket = new AuthenticationTicket(oauthIdentity, properties); context.Validated(ticket); context.Request.Context.Authentication.SignIn(cookiesIdentity); } }
//funcion que recibe y valida el nombre y contraseña del usuario y lo valida contra la bd 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) //tambien valida que el usuario haya recibido y confirmado el email de confirmacion { context.SetError("invalid_grant", "User did not confirm email."); return; } ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, "JWT"); //agrego claims adicionales para tener ademas del token, el nombre de usuario y el rol // los claim son atributos nombre-valor que dan info sobre el usuario que quiere conectarse oAuthIdentity.AddClaim(new Claim("LigaId", user.LigaId.ToString())); var ticket = new AuthenticationTicket(oAuthIdentity, null); context.Validated(ticket); //SE GENERA EL TICKET DE ACCESO }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { //context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); var scope = context.OwinContext.Get<Autofac.Core.Lifetime.LifetimeScope>("autofac:OwinLifetimeScope"); var usrMgr = scope.GetService(typeof(ApplicationUserManager)) as ApplicationUserManager; ApplicationUser user = await usrMgr.FindAsync(context.UserName, context.Password); if (user == null) { context.SetError("invalid_grant", "The username or password is incorrect."); return; } if (!user.EmailConfirmed) { context.SetError("invalid_grant", "User did not confirm email."); } ClaimsIdentity oauthIdentity = await user.GenerateUserIdentityAsync(usrMgr, "JWT"); var ticket = new AuthenticationTicket(oauthIdentity, null); context.Validated(ticket); }
public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { if (!CredentialsAvailable(context)) { context.SetError("invalid_grant", "User or password is missing."); return base.GrantResourceOwnerCredentials(context); } Credentials credentials = GetCredentials(context); UserIdentity userIdentity; if (authService.TryAuthentifcate(credentials, out userIdentity)) { var oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType); oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, userIdentity.Name)); // Add Claims from DB: foreach (var claim in userIdentity.Claims) { oAuthIdentity.AddClaim(new Claim(claim.Type, claim.Value)); } context.Validated(oAuthIdentity); return base.GrantResourceOwnerCredentials(context); } else { context.SetError("invalid_grant", "Invalid credentials."); return base.GrantResourceOwnerCredentials(context); } }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { 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; } else if (user.EmailConfirmed == false) { context.SetError("email_not_confirmed", "Please confirm your email before login"); return; } ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, OAuthDefaults.AuthenticationType); ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager, CookieAuthenticationDefaults.AuthenticationType); AuthenticationProperties properties = CreateProperties(user.UserName, user.FullName); AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties); context.Validated(ticket); context.Request.Context.Authentication.SignIn(cookiesIdentity); }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { var allowedOrigin = "*"; context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin }); var userRepository = context.OwinContext.GetUserManager<UserRepository>(); User user = userRepository.GetUserByUsername(context.UserName); if (user == null) { context.SetError("invalid_grant", "The user name is incorrect."); return; } var hash = Criptografia.Criptografar(context.Password); if (user.PasswordHash != hash) { context.SetError("invalid_grant", "The password is incorrect."); return; } if (!user.EmailConfirmed) { context.SetError("invalid_grant", "User did not confirm email."); return; } var identity = new ClaimsIdentity(context.Options.AuthenticationType); identity.AddClaim(new Claim("user", context.UserName)); context.Validated(identity); }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { var userManager = _container.Resolve<CustomUserManager>(); context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); var user = await userManager.FindByNameAsync(context.UserName); if (user == null) { context.SetError("invalid_grant", "The user name doesnt Exist"); return; } var passwordCorrect = await userManager.CheckPasswordAsync(user, context.Password); if (!passwordCorrect) { context.SetError("invalid_grant", "The password is fake"); return; } var identity = new ClaimsIdentity(context.Options.AuthenticationType); identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName)); identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id.ToString())); context.Validated(identity); }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { user User = await CheckUser(context.UserName); if (User == null) { context.SetError("invalid_grant", "账号不存在"); return; } if (User.PassWord.TrimEnd(' ') != Regent.MCSRules.Configuration.Encrypt(context.Password, key)) { context.SetError("invalid_grant", "密码不正确"); return; } if (User.ShutOut == true) { context.SetError("invalid_grant", "账号已停用"); return; } //EnableCros(context); ClaimsIdentity oAuthIdentity = new ClaimsIdentity(new GenericIdentity(User.UserNo, OAuthDefaults.AuthenticationType)); context.Validated(oAuthIdentity); }
public override async Thread.Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); using (UserManager<TaskUser> userManager = _userManagerFactory()) { // // //userManager.PasswordHasher = new ClearPasswordHasher(); TaskUser user = await userManager.FindAsync(context.UserName, context.Password); //user = user1; if (user == null) { context.SetError("invalid_grant", "The user name or password is incorrect."); return; } if (userManager.GetLockoutEnabled(user.Id)) { context.SetError("locked_out", "The user is locked out"); return; } ClaimsIdentity oAuthIdentity = await userManager.CreateIdentityAsync(user, context.Options.AuthenticationType); ClaimsIdentity cookiesIdentity = await userManager.CreateIdentityAsync(user, CookieAuthenticationDefaults.AuthenticationType); AuthenticationProperties properties = CreateProperties(user.UserName); AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties); context.Validated(ticket); context.Request.Context.Authentication.SignIn(cookiesIdentity); } }
/// <summary> /// oAuth Resource Password Login Flow /// 1. Checks the password with the Identity API /// 2. Create a user identity for the bearer token /// 3. Create a user identity for the cookie /// 4. Calls the context.Validated(ticket) to tell the oAuth2 server to protect the ticket as an access token and send it out in JSON payload /// 5. Signs the cookie identity so it can send the authentication cookie /// </summary> /// <param name="context">The authorization context</param> /// <returns>Task</returns> public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { using (ApplicationUserManager userManager = _userManagerFactory()) { userManager.MaxFailedAccessAttemptsBeforeLockout = 5; userManager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5); UserProfile user = await userManager.FindByNameAsync(context.UserName); if (user == null) { context.SetError("invalid_grant", "Invalid username"); return; } if (await userManager.IsLockedOutAsync(user.Id)) { var timeleft = user.LockoutEndDateUtc.GetValueOrDefault().Subtract(DateTime.UtcNow); var timetype = timeleft.Minutes == 0 ? "seconds" : "minute(s)"; var timevalue = timeleft.Minutes == 0 ? timeleft.Seconds : timeleft.Minutes; context.SetError("invalid_grant", string.Format("Your account is locked for {0} more {1}", timevalue, timetype)); return; } if (!(await userManager.CheckPasswordAsync(user, context.Password))) { await userManager.AccessFailedAsync(user.Id); if (await userManager.IsLockedOutAsync(user.Id)) { context.SetError("invalid_grant", string.Format("Your account has been locked for {0} minutes", userManager.DefaultAccountLockoutTimeSpan.Minutes)); return; } var possibleAttempts = userManager.MaxFailedAccessAttemptsBeforeLockout; var currentcount = await userManager.GetAccessFailedCountAsync(user.Id); context.SetError("invalid_grant", string.Format("Invalid password. Your account will be locked after {0} more failed attempts.", possibleAttempts - currentcount)); return; } ClaimsIdentity oAuthIdentity = await userManager.CreateIdentityAsync(user, context.Options.AuthenticationType); ClaimsIdentity cookiesIdentity = await userManager.CreateIdentityAsync(user, CookieAuthenticationDefaults.AuthenticationType); var justCreatedIdentity = await userManager.FindByNameAsync(user.UserName); var roles = await userManager.GetRolesAsync(justCreatedIdentity.Id); AuthenticationProperties properties = CreateProperties(user.UserName, roles.ToArray(), user.EmailConfirmed); AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties); context.Validated(ticket); context.Request.Context.Authentication.SignIn(cookiesIdentity); } }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { //var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>(); //ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password); //debug using (var lifeTimeScope = _lifetimeScope.BeginLifetimeScope()) { Account user = _queryProcessor.Execute(new GetAccountQueryDto(context.UserName)); if (user == null) { context.SetError("invalid_grant", "Invalid credentials: Username or Password incorrect"); context.Rejected(); return; } if (!user.VerifyPassword(context.Password)) { context.SetError("invalid_grant", "Invalid credentials: Username or Password incorrect"); context.Rejected(); return; } //if (!user.EmailConfirmed) //{ // context.SetError("invalid_grant", "User did not confirm email."); // return; //} var claimsIdentity = new ClaimsIdentity(context.Options.AuthenticationType); //ClaimsIdentity oAuthIdentity = await accountManager.CreateIdentityAsync(user, "JWT"); claimsIdentity.AddClaim(new Claim(ClaimTypes.Name, user.Username)); claimsIdentity.AddClaim(new Claim("accountId", user.Id.ToString())); claimsIdentity.AddClaim(new Claim("IP", context.Request.RemoteIpAddress)); foreach (AccountRole role in user.AccountRoles) { claimsIdentity.AddClaim(new Claim(ClaimTypes.Role, role.AccountRoleType.ToString())); } var authenticationProperties = new AuthenticationProperties() { ExpiresUtc = DateTime.UtcNow.AddHours(24), IsPersistent = true, }; claimsIdentity.AddClaim(new Claim(ClaimTypes.Expiration, authenticationProperties.ExpiresUtc.ToString())); var ticket = new AuthenticationTicket(claimsIdentity, authenticationProperties); context.Validated(ticket); } }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { UserManager = ManagerModel.AppUser; SignInManager = ManagerModel.SigninUser; var identity = new ClaimsIdentity(context.Options.AuthenticationType); context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); //var owin = new OwinContext(); //_userManager = new ApplicationUserManager(new UserStore<ApplicationUser>(owin.Get<ApplicationDbContext>())); //_signInManager = new ApplicationSignInManager(owin.GetUserManager<ApplicationUserManager>(), owin.Authentication); var store = new UserStore <ApplicationUser>(new ApplicationDbContext()); var userManager = new ApplicationUserManager(store); var user = await userManager.FindAsync(context.UserName, context.Password); if (user == null) { context.SetError("invalid_grant", "The user name or password is incorrect."); //context.Rejected(); return; } identity = await userManager.CreateIdentityAsync(user, context.Options.AuthenticationType); //identity.AddClaim(new Claim("Username", context.UserName)); identity.AddClaim(new Claim("SecurityStamp", user.SecurityStamp)); var props = new AuthenticationProperties(new Dictionary <string, string> { { "userdisplayname", context.UserName } }); var ticket = new AuthenticationTicket(identity, props); context.Validated(ticket); }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { var identity = new ClaimsIdentity(context.Options.AuthenticationType); if (context.UserName == "admin" && context.Password == "admin") { identity.AddClaim(new Claim(ClaimTypes.Role, "admin")); identity.AddClaim(new Claim("username", "admin")); identity.AddClaim(new Claim(ClaimTypes.Name, "Hi Admin")); context.Validated(identity); } else if (context.UserName == "user" && context.Password == "user") { identity.AddClaim(new Claim(ClaimTypes.Role, "user")); identity.AddClaim(new Claim("username", "user")); identity.AddClaim(new Claim(ClaimTypes.Name, "Hi User")); context.Validated(identity); } else { context.SetError("invalid_grant", "Provided username and password is incorrect"); return; } }
public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { var identity = new ClaimsIdentity(context.Options.AuthenticationType); if (context.UserName == "*****@*****.**" && context.Password == "pass1234") { identity.AddClaim(new Claim(ClaimTypes.Role, "admin")); identity.AddClaim(new Claim("username", "admin")); identity.AddClaim(new Claim(ClaimTypes.Name, "Vickey Wadhwani")); context.Validated(identity); } else if (context.UserName == "*****@*****.**" && context.Password == "user1234") { identity.AddClaim(new Claim(ClaimTypes.Role, "user")); identity.AddClaim(new Claim("username", "user")); identity.AddClaim(new Claim(ClaimTypes.Name, "John doe")); context.Validated(identity); } else { context.SetError("invalid_grant", "Provided username and password is incorrect"); } return(Task.FromResult(0)); }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { 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; } ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, OAuthDefaults.AuthenticationType); ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager, CookieAuthenticationDefaults.AuthenticationType); AuthenticationProperties properties = CreateProperties(user.UserName); AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties); context.Validated(ticket); context.Request.Context.Authentication.SignIn(cookiesIdentity); }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { var userManager = context.OwinContext.GetUserManager <ApplicationUserManager>(); var user = await userManager.FindAsync(userName : context.UserName, password : context.Password); if (user == null) { context.SetError(error: "invalid_grant", errorDescription: "The user name or password is incorrect."); return; } var oAuthIdentity = await user.GenerateUserIdentityAsync(manager : userManager, authenticationType : OAuthDefaults.AuthenticationType); var cookiesIdentity = await user.GenerateUserIdentityAsync(manager : userManager, authenticationType : CookieAuthenticationDefaults.AuthenticationType); var properties = CreateProperties(userName: user.UserName); var ticket = new AuthenticationTicket(identity: oAuthIdentity, properties: properties); context.Validated(ticket: ticket); context.Request.Context.Authentication.SignIn(cookiesIdentity); }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { UserService userservice = new UserService(); MyUsersDBEntities userDb = new MyUsersDBEntities(); var identity = new ClaimsIdentity(context.Options.AuthenticationType); string contextPassword = ""; using (var db = new MyUsersDBEntities()) { var user = db.Users.ToList(); if (user != null) { foreach (var u in db.Users.Where(x => x.isPasswordHashed == true && x.Username == context.UserName)) { LoginService loginService = new LoginService(); contextPassword = context.Password.ToString(); contextPassword = loginService.reEncryptPassword(contextPassword, u.Salt, u.Hash, u); if (!string.IsNullOrEmpty(user.Where(x => x.Username == context.UserName && x.Hash == contextPassword).FirstOrDefault().Username)) { var currentUser = user.Where(x => x.Username == context.UserName && x.Hash == contextPassword).FirstOrDefault(); identity.AddClaim(new Claim("UserName", currentUser.Username)); identity.AddClaim(new Claim("Id", Convert.ToString(currentUser.Id))); var props = new AuthenticationProperties(new Dictionary <string, string> { { "Username", context.UserName }, }); var ticket = new AuthenticationTicket(identity, props); context.Validated(ticket); } else { context.SetError("invalid_grant", "Provided username and password is not matching, Please retry."); context.Rejected(); } } foreach (var u in db.Users.Where(x => x.isPasswordHashed == null && x.Username == context.UserName)) { contextPassword = context.Password; if (!string.IsNullOrEmpty(user.Where(x => x.Username == context.UserName && x.Hash == contextPassword).FirstOrDefault().Username)) { var currentUser = user.Where(x => x.Username == context.UserName && x.Hash == contextPassword).FirstOrDefault(); identity.AddClaim(new Claim("UserName", currentUser.Username)); identity.AddClaim(new Claim("Id", Convert.ToString(currentUser.Id))); var props = new AuthenticationProperties(new Dictionary <string, string> { { "Username", context.UserName }, }); var ticket = new AuthenticationTicket(identity, props); context.Validated(ticket); } else { context.SetError("invalid_grant", "Provided username and password is not matching, Please retry."); context.Rejected(); } } } else { context.SetError("invalid_grant", "Provided username and password is not matching, Please retry."); context.Rejected(); } return; } }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { var userManager = context.OwinContext.GetUserManager <ApplicationUserManager>(); ApplicationUser user; // find user by username first user = await userManager.FindByNameAsync(context.UserName); if (user == null) { context.SetError("invalid_grant", "The user name or password is incorrect."); return; } else { var validCredentials = await userManager.FindAsync(user.UserName, context.Password); var lockoutNotice = string.Format("Your account has been locked out for {0} minutes due to multiple failed login attempts.", userManager.DefaultAccountLockoutTimeSpan.Minutes.ToString()); // When a user is lockedout, this check is done to ensure that even if the credentials are valid // the user can not login until the lockout duration has passed if (await userManager.IsLockedOutAsync(user.Id)) { context.SetError("", lockoutNotice); return; } // if user is subject to lockouts and the credentials are invalid // record the failure and check if user is lockedout and display message, otherwise, // display the number of attempts remaining before lockout else if (await userManager.GetLockoutEnabledAsync(user.Id) && validCredentials == null) { // Record the failure which also may cause the user to be locked out await userManager.AccessFailedAsync(user.Id); string message; if (await userManager.IsLockedOutAsync(user.Id)) { message = lockoutNotice; } else { int accessFailedCount = await userManager.GetAccessFailedCountAsync(user.Id); int attemptsLeft = userManager.MaxFailedAccessAttemptsBeforeLockout - accessFailedCount; message = string.Format( "Invalid credentials. You have {0} more attempt(s) before your account gets locked out.", attemptsLeft); } context.SetError("", message); return; } else if (validCredentials == null) { context.SetError("invalid_grant", "The user name or password is incorrect."); return; } else { // When token is verified correctly, clear the access failed count used for lockout await userManager.ResetAccessFailedCountAsync(user.Id); } } ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, OAuthDefaults.AuthenticationType); ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager, CookieAuthenticationDefaults.AuthenticationType); AuthenticationProperties properties = CreateProperties(user.UserName); AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties); context.Validated(ticket); context.Request.Context.Authentication.SignIn(cookiesIdentity); }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { _iAuthorizationBus = (IAuthorizationBus)GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(IAuthorizationBus)); var allowedOrigin = context.OwinContext.Get <string>("as:clientAllowedOrigin"); if (allowedOrigin == null) { allowedOrigin = "*"; } //context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); if (context.UserName == null || context.Password == null) { context.SetError("invalid_request", Resources.InvalidLoginRequest); return; } var user = await _iAuthorizationBus.FindUser(context.UserName, context.Password); if (user == null) { context.SetError("invalid_grant", Resources.InvalidEmailOrPassword); return; } var userRoles = await _iAuthorizationBus.UserRoles(user.Id); var identity = new ClaimsIdentity(context.Options.AuthenticationType); identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName)); identity.AddClaim(new Claim(AuthConstants.CustomClaims.UserId, user.Id)); foreach (var role in userRoles) { identity.AddClaim(new Claim(ClaimTypes.Role, role)); } var props = new AuthenticationProperties(new Dictionary <string, string> { { AuthConstants.CustomAuthProps.ClientId, (context.ClientId == null) ? string.Empty : context.ClientId }, { AuthConstants.CustomAuthProps.UserName, context.UserName }, { AuthConstants.CustomAuthProps.IsAdmin, (userRoles.Contains(ApplicationConstants.ADMIN)) ? "true" : "false" }, { AuthConstants.CustomAuthProps.UserId, user.Id }, { AuthConstants.CustomAuthProps.FullName, user.FirstName + " " + user.LastName }, { AuthConstants.CustomAuthProps.ProfilePic, user.ProfileImage } }); var ticket = new AuthenticationTicket(identity, props); context.Validated(ticket); }
public override async Task GrantResourceOwnerCredentials( OAuthGrantResourceOwnerCredentialsContext context ) { var owinContext = context.OwinContext; var options = context.Options; if (owinContext == null || options == null) { context.SetError("server_error"); if (context.Response != null) { context.Response.StatusCode = 500; } return; } var username = context.UserName; var password = context.Password; if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password)) { context.SetError("credentials_missing"); return; } username = username.Trim(); var user = User.Find(username); if (!user?.IsPasswordValid(password.ToUpper().Trim()) ?? true) { context.SetError("credentials_invalid"); return; } if (!user.Power?.Api ?? true) { context.SetError("insufficient_permissions"); return; } if (!Guid.TryParse(context.ClientId, out var clientId)) { Log.Diagnostic("Received invalid client id '{0}'.", context.ClientId); } var ticketId = Guid.NewGuid(); owinContext.Set("ticket_id", ticketId); var identity = new ClaimsIdentity(options.AuthenticationType); identity.AddClaim(new Claim(IntersectClaimTypes.UserId, user.Id.ToString())); identity.AddClaim(new Claim(IntersectClaimTypes.UserName, user.Name)); identity.AddClaim(new Claim(IntersectClaimTypes.Email, user.Email)); identity.AddClaim(new Claim(IntersectClaimTypes.ClientId, clientId.ToString())); identity.AddClaim(new Claim(IntersectClaimTypes.TicketId, ticketId.ToString())); if (user.Power != null) { identity.AddClaims(user.Power.Roles.Select(role => new Claim(IntersectClaimTypes.Role, role))); if (user.Power.ApiRoles?.UserQuery ?? false) { identity.AddClaim(new Claim(IntersectClaimTypes.AccessRead, typeof(User).FullName)); identity.AddClaim( new Claim( IntersectClaimTypes.AccessRead, typeof(User).GetProperty(nameof(User.Ban))?.GetFullName() ) ); identity.AddClaim( new Claim( IntersectClaimTypes.AccessRead, typeof(User).GetProperty(nameof(User.Mute))?.GetFullName() ) ); identity.AddClaim( new Claim( IntersectClaimTypes.AccessRead, typeof(User).GetProperty(nameof(User.IsBanned))?.GetFullName() ) ); identity.AddClaim( new Claim( IntersectClaimTypes.AccessRead, typeof(User).GetProperty(nameof(User.IsMuted))?.GetFullName() ) ); } } var ticketProperties = new AuthenticationProperties(); var ticket = new AuthenticationTicket(identity, ticketProperties); context.Validated(ticket); }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { var allowedOrigin = context.OwinContext.Get <string>("as:clientAllowedOrigin") ?? "*"; ApplicationUser user = new ApplicationUser(); var claimsIdentity = new ClaimsIdentity(context.Options.AuthenticationType); var concatenatedRoles = ""; context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin }); AspNetUserProperty userProperty; using (AuthRepository _repo = new AuthRepository()) { if (TokenIdentityHelper.IsCredentialForSingleClick(context.Password)) { var userId = TokenIdentityHelper.GetUserIdSingleClickSignInToken(context.Password); user = await _repo.FindByUserIdAsync(userId); } else { user = await _repo.FindUser(context.UserName, context.Password); } if (user == null) { context.SetError("invalid_grant", "The user name or password is incorrect."); return; } else if (!user.IsActive || _repo.IsLockedOut(user.Id)) { context.SetError("blocked_user", "Your account is disabled."); return; } var userRoles = await _repo.FindRolesAsync(user.Id); foreach (var role in userRoles) { claimsIdentity.AddClaim(new Claim(ClaimTypes.Role, role)); } concatenatedRoles = string.Join(",", userRoles); //Add user property userProperty = await _repo.FindUserProperty(user.Id); //addingclaims claimsIdentity.AddClaim(new Claim(ClaimTypes.Name, user.FirstName)); claimsIdentity.AddClaim(new Claim(GlobalConstants.Account.ClaimTypes.UserName, user.UserName)); claimsIdentity.AddClaim(new Claim(GlobalConstants.Account.ClaimTypes.Subject, user.Id)); claimsIdentity.AddClaim(new Claim(GlobalConstants.Account.ClaimTypes.Issuer, GlobalConstants.EhrsIssuerUri)); } Dictionary <string, string> properties = new Dictionary <string, string> { { "as:client_id", (context.ClientId == null) ? string.Empty : context.ClientId } }; properties.Add("userName", context.UserName); properties.Add("firstName", user.FirstName); properties.Add("roles", concatenatedRoles); var authProps = new AuthenticationProperties(properties); var ticket = new AuthenticationTicket(claimsIdentity, authProps); 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 roleHeader = "Role"; var userIdHeader = "UserId"; var userNameHeader = "UserName"; context.OwinContext.Response.Headers.Add("Access-Control-Expose-Headers", new[] { roleHeader, userIdHeader, userNameHeader }); ApplicationUserManager userManager = context.OwinContext.GetUserManager <ApplicationUserManager>(); BAIdentityUser user = await userManager.FindAsync(context.UserName, context.Password); if (user == null) { context.SetError("invalid_grant", "The user name or password is incorrect.!!!!"); return; } BAContext BAContext = new BAContext(); var userRole = user.Roles.First().RoleId; var role = BAContext.Roles.FirstOrDefault(r => r.Id == userRole); //BAContext.Roles.Where(x => //bool isAdmin = await userManager.IsInRoleAsync(user.UserName, "Admin"); if (role.Name.Equals("Admin")) { context.OwinContext.Response.Headers.Add("Role", new[] { "Admin" }); } else if (role.Name.Equals("Manager")) { context.OwinContext.Response.Headers.Add("Role", new[] { "Manager" }); } else { context.OwinContext.Response.Headers.Add("Role", new[] { "User" }); } context.OwinContext.Response.Headers.Add("UserId", new[] { user.AppUserId.ToString() }); if (role.Name.Equals("Admin")) { string username = "******" + user.Email; context.OwinContext.Response.Headers.Add("UserName", new[] { username }); } else { AppUser appUser = BAContext.AppUsers.Where(au => au.Id == user.AppUserId).FirstOrDefault(); string username = role.Name + ": " + appUser.Name + " " + appUser.LastName; context.OwinContext.Response.Headers.Add("UserName", new[] { username }); } ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, "JWT"); var ticket = new AuthenticationTicket(oAuthIdentity, null); context.Validated(ticket); } catch (Exception e) { Console.WriteLine(e); } }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { DatabaseContext dbContext = new DatabaseContext(); string userName = context.UserName; string password = context.Password; if (string.IsNullOrWhiteSpace(userName) || string.IsNullOrWhiteSpace(password)) { context.SetError("invalid_grant", "Invalid credentials"); return; } User user = dbContext.Users.Where(x => x.UserName == context.UserName).SingleOrDefault(); var identity = new ClaimsIdentity(context.Options.AuthenticationType); if (user != null) { UserDTO userDTO = UserDTO.From(user); string existingPassword = DataSecurity.Decrypt(user.Password); if (password != existingPassword) { context.SetError("invalid_grant", "Provided username and password is incorrect"); return; } UserRole userRole = dbContext.UserRoles.Where(x => x.UserId == user.Id).SingleOrDefault(); if (userRole != null) { identity.AddClaim(new Claim(ClaimTypes.Role, userRole.Role.Name)); identity.AddClaim(new Claim("username", user.UserName)); identity.AddClaim(new Claim(ClaimTypes.Email, user.UserName)); identity.AddClaim(new Claim(ClaimTypes.UserData, user.Id.ToString())); identity.AddClaim(new Claim("userId", user.Id.ToString())); var props = new AuthenticationProperties(new Dictionary <string, string> { { "username", userName }, { "role", userRole.Role.Name }, { "id", userDTO.Id.ToString() } }); if (userDTO.Role != null && userDTO.Role.Count > 0) { foreach (RoleDTO role in userDTO.Role) { if (role.Accesses != null && role.Accesses.Count > 0) { List <MenuDTO> menuList = role.Accesses.ToList(); foreach (MenuDTO menu in menuList) { identity.AddClaim(new Claim(ClaimTypes.Webpage, menu.ControllerName + "$%" + menu.ActionName)); } } } } string urlAPI = string.Format("api/Menu/GetByGeneralAccess?generalAccess=1"); var generlAccessMenu = dbContext.Menus.Where(x => x.IsGeneralAccess == true).ToList(); if (generlAccessMenu.Count > 0) { IList <MenuDTO> generlAccessMenuDTO = MenuDTO.From(generlAccessMenu); if (generlAccessMenuDTO != null && generlAccessMenuDTO.Count > 0) { foreach (MenuDTO menu in generlAccessMenuDTO) { identity.AddClaim(new Claim(ClaimTypes.Webpage, menu.ControllerName + "$%" + menu.ActionName)); } } } var ticket = new AuthenticationTicket(identity, props); context.Validated(ticket); context.Request.Context.Authentication.SignIn(identity); } else { context.SetError("invalid_grant", "Existing user not set any Role(s)"); return; } } else { context.SetError("invalid_grant", "Provided username and password is incorrect"); return; } }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { try { var userStore = new UserStore<ApplicationUserIdentity>(new AuthenticationDbContext()); var manager = new UserManager<ApplicationUserIdentity>(userStore); var userAuth = await manager.FindAsync(context.UserName, context.Password); if (userAuth != null) { var identity = new ClaimsIdentity(context.Options.AuthenticationType); identity.AddClaim(new Claim("Username", userAuth.UserName)); identity.AddClaim(new Claim("Email", userAuth.Email)); identity.AddClaim(new Claim("UserRefID", userAuth.UserRefID.ToString())); identity.AddClaim(new Claim("LoggedOn", DateTime.Now.ToString())); var user = ServiceProvider.EntityContext.Users.Get(int.Parse(userAuth.UserRefID.ToString())); if (!user.IsActive) { context.SetError("invalid_grant", "The user name or password is incorrect."); } else { var userRoles = manager.GetRoles(userAuth.Id); foreach (string roleName in userRoles) { identity.AddClaim(new Claim(ClaimTypes.Role, roleName)); } //return data to client var additionalData = new AuthenticationProperties(new Dictionary<string, string>{ { "role", Newtonsoft.Json.JsonConvert.SerializeObject(userRoles) }, { "userName", context.UserName }, { "isUseDiningRoom", user.IsUseDiningRoom.ToString() } }); AuthenticationProperties properties = CreateProperties(context.UserName); AuthenticationTicket ticket = new AuthenticationTicket(identity, additionalData); context.Validated(ticket); } } else { context.SetError("invalid_grant", "The user name or password is incorrect."); } return; } catch (Exception ep) { throw; } }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { var allowedOrigin = context.OwinContext.Get <string>("as:clientAllowedOrigin") ?? "*"; context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin }); var identity = new ClaimsIdentity(context.Options.AuthenticationType); var props = new AuthenticationProperties(new Dictionary <string, string> { { "as:client_id", context.ClientId ?? string.Empty } } ); using (AuthRepository repo = new AuthRepository(context.OwinContext, Startup.DataProtectionProvider)) { // Require the user to have a confirmed email before they can log on. var user = await repo.FindUser(context.UserName, context.Password); if (user != null) { if (!await repo.IsUserConfirmed(user)) { await repo.SendEmailConfirmationTokenEmail(user.Id, _client.AllowedOrigin); context.SetError("", "You must have a confirmed email to log on. The confirmation token has been resent to your email account."); return; } } else { context.SetError("invalid_grant", "The user name or password is incorrect."); return; } identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName)); foreach (var role in await repo.GetUserRoles(user.Id)) { identity.AddClaim(new Claim(ClaimTypes.Role, role)); } identity.AddClaim(new Claim("sub", context.UserName)); props.Dictionary.Add(new KeyValuePair <string, string> ( "email", user.Email )); props.Dictionary.Add(new KeyValuePair <string, string> ( "username", user.UserName )); props.Dictionary.Add(new KeyValuePair <string, string> ( "roles", Json.Encode((await repo.GetUserRoles(user.Id))) )); } var ticket = new AuthenticationTicket(identity, props); //var currentUtc = new SystemClock().UtcNow; //ticket.Properties.IssuedUtc = currentUtc; //ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromSeconds(90)); 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, "JWT"); // var ticket = new AuthenticationTicket(oAuthIdentity, null); // context.Validated(ticket); //} public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { string uid = ""; string usertype = ""; string username = ""; string userroles = ""; string name = ""; string passwordchanged = ""; IList <string> roles = null; ApplicationUser user = null; var allowedOrigin = context.OwinContext.Get <string>("as:clientAllowedOrigin"); if (allowedOrigin == null) { allowedOrigin = "*"; } context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin }); using (AuthRepository _repo = new AuthRepository()) { if (IsValidEmail(context.UserName) == true) { ApplicationUser us = await _repo.FindUserByEmail(context.UserName); if (us == null) { context.SetError("true", "The email or password is incorrect."); return; } user = await _repo.FindUser(us.UserName, context.Password); if (user == null) { context.SetError("true", "The user name or password is incorrect."); return; } uid = user.Id; roles = await _repo.GetUserRoles(user.Id); //role = roles.FirstOrDefault(); username = user.UserName; var upi = _repo.GetUserPrimaryInfo(user.Id); name = upi.PTitle + " " + upi.FirstName + " " + upi.LastName; passwordchanged = user.PasswordChanged.ToString(); } else { user = await _repo.FindUser(context.UserName, context.Password); if (user == null) { context.SetError("true", "The user name or password is incorrect."); return; } //if (user.EmailConfirmed == false) //{ // context.SetError("true", "Account not activated"); // return; //} uid = user.Id; roles = await _repo.GetUserRoles(user.Id); //role = roles.FirstOrDefault(); username = user.UserName; var upi = _repo.GetUserPrimaryInfo(user.Id); name = upi.PTitle + " " + upi.FirstName + " " + upi.LastName; passwordchanged = user.PasswordChanged.ToString(); } } var identity = new ClaimsIdentity(context.Options.AuthenticationType); identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName)); identity.AddClaim(new Claim(ClaimTypes.GivenName, name)); identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id)); if (roles != null && roles.Any()) { foreach (var role in roles) { identity.AddClaim(new Claim(ClaimTypes.Role, role)); userroles += role + ","; } userroles = userroles.Substring(0, userroles.Length - 1); } identity.AddClaim(new Claim("sub", context.UserName)); var props = new AuthenticationProperties(new Dictionary <string, string> { //{ // "as:client_id", (context.ClientId == null) ? string.Empty : context.ClientId //}, { "userName", username }, { "userId", uid }, { "role", userroles }, { "name", name }, { "passwordchanged", passwordchanged }, { "error", "false" } }); var ticket = new AuthenticationTicket(identity, props); context.Validated(ticket); }
//public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) //{ // try // { // var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>(); // var array = context.Scope.ToArray(); // var fbId = array.GetValue(0).ToString(); // var brandID = Convert.ToInt32(array.GetValue(1)); // var phone = array.GetValue(2).ToString(); // var customerId = Convert.ToInt32(array.GetValue(3)); // //var a = array.GetValue(1); // //= (int)array.GetValue(1); // ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password); // if (user == null) // { // if (fbId.Length > 0) // { // var customerDomain = new CustomerDomain(); // CustomerAPIViewModel customer = customerDomain.GetCustomerByBrandIdAndFbId(brandID, fbId); // if (customer != null) // { // ApplicationDbContext db = new ApplicationDbContext(); // ApplicationUser userVM = db.Users.FirstOrDefault(x => x.Id == customer.AspUserVM.Id); // ClaimsIdentity oAuthIdentityVM = await userVM.GenerateUserIdentityAsync(userManager, // OAuthDefaults.AuthenticationType); // ClaimsIdentity cookiesIdentityVM = await userVM.GenerateUserIdentityAsync(userManager, // CookieAuthenticationDefaults.AuthenticationType); // AuthenticationProperties propertiesVM = CreateProperties(userVM.UserName); // AuthenticationTicket ticketVM = new AuthenticationTicket(oAuthIdentityVM, propertiesVM); // context.Validated(ticketVM); // context.Request.Context.Authentication.SignIn(cookiesIdentityVM); // } // } // else if (phone.Length > 0) // { // var customerDomain = new CustomerDomain(); // CustomerAPIViewModel customerByPhone = customerDomain.GetCustomersByPhonenumber(phone, brandID); // if (customerByPhone != null) // { // ApplicationDbContext db = new ApplicationDbContext(); // ApplicationUser userVM = db.Users.FirstOrDefault(x => x.Id == customerByPhone.AspUserVM.Id); // ClaimsIdentity oAuthIdentityVM = await userVM.GenerateUserIdentityAsync(userManager, // OAuthDefaults.AuthenticationType); // ClaimsIdentity cookiesIdentityVM = await userVM.GenerateUserIdentityAsync(userManager, // CookieAuthenticationDefaults.AuthenticationType); // AuthenticationProperties propertiesVM = CreateProperties(userVM.UserName); // AuthenticationTicket ticketVM = new AuthenticationTicket(oAuthIdentityVM, propertiesVM); // context.Validated(ticketVM); // context.Request.Context.Authentication.SignIn(cookiesIdentityVM); // } // } // else if (customerId > 0) // { // var customerDomain = new CustomerDomain(); // CustomerAPIViewModel customerById = customerDomain.GetCustomerById(customerId); // if (customerById != null) // { // ApplicationDbContext db = new ApplicationDbContext(); // ApplicationUser userVM = db.Users.FirstOrDefault(x => x.Id == customerById.AspUserVM.Id); // ClaimsIdentity oAuthIdentityVM = await userVM.GenerateUserIdentityAsync(userManager, // OAuthDefaults.AuthenticationType); // ClaimsIdentity cookiesIdentityVM = await userVM.GenerateUserIdentityAsync(userManager, // CookieAuthenticationDefaults.AuthenticationType); // AuthenticationProperties propertiesVM = CreateProperties(userVM.UserName); // AuthenticationTicket ticketVM = new AuthenticationTicket(oAuthIdentityVM, propertiesVM); // context.Validated(ticketVM); // context.Request.Context.Authentication.SignIn(cookiesIdentityVM); // } // } // else // { // context.SetError("invalid_grant", "The user name or password is incorrect."); // return; // } // } // else // { // ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, // OAuthDefaults.AuthenticationType); // ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager, // CookieAuthenticationDefaults.AuthenticationType); // AuthenticationProperties properties = CreateProperties(user.UserName); // AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties); // context.Validated(ticket); // context.Request.Context.Authentication.SignIn(cookiesIdentity); // } // } // catch (Exception e) // { // Console.WriteLine(e); // } //} #endregion public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { try { var userManager = context.OwinContext.GetUserManager <ApplicationUserManager>(); var array = context.Scope.ToArray(); var fbId = array.GetValue(0).ToString(); var brandID = Convert.ToInt32(array.GetValue(1)); var phone = array.GetValue(2).ToString(); var customerId = Convert.ToInt32(array.GetValue(3)); //var a = array.GetValue(1); //= (int)array.GetValue(1); ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password); if (user == null) { ApplicationUser userVM = new ApplicationUser(); var customerDomain = new CustomerDomain(); CustomerAPIViewModel customer = new CustomerAPIViewModel(); if (fbId.Length > 0) { customer = customerDomain.GetCustomerByBrandIdAndFbId(brandID, fbId); if (customer != null) { ApplicationDbContext db = new ApplicationDbContext(); userVM = db.Users.FirstOrDefault(x => x.Id == customer.AspUserVM.Id); } } else if (phone.Length > 0) { CustomerAPIViewModel customerByPhone = customerDomain.GetCustomersByPhonenumber(phone, brandID); if (customerByPhone != null) { ApplicationDbContext db = new ApplicationDbContext(); userVM = db.Users.FirstOrDefault(x => x.Id == customerByPhone.AspUserVM.Id); } } else if (customerId > 0) { CustomerAPIViewModel customerById = customerDomain.GetCustomerById(customerId); if (customerById != null) { ApplicationDbContext db = new ApplicationDbContext(); userVM = db.Users.FirstOrDefault(x => x.Id == customerById.AspUserVM.Id); } } else { context.SetError("invalid_grant", "The user name or password is incorrect."); return; } ClaimsIdentity oAuthIdentityVM = await userVM.GenerateUserIdentityAsync(userManager, OAuthDefaults.AuthenticationType); ClaimsIdentity cookiesIdentityVM = await userVM.GenerateUserIdentityAsync(userManager, CookieAuthenticationDefaults.AuthenticationType); AuthenticationProperties propertiesVM = CreateProperties(userVM.UserName); AuthenticationTicket ticketVM = new AuthenticationTicket(oAuthIdentityVM, propertiesVM); context.Validated(ticketVM); context.Request.Context.Authentication.SignIn(cookiesIdentityVM); } else { ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, OAuthDefaults.AuthenticationType); ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager, CookieAuthenticationDefaults.AuthenticationType); AuthenticationProperties properties = CreateProperties(user.UserName); AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties); context.Validated(ticket); context.Request.Context.Authentication.SignIn(cookiesIdentity); } } catch (Exception e) { Console.WriteLine(e); } }
public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); string wechatLoginKey = ConfigurationManager.AppSettings["wxLoginKey"]; if (string.IsNullOrWhiteSpace(wechatLoginKey)) { context.SetError("AppSettings", "Key:wxLoginKey is not found"); return(Task.FromResult <object>(null)); } var identity = new ClaimsIdentity("JWT"); if (context.Password == wechatLoginKey.Trim()) { string apiUrl = string.Format(wxLoginApi, ConfigurationManager.AppSettings["wxAppid"], ConfigurationManager.AppSettings["wxAppsercret"], context.UserName); JavaScriptSerializer js = new JavaScriptSerializer(); WechatLoginMsg msg = js.Deserialize <WechatLoginMsg>(HttpHelper.HttpGet(apiUrl)); //msg.Openid = "oqK0I0VG0jE5udoT1jIVBZOkQr3w"; //msg.Session_key = "87LCUedsESieDCbaABh/4g=="; if (!string.IsNullOrWhiteSpace(msg.Openid) && !string.IsNullOrWhiteSpace(msg.Session_key)) { using (var userAppService = IocManager.Instance.ResolveAsDisposable <IUserAppService>()) { LoginOutput output = userAppService.Object.WechatLogin(new WechatLoginInput { Openid = msg.Openid, Session_key = msg.Session_key }); identity.AddClaim(new Claim("UserId", output.UserId.ToString())); identity.AddClaim(new Claim("IsNewUser", output.IsNewUser.ToString())); if (!string.IsNullOrEmpty(output.NickName)) { identity.AddClaim(new Claim("nickname", output.NickName)); } if (!string.IsNullOrEmpty(output.UserName)) { identity.AddClaim(new Claim("username", output.UserName)); } if (!string.IsNullOrEmpty(output.UserType)) { identity.AddClaim(new Claim("usertype", output.UserType)); } } } else { context.SetError(msg.Errcode, msg.Errmsg); return(Task.FromResult <object>(null)); } } else { using (var userAppService = IocManager.Instance.ResolveAsDisposable <IUserAppService>()) { LoginOutput output = userAppService.Object.ManageLogin(new ManageLoginInput { PassWord = context.Password, UserName = context.UserName }); if (!output.UserId.HasValue) { context.SetError("invalid_grant", "The user name or password is incorrect"); return(Task.FromResult <object>(null)); } identity.AddClaim(new Claim("UserId", output.UserId.ToString())); identity.AddClaim(new Claim("IsNewUser", output.IsNewUser.ToString())); if (!string.IsNullOrEmpty(output.NickName)) { identity.AddClaim(new Claim("nickname", output.NickName)); } if (!string.IsNullOrEmpty(output.UserName)) { identity.AddClaim(new Claim("username", output.UserName)); } if (!string.IsNullOrEmpty(output.UserType)) { identity.AddClaim(new Claim("usertype", output.UserType)); } } } var props = new AuthenticationProperties(new Dictionary <string, string> { { "audience", context.ClientId ?? string.Empty } }); var ticket = new AuthenticationTicket(identity, props); context.Validated(ticket); return(Task.FromResult <object>(null)); }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { //for choi : Entity Framwork를 사용하지 않음 //if (context.UserName == "admin" && context.Password == "admin") //{ // //쿠키를 만든다. 사용자명과 User권한을 쿠키에 넣어서 보내준다. 클라이언트가 쿠키를 다시 보내주면 사용자명과 권한을 추출해 통과시킨다 // var oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType); // oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, context.UserName)); // oAuthIdentity.AddClaim(new Claim(ClaimTypes.Role, "User")); // context.Validated(oAuthIdentity); //인증 ok // var cookiesIdentity = new ClaimsIdentity(context.Options.AuthenticationType); // AuthenticationProperties properties = CreateProperties(context.UserName); // AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties); // context.Validated(ticket); // //context.Request.Context.Authentication.SignIn(cookiesIdentity); //이게 뭐하는 거지? //} // var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>(); var identity = new ClaimsIdentity(context.Options.AuthenticationType); if (context.UserName == "admin" && context.Password == "admin") { identity.AddClaim(new Claim(ClaimTypes.Role, "admin")); identity.AddClaim(new Claim("username", "admin")); identity.AddClaim(new Claim(ClaimTypes.Name, "Sourav Mondal")); context.Validated(identity); } else if (context.UserName == "user" && context.Password == "user") { identity.AddClaim(new Claim(ClaimTypes.Role, "user")); identity.AddClaim(new Claim("username", "user")); identity.AddClaim(new Claim(ClaimTypes.Name, "Suresh Sha")); context.Validated(identity); } else { context.SetError("invalid grant", "provided username and password is incorrect"); return; } var cookiesIdentity = new ClaimsIdentity(context.Options.AuthenticationType); AuthenticationProperties properties = CreateProperties(context.UserName); AuthenticationTicket ticket = new AuthenticationTicket(cookiesIdentity, properties); context.Validated(ticket); context.Request.Context.Authentication.SignIn(cookiesIdentity); //ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password); //if (user == null) //{ // context.SetError("invalid_grant", "사용자 이름 또는 암호가 잘못되었습니다."); // return; //} //ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, // OAuthDefaults.AuthenticationType); //ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager, // CookieAuthenticationDefaults.AuthenticationType); //AuthenticationProperties properties = CreateProperties(user.UserName); //AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties); //context.Validated(ticket); //context.Request.Context.Authentication.SignIn(cookiesIdentity); }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { _logger.WriteVerbose("BoM: GrantResourceOwnerCredentials"); if (string.IsNullOrEmpty(context.ClientId) == false) { Client client = context.OwinContext.Get <Client>(Constants.Owin.ClientObjectEnvironmentKey); if (client.Flow == OAuthFlow.ResourceOwner) { _logger.WriteVerbose(string.Format("Client flow matches the requested flow. flow: {0}", Enum.GetName(typeof(OAuthFlow), client.Flow))); IServiceProvider requestContainer = context.OwinContext.Environment.GetRequestContainer(); UserManager <UserEntity> userManager = requestContainer.GetService <UserManager <UserEntity> >(); UserEntity user; try { user = await userManager.FindAsync(context.UserName, context.Password); } catch (Exception ex) { _logger.WriteError(string.Format("Could not retrieve the user. username: {0}", context.UserName), ex); context.SetError(Constants.Errors.ServerError); context.Rejected(); // Return here so that we don't process further. Not ideal but needed to be done here. return; } if (user != null) { try { _logger.WriteVerbose(string.Format("User is found. userId: {0}, clientId: {1}", user.Id, client.Id)); ClaimsIdentity identity = await userManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ExternalBearer); context.Validated(identity); } catch (Exception ex) { _logger.WriteError(string.Format("The ClaimsIdentity could not be created by the UserManager. userId: {0}, username: {1}", user.Id, user.UserName), ex); context.SetError(Constants.Errors.ServerError); context.Rejected(); } } else { _logger.WriteInformation(string.Format("The resource owner credentials are invalid or resource owner does not exist. clientId: {0}, flow: {1}, username: {2}", client.Id, Enum.GetName(typeof(OAuthFlow), client.Flow), context.UserName)); context.SetError(Constants.Errors.InvalidGrant, "The resource owner credentials are invalid or resource owner does not exist."); context.Rejected(); } } else { _logger.WriteInformation(string.Format("Client is not allowed for the 'Resource Owner Password Credentials Grant'. clientId: {0}, allowedFlow: {1}", client.Id, Enum.GetName(typeof(OAuthFlow), client.Flow))); context.SetError(Constants.Errors.UnauthorizedClient, "Client is not allowed for the 'Resource Owner Password Credentials Grant'"); context.Rejected(); } } else { _logger.WriteInformation(string.Format("The clientId is not present inside the context. Headers: {0}", string.Join("; ", context.Request.Headers.Select(header => string.Concat(header.Key, ": ", header.Value)).ToArray()))); context.SetError(Constants.Errors.InvalidClient, "ClientId is not present inside the request."); context.Rejected(); } }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { try { context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); using (var db = new ApplicationDbContext()) { ApplicationUser user = null; if (!string.IsNullOrEmpty(context.UserName) && context.UserName.Contains("----")) { var data = context.UserName.Split(new string[] { "----" }, StringSplitOptions.RemoveEmptyEntries); AppAuthenticationRequest request = new AppClient.AppAuthenticationRequest(); request.Application = "NGP-R"; request.UserName = data[0]; request.SystemLoginUser = data[1]; request.SystemID = data[2]; request.IP = data[3]; request.ApplicationVersion = data[4]; request.PWD = context.Password; AppASClient client = new AppASClient(); var LDAPResult = client.AuthenticateUser(request); if (!LDAPResult.Acknowledgement.IsError) { user = userService.SyncLdapUser(data[0], context.Password, UserManager); if (user == null) { context.SetError("invalid", "The user name or password is incorrect."); return; } } else { context.SetError("invalid", LDAPResult.Acknowledgement.Description); return; } var identity = new ClaimsIdentity(context.Options.AuthenticationType); identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName)); identity.AddClaim(new Claim(ClaimTypes.WindowsAccountName, user.Id)); var usr = (from u in db.Users where u.UserName.Equals(user.UserName) select u).FirstOrDefault(); if (usr.AnalystId == null) { usr.AnalystId = 0; usr.BenchMark = 0; } var userLogin = new Models.Core.UserLogin { ApplicationUser = usr, Ip = context.OwinContext.Request.RemoteIpAddress }; db.UserLogins.Add(userLogin); db.Entry(userLogin).State = System.Data.Entity.EntityState.Added; db.SaveChanges(); context.Validated(identity); context.Response.Headers.Add("UserId", new string[] { user.Id }); } else { context.SetError("invalid", "Some fields Missed in Request"); return; } } } catch (Exception ex) { Log.Error(ex); throw; } }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { var userManager = context.OwinContext.GetUserManager <ApplicationUserManager>(); bool magicFlag = false; bool externalLoginFlag = false; bool addExternalFlag = false; string magictoken = ""; string externallogin = ""; if (context.Request.Headers["magictoken"] != null) { magictoken = context.Request.Headers["magictoken"].ToString(); } else if (context.Request.Headers["externallogin"] != null) { externallogin = context.Request.Headers["externallogin"].ToString(); } ApplicationUser user = null; if (magictoken.Trim() == "" && (externallogin == "null" || externallogin == "")) { user = await userManager.FindAsync(context.UserName, context.Password); } else { if (magictoken.Trim() != "") { magicFlag = true; if (await MagicLink(context.UserName, magictoken)) { user = await userManager.FindByEmailAsync(context.UserName); } else { addExternalFlag = true; } } else if (externallogin != "") { var authKey = externallogin.Substring(1, externallogin.Length - 1); var typeAuth = externallogin.Substring(0, 1); var userId = ""; if (context.UserName != "") { user = await userManager.FindByEmailAsync(context.UserName); if (user != null) { if (!await AddExternalLogin(typeAuth, authKey, user.Id)) { user = null; addExternalFlag = true; } } else { addExternalFlag = true; } } else { externalLoginFlag = true; userId = await ExternalLogin(authKey, userId); if (userId != "") { user = await userManager.FindByIdAsync(userId); } } } } if (user == null) { if (magicFlag) { context.SetError("invalid_grant", "The magic link is invalid or has expired"); } else if (externalLoginFlag) { context.SetError("invalid_grant", "externallogin"); } else if (addExternalFlag) { context.SetError("invalid_grant", "Invalid Associated email"); } else { context.SetError("invalid_grant", "The user name or password is incorrect."); } return; } ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, OAuthDefaults.AuthenticationType); ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager, CookieAuthenticationDefaults.AuthenticationType); AuthenticationProperties properties = CreateProperties(user.UserName); AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties); context.Validated(ticket); context.Request.Context.Authentication.SignIn(cookiesIdentity); }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { if (string.IsNullOrEmpty(context.UserName) || string.IsNullOrEmpty(context.Password)) { context.SetError("invalid_grant", "The user name or password not supplied."); return; } var extraParams = await context.Request.ReadFormAsync(); string username = extraParams["username"]; string password = extraParams["password"]; if (string.IsNullOrEmpty(username) && string.IsNullOrEmpty(password)) { context.SetError("invalid_grant", "username or password not provided."); return; } int memberId = 0; string role = "Member"; string AuthenticationType = "Authenticated"; bool isAdmin = false; string apiUrl = ""; using (NSAKLEntities asContext = new NSAKLEntities()) { string hashPassword = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(context.Password, "sha1"); try { var queryResult = ""; //var queryResult = asContext.Database.SqlQuery<List<string>>("exec spInternetUserWithTermsAccept_Validate '" + context.UserName + "','" + hashPassword + "','',''").ToList(); } catch (SqlException ex) { context.SetError("invalid_user", ex.Message); return; } catch (Exception ex) { context.SetError("invalid_user", ex.Message); return; } var internetUser = asContext.users.Where(x => x.username == context.UserName && x.password == hashPassword).FirstOrDefault(); if (internetUser == null) { context.SetError("invalid_grant", "The user name or password is incorrect."); return; } apiUrl = System.Configuration.ConfigurationManager.AppSettings["APIUrl"]; var memberinfo = asContext.members.Where(x => x.username == internetUser.username).FirstOrDefault(); if (internetUser == null) { context.SetError("invalid_grant", "The user name or password is incorrect."); return; } if (internetUser != null) { if (memberinfo != null) { memberId = memberinfo.recid; var coordinatorinfo = asContext.coordinators.Where(x => x.member_id == memberId).FirstOrDefault(); var admininfo = asContext.committees.Where(x => x.user_id == memberId).FirstOrDefault(); if (coordinatorinfo != null) { role = "Coordinator"; } if (admininfo != null) { role = "Admin"; } } if (string.IsNullOrEmpty(internetUser.username))//if interface doesnt' have IMEI and MAC, let the user log in { AuthenticationType = "UserNameBlank"; } else { AuthenticationType = "AuthenticatedValueMatch"; } } } var identity = new ClaimsIdentity(context.Options.AuthenticationType); identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName)); identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, memberId.ToString())); identity.AddClaim(new Claim(ClaimTypes.Role, role.ToString())); AuthenticationProperties properties = CreateProperties(context.UserName, AuthenticationType); AuthenticationTicket ticket = new AuthenticationTicket(identity, properties); context.Validated(ticket); }
public override async Task GrantResourceOwnerCredentials( OAuthGrantResourceOwnerCredentialsContext context) { Client client = context.OwinContext.Get <Client>("oauth:client"); if (client.AllowedGrant == OAuthGrant.ResourceOwner) { // Client flow matches the requested flow. Continue... UserManager <IdentityUser> userManager = context.OwinContext.GetUserManager <UserManager <IdentityUser> >(); IdentityUser user; try { user = await userManager.FindAsync(context.UserName, context.Password); } catch { // Could not retrieve the user. context.SetError("server_error"); context.Rejected(); // Return here so that we don't process further. Not ideal but needed to be done here. return; } if (user != null) { try { // User is found. Signal this by calling context.Validated ClaimsIdentity identity = await userManager.CreateIdentityAsync( user, DefaultAuthenticationTypes.ExternalBearer); context.Validated(identity); } catch { // The ClaimsIdentity could not be created by the UserManager. context.SetError("server_error"); context.Rejected(); } } else { // The resource owner credentials are invalid or resource owner does not exist. context.SetError( "access_denied", "The resource owner credentials are invalid or resource owner does not exist."); context.Rejected(); } } else { // Client is not allowed for the 'Resource Owner Password Credentials Grant'. context.SetError( "invalid_grant", "Client is not allowed for the 'Resource Owner Password Credentials Grant'"); context.Rejected(); } }
public override async Task GrantResourceOwnerCredentials( OAuthGrantResourceOwnerCredentialsContext context) { // Get the user credentials var username = context.UserName; var password = context.Password; if (string.IsNullOrWhiteSpace(password) || string.IsNullOrWhiteSpace(username)) { context.SetError("Unsuccessful Login", "The username or password is not correct."); return; } // Get service account credentials var serviceUsername = System.Web.Configuration.WebConfigurationManager.AppSettings["serviceUsername"]; var servicePassword = System.Web.Configuration.WebConfigurationManager.AppSettings["servicePassword"]; // Syntax like : my.server.com:8080 var ldapServer = System.Web.Configuration.WebConfigurationManager.AppSettings["ldapServer"]; /******************************* * Ldap Authentication *******************************/ try { PrincipalContext ADServiceConnection = new PrincipalContext( ContextType.Domain, ldapServer, "OU=Gordon College,DC=gordon,DC=edu", ContextOptions.Negotiate | ContextOptions.ServerBind | ContextOptions.SecureSocketLayer, serviceUsername, servicePassword); UserPrincipal userQuery = new UserPrincipal(ADServiceConnection); userQuery.SamAccountName = username; PrincipalSearcher search = new PrincipalSearcher(userQuery); UserPrincipal userEntry = (UserPrincipal)search.FindOne(); search.Dispose(); if (userEntry != null) { PrincipalContext ADUserConnection = new PrincipalContext( ContextType.Domain, ldapServer, "OU=Gordon College,DC=gordon,DC=edu" ); var areValidCredentials = ADUserConnection.ValidateCredentials( username, password, ContextOptions.SimpleBind | ContextOptions.SecureSocketLayer ); if (areValidCredentials) { var personID = userEntry.EmployeeId; // Some accounts don't have id's if (personID == null) { context.SetError("Unsuccessful Login", "The username or password is not correct."); return; } IUnitOfWork unitOfWork = new UnitOfWork(); var adminService = new AdministratorService(unitOfWork); var accountService = new AccountService(unitOfWork); var distinguishedName = userEntry.DistinguishedName; var readOnly = accountService.Get(personID).ReadOnly; var collegeRole = string.Empty; if (readOnly == 1) { collegeRole = Position.READONLY; } else if (distinguishedName.Contains("OU=Students")) { collegeRole = Position.STUDENT; } else { collegeRole = Position.FACSTAFF; } try { // This get operation is by gordon_id // Throws an exception if not found. var unit = new UnitOfWork(); bool isPolice = unit.AccountRepository.FirstOrDefault(x => x.gordon_id == personID).is_police == 1; if (isPolice) { collegeRole = Position.POLICE; } } catch (ResourceNotFoundException e) { // Silent catch. // This is ok because we know this exception means the user is not an admin } try { // This get operation is by gordon_id // Throws an exception if not found. var isAdmin = adminService.Get(personID); if (isAdmin != null) { collegeRole = Position.GOD; } } catch (ResourceNotFoundException e) { // Silent catch. // This is ok because we know this exception means the user is not an admin } var identity = new ClaimsIdentity(context.Options.AuthenticationType); identity.AddClaim(new Claim("name", userEntry.Name)); identity.AddClaim(new Claim("id", personID)); identity.AddClaim(new Claim("college_role", collegeRole)); identity.AddClaim(new Claim("user_name", username)); ADServiceConnection.Dispose(); context.Validated(identity); } else { ADServiceConnection.Dispose(); context.SetError("Unsuccessful Login", "The username or password is not correct"); } } else { Debug.WriteLine("\n\nNOT FOUND\n\n"); context.SetError("Unsuccessful Login", "The username or password is not correct"); } } catch (Exception e) { Debug.WriteLine("Exception caught: " + e.ToString()); context.SetError("connection_error", "There was a problem connecting to the authorization server."); } }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { var identity = new ClaimsIdentity(context.Options.AuthenticationType); string UserTypeID = context.OwinContext.Get <string>("UserTypeID"); Login loginsetdetails = new Login(); loginsetdetails.UserName = context.UserName; loginsetdetails.UserPassword = context.Password; loginsetdetails.UserTypeID = Convert.ToInt32(context.OwinContext.Get <string>("UserTypeID")); //Login logingetdetails = _iBAccount.GetUserDetails(loginsetdetails); Login logingetdetails = DataAccessLayer.DAccount.GetUserDetails1(loginsetdetails); // var currentUserRole = "Admin"; if (logingetdetails != null) { var currentUserRole = logingetdetails.UserType; identity.AddClaim(new Claim("Role", currentUserRole)); var props = new AuthenticationProperties(new Dictionary <string, string> { { "DisplayName", context.UserName }, { "Role", currentUserRole }, { "UserID", logingetdetails.UserID.ToString() }, { "FirstName", logingetdetails.FirstName }, { "LastName", logingetdetails.LastName }, { "MobileNo", logingetdetails.MobileNo } }); var token = new AuthenticationTicket(identity, props); context.Validated(token); } else if (context.UserName == "student") { if (context.Password == "student") { var currentUserRole = "Student"; identity.AddClaim(new Claim("Role", currentUserRole)); var props = new AuthenticationProperties(new Dictionary <string, string> { { "DisplayName", context.UserName }, { "Role", currentUserRole } }); var token = new AuthenticationTicket(identity, props); context.Validated(token); } } else if (context.UserName == "superadmin") { if (context.Password == "superadmin") { var currentUserRole = "SuperAdmin"; identity.AddClaim(new Claim("Role", currentUserRole)); var props = new AuthenticationProperties(new Dictionary <string, string> { { "DisplayName", context.UserName }, { "Role", currentUserRole } }); var token = new AuthenticationTicket(identity, props); context.Validated(token); } } else { context.SetError("invalid_grant", "The username or password is incorrect."); } // context.Response.Headers.Add("AuthorizationResponse",new[]{"Failed"}); return; }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { if (String.IsNullOrWhiteSpace(AccessControlAllowOrigin)) { AccessControlAllowOrigin = "*"; } // If i want to obtain other values from the request, i can do that here. // For example, to get an email/username and a pin, instead of password. // Or i can just use those fields as they are.....i like this idea. //context.Request.ReadFormAsync context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { AccessControlAllowOrigin }); context.OwinContext.Response.Headers.Add("Access-Control-Allow-Methods", new[] { "GET, POST, PUT, DELETE, OPTIONS" }); var dbUser = await UserManager.FindAsync(context.UserName, context.Password); if (dbUser == null) { context.SetError("invalid_grant", "The user name or password is incorrect."); context.Response.StatusCode = (int)HttpStatusCode.Unauthorized; if (UserManager.SupportsUserLockout) //ABCxyz { var user = await UserManager.FindByNameAsync(context.UserName); if (user != null) { await UserManager.AccessFailedAsync(user.Id); // I am not supporting this feature anyway at the moment. Maybe i should??? } } return; } if (UserManager.SupportsUserEmail) { var emailConfirmed = await UserManager.IsEmailConfirmedAsync(dbUser.Id); if (emailConfirmed == false) { context.SetError("invalid_grant", "Email has not been confirmed"); return; } } //UserContext.UserCanLogIn abcxyz var userCanLogIn = await UserManager.UserCanLogIn(dbUser.Id); if (!userCanLogIn) { context.SetError("invalid_grant", "User is not allowed to log in."); return; } var identity = await UserManager.CreateIdentityAsync(dbUser, context.Options.AuthenticationType); 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(identity, props); context.Validated(ticket); }
/// <summary> /// Realiza a autenticação do usuário /// </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>(); authenticateResult = new AuthenticateResult { IsAuthenticated = false, Username = context.UserName }; if (!ApplicationUserManager.AuthenticateTypeIsSet()) { authenticateResult.IsAuthenticated = false; authenticateResult.MessageCode = "alerts:error.authentication_type_not_set"; authenticateResult.MessageDescription = "Authentication not set(see General Settings)"; } else { var user = await userManager.FindUserAsync(context.UserName); authenticateResult = CheckUser(user, context.UserName, SettingHelper.Get()); if (authenticateResult.CheckUserIsOk && user.AuthenticationType == AuthenticationType.DataBase) { var signInManager = context.OwinContext.Get <ApplicationSignInManager>(); var result = await AuthenticateDataBaseAsync(signInManager, user.UserName, context.Password); authenticateResult = CheckAuthenticatedInDataBase(user, authenticateResult, result); if (authenticateResult.IsAuthenticated) { await userManager.ResetAccessFailedCountAsync(user.Id); // Zerando contador de logins errados. } } else if (authenticateResult.CheckUserIsOk && user.AuthenticationType == AuthenticationType.ActiveDirectory) { authenticateResult.IsAuthenticated = AuthenticateActiveDirectory(context.UserName, context.Password); if (!authenticateResult.IsAuthenticated) { authenticateResult.MessageCode = "alerts:error.invalid_grant"; authenticateResult.MessageDescription = "The user name or password is incorrect."; } } if (authenticateResult.IsAuthenticated) { authenticateResult.Username = user.UserName; var oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, OAuthDefaults.AuthenticationType); var cookiesIdentity = await user.GenerateUserIdentityAsync(userManager, CookieAuthenticationDefaults.AuthenticationType); AddCustomClaims(oAuthIdentity, user); var properties = CreateProperties(user.UserName, context.ClientId); var ticket = new AuthenticationTicket(oAuthIdentity, properties); context.Validated(ticket); context.Request.Context.Authentication.SignIn(cookiesIdentity); } } SaveAccessLog(authenticateResult); if (!authenticateResult.IsAuthenticated) { context.SetError(authenticateResult.MessageCode, authenticateResult.MessageDescription); } }
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 }); ApplicationUser user = new ApplicationUser(); var userRoles = new List <string>(); var isAdmin = "false"; using (AuthRepository _repo = new AuthRepository()) { user = await _repo.FindUser(context.UserName, context.Password); if (user == null) { user = await _repo.FindByEmailAsync(context.UserName); } if (user != null) { user = await _repo.FindUser(user.UserName, context.Password); } if (user == null) { context.SetError("invalid_grant", "The user name or password is incorrect."); return; } userRoles = _repo.GetUserRoles(user.Id); isAdmin = userRoles.Contains("Admin") ? "true" : "false"; } var identity = new ClaimsIdentity(context.Options.AuthenticationType); identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName)); if (userRoles.Count > 0) { foreach (var role in userRoles) { identity.AddClaim(new Claim(ClaimTypes.Role, role)); } } else { identity.AddClaim(new Claim(ClaimTypes.Role, "user")); } identity.AddClaim(new Claim("sub", context.UserName)); var props = new AuthenticationProperties(new Dictionary <string, string> { { "as:client_id", (context.ClientId == null) ? string.Empty : context.ClientId }, { "id", user.Id }, { "userName", context.UserName }, { "fullName", user.FullName }, { "isAdmin", isAdmin }, { "address", user.Address ?? string.Empty }, { "email", user.Email ?? string.Empty }, { "phoneNumber", user.PhoneNumber ?? string.Empty }, { "role", userRoles[0] }, }); var ticket = new AuthenticationTicket(identity, props); context.Validated(ticket); }
private static async Task <Account> GrantLocalUser(OAuthGrantResourceOwnerCredentialsContext context, AuthRepository auth) { var user = await GrantResourceOwnerCredentialsToken(context, auth); if (!object.Equals(user, null)) { return(user); } user = user ?? await auth.AccountGetAsync(context.UserName); if (!object.Equals(user, null) && user.IsEmptyPassword()) { if (context.OwinContext.Get <ExternalClient?>("externalClient").HasValue) { return(user); } var sessionTokensExternalHistory = await auth.SessionTokenExternalHistoriesAsync(user.Id); var sessionTokenExternalHistory = sessionTokensExternalHistory.FirstOrDefault(e => !e.IsUnlinked); if (!object.Equals(sessionTokenExternalHistory, null)) { context.SetError("invalid_grant", string.Format("You should sign in with {0}.", sessionTokenExternalHistory.ExternalClientName)); return(null); } if (!string.IsNullOrEmpty(user.Email)) { context.Response.Headers.Add("User-Email", new string[] { user.Email }); } if (!string.IsNullOrEmpty(user.FirstName)) { context.Response.Headers.Add("User-FirstName", new string[] { user.FirstName }); } if (!string.IsNullOrEmpty(user.LastName)) { context.Response.Headers.Add("User-LastName", new string[] { user.LastName }); } context.SetError("invalid_grant", "You should create an account."); return(null); } if (object.Equals(user, null)) { user = await auth.AccountGetAsync(context.UserName, isIncludeSubEmails : true); if (!object.Equals(user, null)) { context.SetError("invalid_grant", string.Format("You cannot sign in with this email as it is no longer associated with your account.", context.UserName)); return(null); } } if (!object.Equals(user, null) && (auth.PasswordIsEqual(user.Password, context.Password) || string.Equals(user.Password, context.Password, StringComparison.InvariantCultureIgnoreCase))) { return(user); } context.SetError("invalid_grant", "The email or password is incorrect."); return(null); }
private void SetContextError(OAuthGrantResourceOwnerCredentialsContext context, string errorCode, string message) { context.SetError((errorCode).ToString(CultureInfo.InvariantCulture), message); }