public async override Task GrantResourceOwnerCredentials(GrantResourceOwnerCredentialsContext context) { var userManager = context .HttpContext .RequestServices .GetRequiredService<UserManager<ApplicationUser>>(); var user = await userManager.FindByNameAsync(context.UserName); if (!await userManager.CheckPasswordAsync(user, context.Password)) { context.Rejected(OpenIdConnectConstants.Errors.InvalidGrant, "Invalid username or password"); return; } var identity = new ClaimsIdentity(OpenIdConnectServerDefaults.AuthenticationScheme); // this automatically goes into the token and id_token identity.AddClaim(ClaimTypes.NameIdentifier, user.UserName); // the other claims require explicit destinations identity.AddClaim(ClaimTypes.Name, user.FirstName, "token id_token"); identity.AddClaim(ClaimTypes.Surname, user.LastName, "token id_token"); var principal = new ClaimsPrincipal(identity); context.Validated(principal); }
public override Task GrantResourceOwnerCredentials( GrantResourceOwnerCredentialsContext context) { // Validate the credentials here (e.g using ASP.NET Identity). // You can call Reject() with an error code/description to reject // the request and return a message to the caller. var identity = new ClaimsIdentity(context.Options.AuthenticationScheme); identity.AddClaim(ClaimTypes.NameIdentifier, "[unique identifier]"); // By default, claims are not serialized in the access and identity tokens. // Use the overload taking a "destinations" parameter to make sure // your claims are correctly serialized in the appropriate tokens. identity.AddClaim("urn:customclaim", "value", OpenIdConnectConstants.Destinations.AccessToken, OpenIdConnectConstants.Destinations.IdentityToken); var ticket = new AuthenticationTicket( new ClaimsPrincipal(identity), new AuthenticationProperties(), context.Options.AuthenticationScheme); // Call SetResources with the list of resource servers // the access token should be issued for. ticket.SetResources("resource_server_1"); // Call SetScopes with the list of scopes you want to grant // (specify offline_access to issue a refresh token). ticket.SetScopes("profile", "offline_access"); context.Validate(ticket); return(Task.FromResult(0)); }
/// <summary> /// Set cross-origin HTTP request (Cors) header to allow requests from a different domains. /// This Cors value is specific to an Application and set by when validating the client application (ValidateClientAuthenticationp). /// </summary> private static void SetCorsHeader(GrantResourceOwnerCredentialsContext context) { var allowedOrigin = context.HttpContext.Items["as:clientAllowedOrigin"] as string; if (allowedOrigin != null) { context.HttpContext.Response.Headers.Add("Access-Control-Allow-Origin", new StringValues(allowedOrigin)); } }
public override Task GrantResourceOwnerCredentials(GrantResourceOwnerCredentialsContext context) { string username = context.UserName; string password = context.Password; UserManager <ApplicationUser> userManager = context.HttpContext.RequestServices.GetRequiredService <UserManager <ApplicationUser> >(); ApplicationUser user = userManager.FindByNameAsync(username).Result; if (userManager.CheckPasswordAsync(user, password).Result) { ClaimsIdentity identity = new ClaimsIdentity(OpenIdConnectServerDefaults.AuthenticationScheme); identity.AddClaim(ClaimTypes.Name, user.UserName, OpenIdConnectConstants.Destinations.AccessToken, OpenIdConnectConstants.Destinations.IdentityToken); List <string> roles = userManager.GetRolesAsync(user).Result.ToList(); foreach (string role in roles) { identity.AddClaim(ClaimTypes.Role, role, OpenIdConnectConstants.Destinations.AccessToken, OpenIdConnectConstants.Destinations.IdentityToken); } AuthenticationTicket ticket = new AuthenticationTicket( new ClaimsPrincipal(identity), new AuthenticationProperties(), context.Options.AuthenticationScheme); ticket.SetResources("resource_server"); List <string> scopes = new List <string>(); if (context.Request.HasScope("offline_access")) { scopes.Add("offline_access"); } ticket.SetScopes(scopes); if (string.IsNullOrWhiteSpace(context.Request.Resource)) { _logger.LogDebug("setting default audience for ticket...."); } context.Validate(ticket); } else { context.Reject("invalid credentials"); } return(Task.FromResult(0)); }
public override Task GrantResourceOwnerCredentials( GrantResourceOwnerCredentialsContext context) { var identity = new ClaimsIdentity(OpenIdConnectServerDefaults.AuthenticationScheme); identity.AddClaim(ClaimTypes.NameIdentifier, "todo"); // By default, claims are not serialized in the access and identity tokens. // Use the overload taking a "destination" to make sure your claims // are correctly inserted in the appropriate tokens. identity.AddClaim("urn:customclaim", "value", "token id_token"); var principal = new ClaimsPrincipal(identity); context.Validated(principal); return(Task.FromResult <object>(null)); }
/// <summary> /// Validates the userName and password provided by the user. /// </summary> public override async Task GrantResourceOwnerCredentials(GrantResourceOwnerCredentialsContext context) { var query = new UserNamePasswordLogin(context.UserName, context.Password); var result = await ExecuteMessage(context, query); if (!result.Succeeded) { context.Reject("invalid_grant", "The user name or password is incorrect."); return; } SetCorsHeader(context); var ticket = CreateAuthenticationTicket(result, context); context.Validate(ticket); }
public override Task GrantResourceOwnerCredentials(GrantResourceOwnerCredentialsContext context) { var user = new { Id = "users-123", UserName = "******", Password = "******" }; if (context.UserName != user.UserName || context.Password != user.Password) { context.Rejected("Invalid username or password."); return Task.FromResult(0); } var identity = new ClaimsIdentity(OpenIdConnectDefaults.AuthenticationScheme); identity.AddClaim(ClaimTypes.NameIdentifier, user.Id, "id_token token"); identity.AddClaim(ClaimTypes.Name, user.UserName, "id_token token"); context.Validated(new ClaimsPrincipal(identity)); return Task.FromResult(0); }
public override Task GrantResourceOwnerCredentials(GrantResourceOwnerCredentialsContext context) { var user = us.IsValidUser(context.UserName, context.Password); if(user!= null) { // Validate the credentials here (e.g using ASP.NET Identity). // You can call Rejected() with an error code/description to reject // the request and return a message to the caller. VMUser vu = new VMUser(user); var identity = new ClaimsIdentity(OpenIdConnectServerDefaults.AuthenticationScheme); identity.AddClaim(ClaimTypes.NameIdentifier, user.username, "token id_token"); identity.AddClaim("profile", JsonConvert.SerializeObject(vu), "token id_token"); // By default, claims are not serialized in the access and identity tokens. // Use the overload taking a "destination" to make sure your claims // are correctly inserted in the appropriate tokens. // identity.AddClaim("urn:customclaim", "value", "token id_token"); var ticket = new AuthenticationTicket( new ClaimsPrincipal(identity), new AuthenticationProperties(), context.Options.AuthenticationScheme); // Call SetResources with the list of resource servers // the access token should be issued for. ticket.SetResources(new[] { "api" }); // Call SetScopes with the list of scopes you want to grant // (specify offline_access to issue a refresh token). ticket.SetScopes(new[] {"api" }); context.Validated(ticket); } else { context.Rejected(); } return Task.FromResult<object>(null); }
public override async Task GrantClientCredentialsAsync(GrantResourceOwnerCredentialsContext context) { var form = context.Request.Form; var clientId = form.First(c => c.Key.Equals("client_id")).Value; if (string.IsNullOrEmpty(clientId)) { context.SetError("ErrorCode:001 - The client_id is not set"); return; } var client = AppClientsStore.FindClient(clientId); if (client == null) { context.SetError("ErrorCode:002 - The client_id is incorrect"); return; } var authVerifyCallback = await _mediator.Send(new AuthenticationUser.Query() { Email = context.UserName, Password = context.Password }); if (authVerifyCallback.IsFailure) { context.SetError("ErrorCode:003 - Invalid user authentication"); return; } var user = authVerifyCallback.Success; var claims = new List <Claim> { new Claim("UserId", user.Id.ToString()), new Claim(ClaimTypes.Email, user.Email), new Claim(ClaimTypes.Name, user.Name), new Claim("aud", clientId), }; context.Validated(claims); await Task.FromResult(0); }
public async Task InvokeAsync(HttpContext context, IJwtSecurityTokenService iJwtSecurityTokenService) { var grantResourceOwnerCredentialsContext = GrantResourceOwnerCredentialsContext.Create(context); if (grantResourceOwnerCredentialsContext != null) { await jwtServerOptions.AuthorizationServerProvider.GrantClientCredentialsAsync(grantResourceOwnerCredentialsContext); if (grantResourceOwnerCredentialsContext.IsValidated) { var token = iJwtSecurityTokenService.Create(grantResourceOwnerCredentialsContext, jwtServerOptions); await WriteResponseAsync(context, JsonConvert.SerializeObject(token)); } else { await WriteResponseError(context, grantResourceOwnerCredentialsContext.Error); } } }
public override Task GrantResourceOwnerCredentials( GrantResourceOwnerCredentialsContext context) { // Validate the credentials here (e.g using ASP.NET Identity). // You can call Rejected() with an error code/description to reject // the request and return a message to the caller. var identity = new ClaimsIdentity(OpenIdConnectServerDefaults.AuthenticationScheme); identity.AddClaim(ClaimTypes.NameIdentifier, "todo"); // By default, claims are not serialized in the access and identity tokens. // Use the overload taking a "destination" to make sure your claims // are correctly inserted in the appropriate tokens. identity.AddClaim("urn:customclaim", "value", "token id_token"); var principal = new ClaimsPrincipal(identity); context.Validated(principal); return(Task.FromResult <object>(null)); }
public async Task InvokeAsync(HttpContext context, IJwtSecurityTokenService iJwtSecurityTokenService) { var baseValidatingContext = default(BaseValidatingContext); var grantType = this.GetGrantType(context); switch (grantType) { case Parameters.Password: baseValidatingContext = GrantResourceOwnerCredentialsContext.Create(context); if (baseValidatingContext != null) { await jwtServerOptions.AuthorizationServerProvider.GrantClientCredentialsAsync ((GrantResourceOwnerCredentialsContext)baseValidatingContext); } break; case Parameters.RefreshToken: baseValidatingContext = GrantRefreshTokenContext.Create(context); if (baseValidatingContext != null) { await jwtServerOptions.AuthorizationServerProvider.GrantRefreshTokenAsync ((GrantRefreshTokenContext)baseValidatingContext); } break; default: break; } if (baseValidatingContext != null) { if (baseValidatingContext.IsValidated) { var token = await iJwtSecurityTokenService.CreateAsync(baseValidatingContext, jwtServerOptions); await WriteResponseAsync(context, JsonConvert.SerializeObject(token)); } else { await WriteResponseError(context, baseValidatingContext.Error); } } }
public override Task GrantResourceOwnerCredentials(GrantResourceOwnerCredentialsContext context) { var user = new { Id = "users-123", UserName = "******", Password = "******" }; if (context.UserName != user.UserName || context.Password != user.Password) { context.Rejected("Invalid username or password."); return(Task.FromResult(0)); } var identity = new ClaimsIdentity(OpenIdConnectDefaults.AuthenticationScheme); identity.AddClaim(ClaimTypes.NameIdentifier, user.Id, "id_token token"); identity.AddClaim(ClaimTypes.Name, user.UserName, "id_token token"); context.Validated(new ClaimsPrincipal(identity)); return(Task.FromResult(0)); }
public override async Task GrantResourceOwnerCredentials(GrantResourceOwnerCredentialsContext context) { // Don't inject the UserManager to avoid save a reference for the application lifetime // Internally manages an EF DbContext var userManager = context.HttpContext.RequestServices.GetRequiredService <UserManager <ApplicationUser> >(); bool isValidUser = false; var user = await userManager.FindByNameAsync(context.UserName); if (user != null) { isValidUser = await userManager.CheckPasswordAsync(user, context.Password); } if (isValidUser) { var claims = new List <Claim> { new Claim(ClaimTypes.NameIdentifier, user.UserName), new Claim(ClaimTypes.Email, user.Email), new Claim(ClaimTypes.GivenName, user.FullName), }; claims.AddRange(context.Scope.Select(scope => new Claim("scope", scope))); var claimsPrincipal = new ClaimsPrincipal( new ClaimsIdentity(claims, OpenIdConnectServerDefaults.AuthenticationScheme)); var ticket = new AuthenticationTicket( claimsPrincipal, new AuthenticationProperties(), OpenIdConnectServerDefaults.AuthenticationScheme); context.Validated(ticket); } else { context.Rejected(); } }
/// <summary> /// Called when a request to the Token endpoint arrives with a "grant_type" of "password". This occurs when the user has provided name and password /// credentials directly into the client application's user interface, and the client application is using those to acquire an "access_token" and /// optional "refresh_token". If the web application supports the /// resource owner credentials grant type it must validate the context.Username and context.Password as appropriate. To issue an /// access token the context.Validated must be called with a new ticket containing the claims about the resource owner which should be associated /// with the access token. The application should take appropriate measures to ensure that the endpoint isn't abused by malicious callers. /// The default behavior is to reject this grant type. /// See also http://tools.ietf.org/html/rfc6749#section-4.3.2 /// </summary> /// <param name="context">The context of the event carries information in and results out.</param> /// <returns>Task to enable asynchronous execution</returns> public virtual Task GrantResourceOwnerCredentials(GrantResourceOwnerCredentialsContext context) => OnGrantResourceOwnerCredentials(context);
public override async Task GrantResourceOwnerCredentials([NotNull] GrantResourceOwnerCredentialsContext context) { var services = context.HttpContext.RequestServices.GetRequiredService <OpenIddictServices <TUser, TApplication> >(); var user = await services.Users.FindByNameAsync(context.UserName); if (user == null) { context.Reject( error: OpenIdConnectConstants.Errors.InvalidGrant, description: "Invalid credentials."); return; } // Ensure the user is allowed to sign in. if (!await services.SignIn.CanSignInAsync(user)) { context.Reject( error: OpenIdConnectConstants.Errors.InvalidGrant, description: "The user is not allowed to sign in."); return; } // Ensure the user is not already locked out. if (services.Users.SupportsUserLockout && await services.Users.IsLockedOutAsync(user)) { context.Reject( error: OpenIdConnectConstants.Errors.InvalidGrant, description: "Account locked out."); return; } // Ensure the password is valid. if (!await services.Users.CheckPasswordAsync(user, context.Password)) { context.Reject( error: OpenIdConnectConstants.Errors.InvalidGrant, description: "Invalid credentials."); if (services.Users.SupportsUserLockout) { await services.Users.AccessFailedAsync(user); // Ensure the user is not locked out. if (await services.Users.IsLockedOutAsync(user)) { context.Reject( error: OpenIdConnectConstants.Errors.InvalidGrant, description: "Account locked out."); } } return; } if (services.Users.SupportsUserLockout) { await services.Users.ResetAccessFailedCountAsync(user); } // Reject the token request if two-factor authentication has been enabled by the user. if (services.Users.SupportsUserTwoFactor && await services.Users.GetTwoFactorEnabledAsync(user)) { context.Reject( error: OpenIdConnectConstants.Errors.InvalidGrant, description: "Two-factor authentication is required for this account."); return; } // Return an error if the username corresponds to the registered // email address and if the "email" scope has not been requested. if (context.Request.HasScope(OpenIdConnectConstants.Scopes.Profile) && !context.Request.HasScope(OpenIdConnectConstants.Scopes.Email) && string.Equals(await services.Users.GetUserNameAsync(user), await services.Users.GetEmailAsync(user), StringComparison.OrdinalIgnoreCase)) { context.Reject( error: OpenIdConnectConstants.Errors.InvalidRequest, description: "The 'email' scope is required."); return; } var identity = await services.Applications.CreateIdentityAsync(user, context.Request.GetScopes()); Debug.Assert(identity != null); // Create a new authentication ticket holding the user identity. var ticket = new AuthenticationTicket( new ClaimsPrincipal(identity), new AuthenticationProperties(), context.Options.AuthenticationScheme); ticket.SetResources(context.Request.GetResources()); ticket.SetScopes(context.Request.GetScopes()); context.Validate(ticket); }
public virtual Task GrantClientCredentialsAsync(GrantResourceOwnerCredentialsContext context) { return(this.OnGrantResourceOwnerCredentialsAsync.Invoke(context)); }
/// <summary> /// Creates a valid authentication token used to create the access_token. /// </summary> private static AuthenticationTicket CreateAuthenticationTicket(LoginResult result, GrantResourceOwnerCredentialsContext context) { var identity = new ClaimsIdentity(context.Options.AuthenticationScheme); identity.AddClaim(ClaimTypes.Name, result.UserName, OpenIdConnectConstants.Destinations.AccessToken, OpenIdConnectConstants.Destinations.IdentityToken); identity.AddClaim(ClaimTypes.NameIdentifier, result.UserId.ToString(), OpenIdConnectConstants.Destinations.AccessToken, OpenIdConnectConstants.Destinations.IdentityToken); var properties = new AuthenticationProperties(); var principal = new ClaimsPrincipal(new[] { identity }); return(CreateAuthenticationTicket(principal, properties, context.Options, context)); }
public Task GrantResourceOwnerCredentials(GrantResourceOwnerCredentialsContext context) => OnGrantResourceOwnerCredentials(context);
public async override Task GrantResourceOwnerCredentials( GrantResourceOwnerCredentialsContext context) { _authService = (IAuthService)context.HttpContext.RequestServices.GetService(typeof(IAuthService)); Client client = _authService.FindClient(context.ClientId); string allowedOrigin = string.Empty; allowedOrigin = client.AllowedOrigin == null ? "*" : client.AllowedOrigin; //comentado pois está dando conflito com cors adicionado anteriormente //context.HttpContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin }); var user = await _authService.GetUsuarioEmail(context.UserName); var valid = await _authService.CheckPasswordAsync(user, context.Password); if (valid) { int casaId = await _authService.GetCasaSelecionada(user); //verifica se usuario esta bloqueado para aquela casa if (_authService.AcessoUsuarioBloqueado(user.Id, casaId)) { //tenta obter acesso em outra casa int novaCasaSelec = _authService.TentaSelecOutraCasa(user.Id, casaId); if (novaCasaSelec == 0) { context.Reject("O seu acesso foi bloqueado"); return; } casaId = novaCasaSelec; } var identity = new ClaimsIdentity(OpenIdConnectServerDefaults.AuthenticationScheme); foreach (var claim in _authService.GetClaims(user, casaId)) { identity.AddClaim(claim.Type, claim.Value, "access_token", "id_token"); } identity.AddClaim("casa", casaId.ToString(), "access_token", "id_token"); identity.AddClaim(ClaimTypes.NameIdentifier, user.Id, "access_token", "id_token"); identity.AddClaim(ClaimTypes.Name, user.UserName, "access_token", "id_token"); var principal = new ClaimsPrincipal(identity); var props = new AuthenticationProperties(new Dictionary <string, string> { { "client_id", (context.ClientId == null) ? string.Empty : context.ClientId }, { "userName", context.UserName } }); var ticket = new AuthenticationTicket(principal, props, OpenIdConnectServerDefaults.AuthenticationScheme); List <string> scopes = new List <string>(); if (context.Request.HasScope("offline_access")) { scopes.Add("offline_access"); } ticket.SetScopes(scopes); context.Validate(ticket); } }