Beispiel #1
0
        public override async Task HandleTokenRequest(HandleTokenRequestContext context)
        {
            if (!context.Request.IsPasswordGrantType())
            {
                context.Reject(OpenIdConnectConstants.Errors.UnsupportedGrantType,
                               "Only password grants are accepted by this server");
                return;
            }

            User existUser = await _userRepository.GetUser(context.Request.Username, context.Request.Password);

            if (existUser == null)
            {
                context.Reject(error: OpenIdConnectConstants.Errors.AccessDenied,
                               description: "Invalid user credentials.");
                return;
            }

            var identity = new ClaimsIdentity(context.Scheme.Name, OpenIdConnectConstants.Claims.Name,
                                              OpenIdConnectConstants.Claims.Role);

            identity.AddClaim(OpenIdConnectConstants.Claims.Subject, context.Request.Username);
            identity.AddClaim("urn:customclaim", "value", OpenIdConnectConstants.Destinations.AccessToken,
                              OpenIdConnectConstants.Destinations.IdentityToken);
            var ticket = new AuthenticationTicket(new ClaimsPrincipal(identity), new AuthenticationProperties(),
                                                  context.Scheme.Name);

            ticket.SetScopes(OpenIdConnectConstants.Scopes.Profile);
            context.Validate(ticket);
        }
Beispiel #2
0
        public override Task HandleTokenRequest(HandleTokenRequestContext context)
        {
            // Only handle grant_type=password token requests and let the
            // OpenID Connect server middleware handle the other grant types.
            if (context.Request.IsPasswordGrantType())
            {
                var user = new { Id = "users-123", UserName = "******", Password = "******" };

                if (!string.Equals(context.Request.Username, user.UserName, StringComparison.Ordinal) ||
                    !string.Equals(context.Request.Password, user.Password, StringComparison.Ordinal))
                {
                    context.Reject(
                        error: OpenIdConnectConstants.Errors.InvalidGrant,
                        description: "Invalid username or password.");

                    return(Task.FromResult(0));
                }

                var identity = new ClaimsIdentity(context.Options.AuthenticationScheme);

                identity.AddClaim(ClaimTypes.NameIdentifier, user.Id,
                                  OpenIdConnectConstants.Destinations.AccessToken,
                                  OpenIdConnectConstants.Destinations.IdentityToken);

                identity.AddClaim(ClaimTypes.Name, user.UserName,
                                  OpenIdConnectConstants.Destinations.AccessToken,
                                  OpenIdConnectConstants.Destinations.IdentityToken);

                context.Validate(new ClaimsPrincipal(identity));
            }

            return(Task.FromResult(0));
        }
Beispiel #3
0
        public override Task HandleTokenRequest(HandleTokenRequestContext context)
        {
            if (context.Request.IsPasswordGrantType())
            {
                // make db query here
                var user = new { Id = "users-123", Email = "*****@*****.**", Password = "******" };

                if (!string.Equals(context.Request.Username, user.Email, StringComparison.Ordinal) ||
                    !string.Equals(context.Request.Password, user.Password, StringComparison.Ordinal))
                {
                    context.Reject(
                        error: OpenIdConnectConstants.Errors.InvalidGrant,
                        description: "Invalid username or password.");

                    return(Task.FromResult(0));
                }

                var identity = new ClaimsIdentity(context.Options.AuthenticationScheme);
                identity.AddClaim(ClaimTypes.NameIdentifier, user.Id, OpenIdConnectConstants.Destinations.AccessToken, OpenIdConnectConstants.Destinations.IdentityToken);
                identity.AddClaim(ClaimTypes.Name, user.Email, OpenIdConnectConstants.Destinations.AccessToken, OpenIdConnectConstants.Destinations.IdentityToken);

                context.Validate(new ClaimsPrincipal(identity));
            }


            return(Task.FromResult(0));
        }
