示例#1
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);
            }
        }