Beispiel #4
0
        public override Task HandleTokenRequest(HandleTokenRequestContext context)
        {
            if (userStore.ValidateUserSecret(context.Request.Username, context.Request.Password))
            {
                var user = userStore.Get(context.Request.Username);

                var identity = new ClaimsIdentity(OpenIdConnectConstants.Schemes.Bearer);
                // Note: the subject claim is always included in both identity and
                // access tokens, even if an explicit destination is not specified
                identity.AddClaim(OpenIdConnectConstants.Claims.Subject, user.Id.ToString());
                // When adding custom claims, you MUST specify one or more destinations.
                identity.AddClaim(ClaimTypes.Name, user.Name, OpenIdConnectConstants.Destinations.AccessToken);

                var principal = new ClaimsPrincipal(identity);

                var ticket = new AuthenticationTicket(principal, OpenIdConnectConstants.Schemes.Bearer);
                //ticket.SetScopes(
                //    // access reresh token
                //    OpenIdConnectConstants.Scopes.OfflineAccess,
                //    // access identity token
                //    OpenIdConnectConstants.Scopes.OpenId);

                context.Validate(ticket);
            }
            else
            {
                context.Reject(OpenIdConnectConstants.Errors.InvalidGrant);
            }

            return(Task.CompletedTask);
        }
 //
 // Summary:
 //     Represents an event called for each validated token request to allow the user
 //     code to decide how the request should be handled.
 //
 // Parameters:
 //   context:
 //     The context instance associated with this event.
 //
 // Returns:
 //     A System.Threading.Tasks.Task that can be used to monitor the asynchronous operation.
 public override Task HandleTokenRequest(HandleTokenRequestContext context)
 {
     try
     {
         // Only handle grant_type=password token requests and let the
         // OpenID Connect server middleware handle the other grant types.
         if (context.Request.IsPasswordGrantType())
         {
             return(HandleUserAuthentication(context));
         }
         else if (context.Request.IsRefreshTokenGrantType())
         {
             return(HandleRefreshTokenRequest(context));
         }
         else if (context.Request.IsClientCredentialsGrantType())
         {
             return(HandleClientCredentialsAuthentication(context));
         }
     }
     catch (Exception ex)
     {
         context.Reject(
             error: $"{ex.HResult}",
             description: ex.Message);
     }
     return(Task.CompletedTask);
 }
        public override async Task HandleTokenRequest(HandleTokenRequestContext context)
        {
            if (context.Request.IsPasswordGrantType())
            {
                var username = context.Request.Username.ToLowerInvariant();
                var user     = await _userService.GetUserLoginDtoAsync(
                    // filter
                    u => u.UserName == username
                    );

                if (user == null)
                {
                    context.Reject(
                        error: OpenIdConnectConstants.Errors.InvalidGrant,
                        description: "Invalid username or password.");
                    return;
                }
                var password = context.Request.Password;

                var passWordCheckResult = await _userService.CheckUserPasswordAsync(user, context.Request.Password);


                if (!passWordCheckResult)
                {
                    context.Reject(
                        error: OpenIdConnectConstants.Errors.InvalidGrant,
                        description: "Invalid username or password.");
                    return;
                }

                var roles = await _userService.GetUserRolesAsync(user);

                if (!roles.Any())
                {
                    context.Reject(
                        error: OpenIdConnectConstants.Errors.InvalidRequest,
                        description: "Invalid user configuration.");
                    return;
                }
                // add the claims
                var identity = new ClaimsIdentity(context.Options.AuthenticationScheme);
                identity.AddClaim(ClaimTypes.NameIdentifier, user.Id, OpenIdConnectConstants.Destinations.AccessToken, OpenIdConnectConstants.Destinations.IdentityToken);
                identity.AddClaim(ClaimTypes.Name, user.UserName, OpenIdConnectConstants.Destinations.AccessToken, OpenIdConnectConstants.Destinations.IdentityToken);
                // add the user's roles as claims
                foreach (var role in roles)
                {
                    identity.AddClaim(ClaimTypes.Role, role, OpenIdConnectConstants.Destinations.AccessToken, OpenIdConnectConstants.Destinations.IdentityToken);
                }
                context.Validate(new ClaimsPrincipal(identity));
            }
            else
            {
                context.Reject(
                    error: OpenIdConnectConstants.Errors.InvalidGrant,
                    description: "Invalid grant type.");
                return;
            }

            return;
        }
Beispiel #7
0
 public override Task HandleTokenRequest(HandleTokenRequestContext context)
 {
     // Only handle grant_type=password token requests and let the
     // OpenID Connect server middleware handle the other grant types.
     if (context.Request.IsPasswordGrantType())
     {
         // Validate the credentials here (e.g using ASP.NET Core 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(OpenIdConnectConstants.Claims.Subject, "[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));
 }
        public override Task HandleTokenRequest(HandleTokenRequestContext context) {
            // Only handle grant_type=password token requests and let the
            // OpenID Connect server middleware handle the other grant types.
            if (context.Request.IsPasswordGrantType()) {
                var user = new { Id = "users-123", UserName = "******", Password = "******" };

                if (!string.Equals(context.Request.Username, user.UserName, StringComparison.Ordinal) ||
                    !string.Equals(context.Request.Password, user.Password, StringComparison.Ordinal)) {
                    context.Reject(
                        error: OpenIdConnectConstants.Errors.InvalidGrant,
                        description: "Invalid username or password.");

                    return Task.FromResult(0);
                }

                var identity = new ClaimsIdentity(context.Options.AuthenticationScheme);

                identity.AddClaim(ClaimTypes.NameIdentifier, user.Id,
                    OpenIdConnectConstants.Destinations.AccessToken,
                    OpenIdConnectConstants.Destinations.IdentityToken);

                identity.AddClaim(ClaimTypes.Name, user.UserName,
                    OpenIdConnectConstants.Destinations.AccessToken,
                    OpenIdConnectConstants.Destinations.IdentityToken);

                context.Validate(new ClaimsPrincipal(identity));
            }

            return Task.FromResult(0);
        }
Beispiel #9
0
        public override Task HandleTokenRequest(HandleTokenRequestContext context)
        {
            AuthenticationTicket ticket;

            // Handling Client Credentials
            if (context.Request.IsClientCredentialsGrantType())
            {
                // If we do not specify any form of Ticket, or ClaimsIdentity, or ClaimsPrincipal, our validation will succeed here but fail later.
                // ASOS needs those to serialize a token, and without any, it fails because there's way to fashion a token properly. Check the ASOS source for more details.
                ticket = TicketCounter.MakeClaimsForClientCredentials(context.Request.ClientId);
                context.Validate(ticket);
                return(Task.CompletedTask);
            }

            // Handling Authorization Codes
            if (context.Request.IsAuthorizationCodeGrantType() || context.Request.IsRefreshTokenGrantType())
            {
                ticket = context.Ticket;
                if (ticket != null)
                {
                    context.Validate(ticket);
                    return(Task.CompletedTask);
                }

                context.Reject(OpenIdConnectConstants.Errors.InvalidRequest, "User isn't valid");
                return(Task.CompletedTask);
            }

            // Catch all error
            context.Reject(OpenIdConnectConstants.Errors.ServerError, "Could not validate the token request");
            return(Task.CompletedTask);
        }
        private Task HandleRefreshTokenRequest(HandleTokenRequestContext context)
        {
            try
            {
                // Retrieve the token from the database and ensure it is still valid.
                var clientId = context.Ticket.Properties.Items["ClientId"];
                var token    = _authService.FindRefreshToken(t =>
                                                             t.TokenIdentifier.Equals(context.Ticket.GetTokenId()) &&
                                                             t.ClientId.Equals(clientId));
                if (token == null)
                {
                    context.Reject(
                        error: OpenIdConnectConstants.Errors.InvalidGrant,
                        description: "The refresh token is no longer valid.");

                    return(Task.CompletedTask);
                }
                _authService.DeleteRefreshToken(token);

                context.Validate(new ClaimsPrincipal(context.Ticket.Principal),
                                 new AuthenticationProperties(context.Ticket.Properties.Items),
                                 OpenIdConnectServerDefaults.AuthenticationScheme);
            }
            catch (Exception ex)
            {
                context.Reject(
                    error: $"{ex.HResult}",
                    description: ex.Message);
            }

            return(Task.CompletedTask);
        }
Beispiel #11
0
        private async Task _handleAuthorizationToken(HandleTokenRequestContext context)
        {
            AuthenticateResult ar = await context.HttpContext.AuthenticateAsync(OpenIdConnectServerDefaults.AuthenticationScheme);

            AuthenticationTicket at = ar.Ticket;

            context.Validate(at);
        }
Beispiel #12
0
        public override async Task HandleTokenRequest(HandleTokenRequestContext context)
        {
            if (!context.Request.IsPasswordGrantType())
            {
                return;
            }

            var username = context.Request.Username;
            var password = context.Request.Password;

            var user = await _userManager.FindByNameAsync(username);

            if (user == null || await _userManager.CheckPasswordAsync(user, password))
            {
                context.Reject(
                    error: OpenIdConnectConstants.Errors.InvalidGrant,
                    description: "Invalid user credentials."
                    );

                return;
            }

            var identity = new ClaimsIdentity(
                OpenIdConnectServerDefaults.AuthenticationScheme,
                OpenIdConnectConstants.Claims.Name,
                OpenIdConnectConstants.Claims.Role
                );

            identity.AddClaim(
                OpenIdConnectConstants.Claims.Subject,
                user.Id.ToString(),
                OpenIdConnectConstants.Destinations.AccessToken,
                OpenIdConnectConstants.Destinations.IdentityToken
                );

            identity.AddClaim(
                OpenIdConnectConstants.Claims.Name,
                user.UserName.ToString(),
                OpenIdConnectConstants.Destinations.AccessToken,
                OpenIdConnectConstants.Destinations.IdentityToken
                );

            var ticket = new AuthenticationTicket(
                new ClaimsPrincipal(identity),
                new AuthenticationProperties(),
                OpenIdConnectServerDefaults.AuthenticationScheme
                );

            ticket.SetScopes(
                OpenIdConnectConstants.Scopes.OpenId,
                OpenIdConnectConstants.Scopes.Profile,
                OpenIdConnectConstants.Scopes.OfflineAccess
                );

            context.Validate(ticket);

            return;
        }
        /// <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(HandleTokenRequestContext 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 async Task HandleTokenRequest(HandleTokenRequestContext context)
        {
            //HttpContext.RequestServices.GetRequiredService
            // Only handle grant_type=password token requests and let the
            // OpenID Connect server middleware handle the other grant types.
            if (context.Request.IsPasswordGrantType())
            {
                var user = await _authManager.FindUser(context.Request.Username, context.Request.Password);

                if (user == null)
                {
                    context.Reject(
                        error: OpenIdConnectConstants.Errors.InvalidGrant,
                        description: "The specified user credentials are invalid.");
                    return;
                }
                // Create a new ClaimsIdentity containing the claims that
                // will be used to create an id_token and/or an access token.
                var identity = new ClaimsIdentity(
                    OpenIdConnectServerDefaults.AuthenticationScheme,
                    OpenIdConnectConstants.Claims.Name,
                    OpenIdConnectConstants.Claims.Role);

                identity.AddClaim(
                    new Claim(OpenIdConnectConstants.Claims.Subject, user.Id.ToString())
                    .SetDestinations(OpenIdConnectConstants.Destinations.AccessToken,
                                     OpenIdConnectConstants.Destinations.IdentityToken));

                identity.AddClaim(
                    new Claim(OpenIdConnectConstants.Claims.Name, user.UserName)
                    .SetDestinations(OpenIdConnectConstants.Destinations.AccessToken,
                                     OpenIdConnectConstants.Destinations.IdentityToken));

                identity.AddClaim(
                    new Claim(OpenIdConnectConstants.Claims.Email, user.Email)
                    .SetDestinations(OpenIdConnectConstants.Destinations.AccessToken,
                                     OpenIdConnectConstants.Destinations.IdentityToken));

                var ticket = new AuthenticationTicket(
                    new ClaimsPrincipal(identity),
                    new AuthenticationProperties(),
                    OpenIdConnectServerDefaults.AuthenticationScheme);

                ticket.SetScopes(new [] {
                    /* openid: */
                    OpenIdConnectConstants.Scopes.OpenId,
                    /* email: */
                    OpenIdConnectConstants.Scopes.Email,
                    /* profile: */
                    OpenIdConnectConstants.Scopes.Profile,
                    /* offline_access: */
                    OpenIdConnectConstants.Scopes.OfflineAccess
                }.Intersect(context.Request.GetScopes()));
                ticket.SetResources("resource_server");
                context.Validate(ticket);
            }
        }
Beispiel #15
0
        /// <inheritdoc />
        public override Task HandleTokenRequest(HandleTokenRequestContext context)
        {
            // Only handle grant_type=password token requests and let the
            // OpenID Connect server middleware handle the other grant types.
            if (context.Request.IsPasswordGrantType())
            {
                // Validate the credentials here (e.g using ASP.NET Core Identity).
                // You can call Reject() with an error code/description to reject
                // the request and return a message to the caller.

                // ReSharper disable once NotAccessedVariable
                UserDto user;

                var credential = new NetworkCredential(context.Request.Username, context.Request.Password);
                try
                {
                    // ReSharper disable once RedundantAssignment
                    user = _loginProvider.GetUser(credential.UserName, credential.Password);
                }
                catch (AuthenticationException err)
                {
                    context.Reject(
                        error: OpenIdConnectConstants.Errors.InvalidClient,
                        description: err.Message);

                    return(Task.CompletedTask);
                }

                var identity = new ClaimsIdentity();
                identity.AddClaim(OpenIdConnectConstants.Claims.Subject, "[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(),
                    "Role");

                // 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.CompletedTask);
        }
        public override Task HandleTokenRequest(HandleTokenRequestContext context)
        {
            // Only handle grant_type=password token requests and let the
            // OpenID Connect server middleware handle the other grant types.
            if (context.Request.IsPasswordGrantType())
            {
                // Using password derivation and a time-constant comparer is STRONGLY recommended.
                if (!string.Equals(context.Request.Username, "Bob", StringComparison.Ordinal) ||
                    !string.Equals(context.Request.Password, "P@ssw0rd", StringComparison.Ordinal))
                {
                    context.Reject(
                        error: OpenIdConnectConstants.Errors.InvalidGrant,
                        description: "The specified user credentials are invalid.");

                    return(Task.FromResult(0));
                }

                // Create a new ClaimsIdentity containing the claims that
                // will be used to create an id_token and/or an access token.
                var identity = new ClaimsIdentity(
                    OpenIdConnectServerDefaults.AuthenticationScheme,
                    OpenIdConnectConstants.Claims.Name,
                    OpenIdConnectConstants.Claims.Role);

                identity.AddClaim(OpenIdConnectConstants.Claims.Subject, Guid.NewGuid().ToString(),
                                  OpenIdConnectConstants.Destinations.AccessToken,
                                  OpenIdConnectConstants.Destinations.IdentityToken);

                identity.AddClaim(OpenIdConnectConstants.Claims.Name, "Bob le Bricoleur",
                                  OpenIdConnectConstants.Destinations.AccessToken,
                                  OpenIdConnectConstants.Destinations.IdentityToken);

                identity.AddClaim(OpenIdConnectConstants.Claims.Role, "Admin",
                                  OpenIdConnectConstants.Destinations.AccessToken,
                                  OpenIdConnectConstants.Destinations.IdentityToken);

                // Create a new authentication ticket holding the user identity.
                var ticket = new AuthenticationTicket(
                    new ClaimsPrincipal(identity),
                    new AuthenticationProperties(),
                    OpenIdConnectServerDefaults.AuthenticationScheme);

                // Set the list of scopes granted to the client application.
                ticket.SetScopes(new[] {
                    /* openid: */ OpenIdConnectConstants.Scopes.OpenId,
                    /* email: */ OpenIdConnectConstants.Scopes.Email,
                    /* profile: */ OpenIdConnectConstants.Scopes.Profile,
                    /* offline_access: */ OpenIdConnectConstants.Scopes.OfflineAccess
                }.Intersect(context.Request.GetScopes()));

                context.Validate(ticket);
            }

            return(Task.FromResult(0));
        }
Beispiel #17
0
        public override async Task HandleTokenRequest(HandleTokenRequestContext context)
        {
            NotificationResult result = null;
            var userService           = GetUserService();

            if (context.Request.IsPasswordGrantType())
            {
                result = await userService.IsValidUsernameAndPasswordAsync(context.Request.Username, context.Request.Password);
            }
            else if (context.Request.IsRefreshTokenGrantType())
            {
                var    idUser   = new Guid(context.Ticket.Principal.GetClaim(ClaimTypes.NameIdentifier));
                string username = context.Ticket.Principal.GetClaim(ClaimTypes.Name);

                result = await userService.IsValidUsernameAndTokenAsync(username, idUser);
            }

            if (result.IsValid && result.Data == null && result.Messages.Any(x => x.Type == NotificationResult.NotificationMessageType.Warning))
            {
                result.AddError(result.Messages.First(x => x.Type == NotificationResult.NotificationMessageType.Warning).Message);
            }

            if (!result.IsValid)
            {
                context.Reject(
                    error: OpenIdConnectConstants.Errors.InvalidGrant,
                    description: result.GetErrors()
                    );
            }
            else
            {
                var identity = new ClaimsIdentity(OpenIdConnectServerDefaults.AuthenticationScheme);
                var user     = result.Data as UserCommandResult;

                identity.AddClaim(OpenIdConnectConstants.Claims.Subject, user.IdUser.ToString());
                identity.AddClaim(ClaimTypes.NameIdentifier, user.IdUser.ToString(), Destinations.AccessToken);
                identity.AddClaim(ClaimTypes.Name, user.Username, Destinations.AccessToken);
                identity.AddClaim(ClaimTypes.GivenName, user.FirstName, Destinations.AccessToken, Destinations.IdentityToken);
                identity.AddClaim(ClaimTypes.Email, user.Email, Destinations.AccessToken, Destinations.IdentityToken);

                var ticket = new AuthenticationTicket(
                    new ClaimsPrincipal(identity),
                    new AuthenticationProperties(),
                    OpenIdConnectServerDefaults.AuthenticationScheme
                    );

                ticket.SetScopes(
                    Scopes.OpenId,
                    Scopes.OfflineAccess
                    );

                context.Validate(ticket);
            }
        }
Beispiel #18
0
 private async Task OnHandleTokenRequest(HandleTokenRequestContext context)
 {
     // Only handle grant_type=password token requests and let
     // the OpenID Connect server handle the other grant types.
     if (context.Request.GrantType == "Password")
     {
         if (context.Request.Password == "12345")
         {
             // your choice of claims...
             ReturnIdentity(context, context.Request.Username);
         }
     }
 }
Beispiel #19
0
        public override async Task HandleTokenRequest(HandleTokenRequestContext context)
        {
            var encrypter = context.HttpContext.RequestServices.GetRequiredService <IEncrypter>();

            if (context.Request.IsPasswordGrantType())
            {
                var Config    = context.HttpContext.RequestServices.GetRequiredService <IConfiguration>();
                var conString = Config.GetSection("ConnectionString").GetValue <string>("dbCon");
                conString = conString.Replace("@@username@@", context.Request.Username);
                conString = conString.Replace("@@pass@@", context.Request.Password);

                using (FbConnection mycon = new FbConnection(conString))
                {
                    try
                    {
                        mycon.Open();
                    }
                    catch (Exception)
                    {
                        throw new ArgumentException("Wrong password or login");
                    }
                }
                conString = encrypter.EncryptConnectionString(conString);

                var identity = new ClaimsIdentity(
                    context.Options.AuthenticationScheme,
                    OpenIdConnectConstants.Claims.Name,
                    OpenIdConnectConstants.Claims.Role);

                // Add the mandatory subject/user identifier claim.
                identity.AddClaim(OpenIdConnectConstants.Claims.Subject, conString);

                identity.AddClaim("username", conString,
                                  OpenIdConnectConstants.Destinations.AccessToken,
                                  OpenIdConnectConstants.Destinations.IdentityToken);

                var ticket = new AuthenticationTicket(
                    new ClaimsPrincipal(identity),
                    new AuthenticationProperties(),
                    context.Options.AuthenticationScheme);

                // Call SetScopes with the list of scopes you want to grant
                // (specify offline_access to issue a refresh token).
                ticket.SetScopes(
                    OpenIdConnectConstants.Scopes.OfflineAccess,
                    OpenIdConnectConstants.Scopes.OpenId);

                context.Validate(ticket);
            }
        }
Beispiel #20
0
        public override Task HandleTokenRequest(HandleTokenRequestContext context)
        {
            if (!context.Request.IsPasswordGrantType())
            {
                return(Task.FromResult(0));
            }

            // "There was a server error while trying to validate the authentication.");
            if (!context.Request.Username.Equals("hello"))
            {
                context.Reject("authentication error. Username must be 'hello'");
                return(Task.FromResult(0));
            }
            // "There was a server error while trying to validate the authentication.");
            if (!context.Request.Password.Equals("world"))
            {
                context.Reject("authentication error. Password must be 'world'");
                return(Task.FromResult(0));
            }

            var identity = new ClaimsIdentity(context.Scheme.Name);

            identity.AddClaim(OpenIdConnectConstants.Claims.Subject, "userID");

            // When adding custom claims, you MUST specify one or more destinations.
            // Read "part 7" for more information about custom claims and scopes.

            /*
             * foreach(var data in authenticatedData.GetData())
             * {
             *  identity.AddClaim(data.Key, data.Value, OpenIdConnectConstants.Destinations.AccessToken,
             *  OpenIdConnectConstants.Destinations.IdentityToken);
             * }*/

            // Create a new authentication ticket holding the user identity.
            var ticket = new AuthenticationTicket(
                new ClaimsPrincipal(identity), new AuthenticationProperties()
            {
                AllowRefresh = true
            },
                context.Scheme.Name);

            // Set the list of scopes granted to the client application. OfflineAccess will return the refresh token
            ticket.SetScopes(OpenIdConnectConstants.Scopes.OfflineAccess, OpenIdConnectConstants.Scopes.Profile);

            // Set the resource servers the access token should be issued for.
            ticket.SetResources("resource_server");
            context.Validate(ticket);
            return(Task.FromResult(0));
        }
Beispiel #21
0
        public override async Task HandleTokenRequest(HandleTokenRequestContext context)
        {
            if (context.Request.IsPasswordGrantType())
            {
                try
                {
                    var user = await this.userService.AuthenticateAsync(context.Request.Username, context.Request.Password);

                    var identity = new ClaimsIdentity(context.Scheme.Name);
                    identity.AddClaim(OpenIdConnectConstants.Claims.Subject, user.Email);
                    identity.AddClaim(
                        "username",
                        $"{user.Email}",
                        OpenIdConnectConstants.Destinations.AccessToken,
                        OpenIdConnectConstants.Destinations.IdentityToken);
                    identity.AddClaim(
                        OpenIdConnectConstants.Claims.Role,
                        user.Role.ToString(),
                        new List <string> {
                        OpenIdConnectConstants.Destinations.AccessToken,
                        OpenIdConnectConstants.Destinations.IdentityToken
                    });
                    // Create a new authentication ticket holding the user identity.
                    var ticket = new AuthenticationTicket(
                        new ClaimsPrincipal(identity),
                        new AuthenticationProperties(),
                        context.Scheme.Name);
                    // Set the list of scopes granted to the client application.
                    ticket.SetScopes(
                        OpenIdConnectConstants.Scopes.OpenId,
                        OpenIdConnectConstants.Scopes.Email,
                        OpenIdConnectConstants.Scopes.Profile,
                        OpenIdConnectConstants.Scopes.OfflineAccess);
                    context.Validate(ticket);
                }
                catch
                {
                    context.Reject(
                        error: OpenIdConnectConstants.Errors.InvalidGrant,
                        description: "Utilisateur et/ou mot de passe incorrect");
                }
            }
            else
            {
                // Cas du refresh_token ASOS gère tout seul
            }
        }
        /// <summary>
        /// Validates the userName and password provided by the user.
        /// </summary>
        private async Task GrantResourceOwnerCredentials(HandleTokenRequestContext context)
        {
            var query  = new UserNamePasswordLoginQuery(context.Request.Username, context.Request.Password);
            var result = await ExecuteQuery(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 HandleTokenRequest(HandleTokenRequestContext context) {
            // Only handle grant_type=password token requests and let the
            // OpenID Connect server middleware handle the other grant types.
            if (context.Request.IsPasswordGrantType()) {
                // Using password derivation and a time-constant comparer is STRONGLY recommended.
                if (!string.Equals(context.Request.Username, "Bob", StringComparison.Ordinal) ||
                    !string.Equals(context.Request.Password, "P@ssw0rd", StringComparison.Ordinal)) {
                    context.Reject(
                        error: OpenIdConnectConstants.Errors.InvalidGrant,
                        description: "Invalid user credentials.");

                    return Task.FromResult(0);
                }

                // Create a new ClaimsIdentity containing the claims that
                // will be used to create an id_token and/or an access token.
                var identity = new ClaimsIdentity(OpenIdConnectServerDefaults.AuthenticationScheme);

                identity.AddClaim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString(),
                    OpenIdConnectConstants.Destinations.AccessToken,
                    OpenIdConnectConstants.Destinations.IdentityToken);

                identity.AddClaim(ClaimTypes.Name, "Bob le Bricoleur",
                    OpenIdConnectConstants.Destinations.AccessToken,
                    OpenIdConnectConstants.Destinations.IdentityToken);

                // Create a new authentication ticket holding the user identity.
                var ticket = new AuthenticationTicket(
                    new ClaimsPrincipal(identity),
                    new AuthenticationProperties(),
                    OpenIdConnectServerDefaults.AuthenticationScheme);

                // Set the list of scopes granted to the client application.
                ticket.SetScopes(new[] {
                    /* openid: */ OpenIdConnectConstants.Scopes.OpenId,
                    /* email: */ OpenIdConnectConstants.Scopes.Email,
                    /* profile: */ OpenIdConnectConstants.Scopes.Profile,
                    /* offline_access: */ OpenIdConnectConstants.Scopes.OfflineAccess
                }.Intersect(context.Request.GetScopes()));

                context.Validate(ticket);
            }

            return Task.FromResult(0);
        }
        /// <summary>
        /// Use this method, because there we are using old version of AuthenticationTicket object from Asp.Net Core 1.0, until OpenIdConnect update their library to use .Net Core 2.0 objects
        /// </summary>
        /// <param name="context"></param>
        /// <param name="principal"></param>
        /// <param name="properties"></param>
        /// <param name="authenticationScheme"></param>
        /// <param name="scopes"></param>
        /// <param name="resources"></param>
        public static void Validate(this HandleTokenRequestContext context,
                                    ClaimsPrincipal principal,
                                    AuthenticationProperties properties,
                                    string authenticationScheme,
                                    List <string> scopes    = null,
                                    List <string> resources = null)
        {
            var ticket = new AuthenticationTicket(principal, properties, authenticationScheme);

            if (context.Request.IsClientCredentialsGrantType())
            {
                if (scopes == null || !scopes.Any())
                {
                    scopes = new[]
                    {
                        /* openid: */ OpenIdConnectConstants.Scopes.OpenId,
                        /* email: */ OpenIdConnectConstants.Scopes.Email,
                        /* profile: */ OpenIdConnectConstants.Scopes.Profile,
                    }
                }
Beispiel #25
0
        private static void ReturnIdentity(HandleTokenRequestContext context, string user)
        {
            var identity = new ClaimsIdentity(context.Scheme.Name, "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name",
                                              "http://schemas.microsoft.com/ws/2008/06/identity/claims/role");

            identity.AddClaim(
                "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier",
                string.IsNullOrEmpty(user) ? "Anonyme" : user,
                OpenIdConnectConstants.Destinations.AccessToken,
                OpenIdConnectConstants.Destinations.IdentityToken);
            identity.AddClaim(
                "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name",
                user,
                OpenIdConnectConstants.Destinations.AccessToken,
                OpenIdConnectConstants.Destinations.IdentityToken);
            identity.AddClaim(
                OpenIdConnectConstants.Claims.Subject,
                user,
                OpenIdConnectConstants.Destinations.AccessToken,
                OpenIdConnectConstants.Destinations.IdentityToken);
            identity.AddClaim(
                "tokenId",
                "1235453432FSD",
                OpenIdConnectConstants.Destinations.AccessToken,
                OpenIdConnectConstants.Destinations.IdentityToken);


            var ticket = new AuthenticationTicket(
                new ClaimsPrincipal(identity),
                new AuthenticationProperties(),
                context.Scheme.Name);

            // Call SetScopes with the list of scopes you want to grant
            // (specify offline_access to issue a refresh token).
            ticket.SetScopes(
                OpenIdConnectConstants.Scopes.Profile,
                OpenIdConnectConstants.Scopes.OfflineAccess);

            context.Validate(ticket);
        }
Beispiel #26
0
        public override async Task HandleTokenRequest(HandleTokenRequestContext 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.Request.Username);

            if (user != null)
            {
                isValidUser = await userManager.CheckPasswordAsync(user, context.Request.Password);
            }

            if (isValidUser)
            {
                var identity = new ClaimsIdentity(context.Options.AuthenticationScheme);

                identity.AddClaim(ClaimTypes.NameIdentifier, user.UserName);
                identity.AddClaim(ClaimTypes.GivenName, user.FullName);

                identity.AddClaim("username", user.UserName,
                                  OpenIdConnectConstants.Destinations.AccessToken,
                                  OpenIdConnectConstants.Destinations.IdentityToken);

                var ticket = new AuthenticationTicket(
                    new ClaimsPrincipal(identity),
                    new AuthenticationProperties(),
                    context.Options.AuthenticationScheme);

                ticket.SetScopes("api");

                context.Validate(ticket);
            }
            else
            {
                context.Reject();
            }
        }
        /// <summary>
        /// Grant a new access_token based on the current refresh_token. Here we couldvalidate whether the
        /// refresh token is still valid or revoked.
        /// </summary>
        private async Task GrantRefreshToken(HandleTokenRequestContext context)
        {
            var validator = new RefreshTokenValidatorQuery(
                context.Ticket.GetTicketId(),
                context.Request.ClientId,
                context.Ticket.Principal.GetClaim(ClaimTypes.NameIdentifier));

            var result = await ExecuteQuery(context, validator);

            if (!result.Succeeded)
            {
                context.Reject(OpenIdConnectConstants.Errors.InvalidRequest, "Could not validate refresh_token.");
                return;
            }

            SetCorsHeader(context);

            var principal = new ClaimsPrincipal(context.Ticket.Principal);
            var ticket    = CreateAuthenticationTicket(principal, context.Ticket.Properties, context.Options, context);

            context.Validate(ticket);
        }
        public override async Task HandleTokenRequest(HandleTokenRequestContext context)
        {
            if (!context.Request.IsPasswordGrantType() &&
                !context.Request.IsRefreshTokenGrantType())
            {
                context.Reject(
                    error: OpenIdConnectConstants.Errors.UnsupportedGrantType,
                    description: "Only password and refresh token grant types " +
                    "are accepted by this authorization server");

                return;
            }

            if (context.Request.IsPasswordGrantType())
            {
                await this.GrantResourceOwnerCredentials(context);
            }
            if (context.Request.IsRefreshTokenGrantType())
            {
                await this.GrantRefreshToken(context);
            }
        }
        public Task GetAccessToken(HandleTokenRequestContext context, CancellationToken cancellationToken)
        {
            if (context.Request.IsPasswordGrantType())
            {
                if (!string.Equals(context.Request.Username, "Bob", StringComparison.Ordinal) ||
                    !string.Equals(context.Request.Password, "P@ssw0rd", StringComparison.Ordinal))
                {
                    context.Reject(
                        error: OpenIdConnectConstants.Errors.InvalidGrant,
                        description: "Invalid user credentials.");

                    return(Task.CompletedTask);
                }

                var identity = new ClaimsIdentity(context.Scheme.Name,
                                                  OpenIdConnectConstants.Claims.Name,
                                                  OpenIdConnectConstants.Claims.Role);

                identity.AddClaim(OpenIdConnectConstants.Claims.Subject, "[unique id]", OpenIdConnectConstants.Destinations.IdentityToken);

                identity.AddClaim("urn:customclaim", "value",
                                  OpenIdConnectConstants.Destinations.AccessToken,
                                  OpenIdConnectConstants.Destinations.IdentityToken);

                var ticket = new AuthenticationTicket(
                    new ClaimsPrincipal(identity),
                    new AuthenticationProperties(),
                    context.Scheme.Name);
                ticket.SetResources("resource_server");
                ticket.SetScopes(
                    OpenIdConnectConstants.Scopes.Profile,
                    OpenIdConnectConstants.Scopes.OfflineAccess
                    );

                context.Validate(ticket);
            }

            return(Task.CompletedTask);
        }
Beispiel #30
0
        public override async Task HandleTokenRequest(HandleTokenRequestContext context)
        {
            authservice = context.HttpContext.RequestServices.GetRequiredService <IValidateAuthorizationService>();
            if (authservice == null)
            {
                context.Reject(OpenIdConnectConstants.Errors.ServerError, "Failed to validate this authorization request");
                return;
            }
            if (context.Request.IsRefreshTokenGrantType())
            {
                await _handleRefreshToken(context);

                return;
            }
            else if (context.Request.IsAuthorizationCodeGrantType())
            {
                await _handleAuthorizationToken(context);

                return;
            }
            else if (context.Request.IsImplicitFlow())
            {
                await _handleImplicitCredentialsToken(context);

                return;
            }
            else if (context.Request.IsClientCredentialsGrantType())
            {
                await _handleClientCredentialsToken(context);

                return;
            }
            context.Reject(
                error: OpenIdConnectConstants.Errors.UnsupportedGrantType,
                description: "Only authorization code, client credentials, and implicit grants " +
                "are accepted by this authorization server");
            return;
        }
        /// <summary>
        /// Represents an event called for each validated token request
        /// to allow the user code to decide how the request should be handled.
        /// </summary>
        /// <param name="context">The context instance associated with this event.</param>
        /// <returns>
        /// A <see cref="T:System.Threading.Tasks.Task" /> that can be used to monitor the asynchronous operation.
        /// </returns>
        public override async Task HandleTokenRequest(HandleTokenRequestContext context)
        {
            //// TODO: Revisar lo que no va quemado
            if (context.Request.IsPasswordGrantType())
            {
                var userService = (IUserService)context.HttpContext.RequestServices.GetService(typeof(IUserService));

                var user = await userService.GetUserAuthenticated(context.Request.Username, context.Request.Password);

                if (user != null)
                {
                    var identity = new ClaimsIdentity(context.Options.AuthenticationScheme);

                    identity.AddClaim(OpenIdConnectConstants.Claims.Subject, user.Id.ToString());
                    identity.AddClaim(OpenIdConnectConstants.Claims.Name, user.Name);

                    var ticket = new AuthenticationTicket(
                        new ClaimsPrincipal(identity),
                        new AuthenticationProperties(),
                        context.Options.AuthenticationScheme);

                    ticket.SetScopes(
                        OpenIdConnectConstants.Scopes.OpenId,
                        OpenIdConnectConstants.Scopes.Email,
                        OpenIdConnectConstants.Scopes.Profile);

                    ticket.SetResources("http://hostaliando.com");

                    context.Validate(ticket);
                }
                else
                {
                    context.Reject(
                        error: OpenIdConnectConstants.Errors.AccessDenied,
                        description: "Los datos ingresados son invalidos");
                }
            }
        }
Beispiel #32
0
        private async Task _handleClientCredentialsToken(HandleTokenRequestContext context)
        {
            ClaimsIdentity identity = new ClaimsIdentity(OpenIdConnectServerDefaults.AuthenticationScheme, OpenIdConnectConstants.Claims.Name, OpenIdConnectConstants.Claims.Role);

            // We serialize the user_id so we can determine which user the caller of this token is
            identity.AddClaim(
                new Claim(OpenIdConnectConstants.Claims.Subject, context.Request.ClientId)
                .SetDestinations(OpenIdConnectConstants.Destinations.AccessToken, OpenIdConnectConstants.Destinations.IdentityToken));

            // We serialize the grant_type so we can user discriminate rate-limits. AuthorizationCode grants have the highest rate-limit allowance
            identity.AddClaim(
                new Claim("grant_type", OpenIdConnectConstants.GrantTypes.ClientCredentials)
                .SetDestinations(OpenIdConnectConstants.Destinations.AccessToken, OpenIdConnectConstants.Destinations.IdentityToken));

            // We serialize the client_id so we can monitor for usage patterns of a given app, and also to allow for app-based token revokes.
            identity.AddClaim(
                new Claim("client_id", context.Request.ClientId)
                .SetDestinations(OpenIdConnectConstants.Destinations.AccessToken, OpenIdConnectConstants.Destinations.IdentityToken));

            AuthenticationTicket ticket = new AuthenticationTicket(new ClaimsPrincipal(identity), new AuthenticationProperties(), OpenIdConnectServerDefaults.AuthenticationScheme);

            context.Validate(ticket);
        }
        public override async Task HandleTokenRequest(HandleTokenRequestContext context)
        {
            // Resolve ASP.NET Core Identity's user manager from the DI container.
            var manager = context.HttpContext.RequestServices.GetRequiredService<UserManager<ApplicationUser>>();

            // Only handle grant_type=password requests and let ASOS
            // process grant_type=refresh_token requests automatically.
            if (context.Request.IsPasswordGrantType())
            {
                var user = await manager.FindByNameAsync(context.Request.Username);
                if (user == null)
                {
                    context.Reject(
                        error: OpenIdConnectConstants.Errors.InvalidGrant,
                        description: "Invalid credentials.");

                    return;
                }

                // Ensure the user is not already locked out.
                if (manager.SupportsUserLockout && await manager.IsLockedOutAsync(user))
                {
                    context.Reject(
                        error: OpenIdConnectConstants.Errors.InvalidGrant,
                        description: "Invalid credentials.");

                    return;
                }

                // Ensure the password is valid.
                if (!await manager.CheckPasswordAsync(user, context.Request.Password))
                {
                    if (manager.SupportsUserLockout)
                    {
                        await manager.AccessFailedAsync(user);
                    }

                    context.Reject(
                        error: OpenIdConnectConstants.Errors.InvalidGrant,
                        description: "Invalid credentials.");

                    return;
                }

                if (manager.SupportsUserLockout)
                {
                    await manager.ResetAccessFailedCountAsync(user);
                }

                // Reject the token request if two-factor authentication has been enabled by the user.
                if (manager.SupportsUserTwoFactor && await manager.GetTwoFactorEnabledAsync(user))
                {
                    context.Reject(
                        error: OpenIdConnectConstants.Errors.InvalidGrant,
                        description: "Two-factor authentication is required for this account.");

                    return;
                }

                var identity = new ClaimsIdentity(context.Options.AuthenticationScheme);

                // Note: the name identifier is always included in both identity and
                // access tokens, even if an explicit destination is not specified.
                identity.AddClaim(ClaimTypes.NameIdentifier, await manager.GetUserIdAsync(user));

                // When adding custom claims, you MUST specify one or more destinations.
                // Read "part 7" for more information about custom claims and scopes.
                identity.AddClaim("username", await manager.GetUserNameAsync(user),
                    OpenIdConnectConstants.Destinations.AccessToken,
                    OpenIdConnectConstants.Destinations.IdentityToken);

                identity.AddClaim("firstName", user.FirstName, OpenIdConnectConstants.Destinations.IdentityToken);

                //Add roles
                var roles = await manager.GetRolesAsync(user);
                var roleClaims = new List<Claim>();
                foreach(var role in roles)
                {
                    identity.AddClaim(ClaimTypes.Role, role, OpenIdConnectConstants.Destinations.AccessToken,
                    OpenIdConnectConstants.Destinations.IdentityToken);
                }

                var estheticians = (IEstheticianService)context.HttpContext.RequestServices.GetService(typeof(IEstheticianService));

                var esthetician = await estheticians.GetByEmailAsync(user.Email);

                if (esthetician != null)
                {
                   identity.AddClaim("estheticianId", esthetician.Id.ToString(), OpenIdConnectConstants.Destinations.AccessToken,
                   OpenIdConnectConstants.Destinations.IdentityToken);
                }

                // Create a new authentication ticket holding the user identity.
                var ticket = new AuthenticationTicket(
                    new ClaimsPrincipal(identity),
                    new AuthenticationProperties(),
                    context.Options.AuthenticationScheme);

                // Set the list of scopes granted to the client application.
                ticket.SetScopes(
                    /* openid: */ OpenIdConnectConstants.Scopes.OpenId,
                    /* email: */ OpenIdConnectConstants.Scopes.Email,
                    
                    /* profile: */ OpenIdConnectConstants.Scopes.Profile,
                    /* offline_access */ OpenIdConnectConstants.Scopes.OfflineAccess);
                // Set the resource servers the access token should be issued for.
                ticket.SetResources("resource_server");
                
                context.Validate(ticket);
            }
        }