public override async Task SerializeRefreshToken([NotNull] SerializeRefreshTokenContext context)
        {
            var applications = context.HttpContext.RequestServices.GetRequiredService <OpenIddictApplicationManager <TApplication> >();
            var options      = context.HttpContext.RequestServices.GetRequiredService <IOptions <OpenIddictOptions> >();
            var tokens       = context.HttpContext.RequestServices.GetRequiredService <OpenIddictTokenManager <TToken> >();

            if (!options.Value.DisableTokenRevocation)
            {
                // Resolve the subject from the authentication ticket. If it cannot be found, throw an exception.
                var subject = context.Ticket.Principal.GetClaim(OpenIdConnectConstants.Claims.Subject) ??
                              context.Ticket.Principal.GetClaim(ClaimTypes.NameIdentifier) ??
                              context.Ticket.Principal.GetClaim(ClaimTypes.Upn);

                if (string.IsNullOrEmpty(subject))
                {
                    throw new InvalidOperationException("The subject associated with the authentication ticket cannot be retrieved.");
                }

                // If a null value was returned by CreateAsync, return immediately.
                var token = await tokens.CreateAsync(OpenIdConnectConstants.TokenTypeHints.RefreshToken, subject, context.HttpContext.RequestAborted);

                if (token == null)
                {
                    return;
                }

                // Throw an exception if the token identifier can't be resolved.
                var identifier = await tokens.GetIdAsync(token, context.HttpContext.RequestAborted);

                if (string.IsNullOrEmpty(identifier))
                {
                    throw new InvalidOperationException("The unique key associated with a refresh token cannot be null or empty.");
                }

                // Attach the key returned by the underlying store
                // to the refresh token to override the default GUID
                // generated by the OpenID Connect server middleware.
                context.Ticket.SetTicketId(identifier);

                // If the client application is known, associate it with the token.
                if (!string.IsNullOrEmpty(context.Request.ClientId))
                {
                    var application = await applications.FindByClientIdAsync(context.Request.ClientId, context.HttpContext.RequestAborted);

                    if (application == null)
                    {
                        throw new InvalidOperationException("The client application cannot be retrieved from the database.");
                    }

                    await tokens.SetClientAsync(token, await applications.GetIdAsync(application, context.HttpContext.RequestAborted), context.HttpContext.RequestAborted);
                }

                // If an authorization identifier was specified, bind it to the token.
                var authorization = context.Ticket.GetProperty(OpenIddictConstants.Properties.AuthorizationId);
                if (!string.IsNullOrEmpty(authorization))
                {
                    await tokens.SetAuthorizationAsync(token, authorization, context.HttpContext.RequestAborted);
                }
            }
        }
        public override async Task SerializeRefreshToken([NotNull] SerializeRefreshTokenContext context)
        {
            var options = (OpenIddictServerOptions)context.Options;

            if (options.DisableTokenStorage)
            {
                return;
            }

            Debug.Assert(context.Request.IsTokenRequest(), "The request should be a token request.");

            var token = await CreateTokenAsync(
                OpenIdConnectConstants.TokenUsages.RefreshToken,
                context.Ticket, options, context.Request, context.DataFormat);

            // If a reference token was returned by CreateTokenAsync(),
            // force the OpenID Connect server middleware to use it.
            if (!string.IsNullOrEmpty(token))
            {
                context.RefreshToken = token;
                context.HandleSerialization();
            }

            // Otherwise, let the OpenID Connect server middleware
            // serialize the token using its default internal logic.

            await _eventService.PublishAsync(new OpenIddictServerEvents.SerializeRefreshToken(context));
        }
示例#3
0
        public override async Task SerializeRefreshToken([NotNull] SerializeRefreshTokenContext context)
        {
            var services = context.HttpContext.RequestServices.GetRequiredService <OpenIddictServices <TUser, TApplication, TAuthorization, TScope, TToken> >();

            Debug.Assert(context.Request.IsTokenRequest(), "The request should be a token request.");
            Debug.Assert(!context.Request.IsClientCredentialsGrantType(),
                         "A refresh token should not be issued when using grant_type=client_credentials.");

            // Note: a null value could be returned by FindByIdAsync if the user was removed after the initial
            // check made by HandleTokenRequest. In this case, throw an exception to abort the token request.
            var user = await services.Users.FindByIdAsync(context.Ticket.Principal.GetClaim(ClaimTypes.NameIdentifier));

            if (user == null)
            {
                throw new InvalidOperationException("The token request was aborted because the user associated " +
                                                    "with the refresh token was not found in the database.");
            }

            string identifier;

            // If the client application sending the token request is known,
            // ensure the token is attached to the corresponding client entity.
            if (!string.IsNullOrEmpty(context.Request.ClientId))
            {
                var application = await services.Applications.FindByClientIdAsync(context.Request.ClientId);

                if (application == null)
                {
                    throw new InvalidOperationException("The application cannot be retrieved from the database.");
                }

                // Persist a new token entry in the database and attach it
                // to the user and the client application it is issued to.
                identifier = await services.Users.CreateTokenAsync(user, context.Request.ClientId,
                                                                   OpenIdConnectConstants.TokenTypeHints.RefreshToken);
            }

            else
            {
                // Persist a new token entry in the database
                // and attach it to the user it corresponds to.
                identifier = await services.Users.CreateTokenAsync(user,
                                                                   OpenIdConnectConstants.TokenTypeHints.RefreshToken);
            }

            if (string.IsNullOrEmpty(identifier))
            {
                throw new InvalidOperationException("The unique key associated with a refresh token cannot be null or empty.");
            }

            // Attach the key returned by the underlying store
            // to the refresh token to override the default GUID
            // generated by the OpenID Connect server middleware.
            context.Ticket.SetTicketId(identifier);
        }
        public override async Task SerializeRefreshToken([NotNull] SerializeRefreshTokenContext context)
        {
            var tokens = context.HttpContext.RequestServices.GetRequiredService <OpenIddictTokenManager <TToken> >();

            var identifier = await tokens.CreateAsync(OpenIdConnectConstants.TokenTypeHints.RefreshToken, context.HttpContext.RequestAborted);

            if (string.IsNullOrEmpty(identifier))
            {
                throw new InvalidOperationException("The unique key associated with a refresh token cannot be null or empty.");
            }

            // Attach the key returned by the underlying store
            // to the refresh token to override the default GUID
            // generated by the OpenID Connect server middleware.
            context.Ticket.SetTicketId(identifier);
        }
示例#5
0
        public override Task SerializeRefreshToken(SerializeRefreshTokenContext context)
        {
            _authService = (IAuthService)context.HttpContext.RequestServices.GetService(typeof(IAuthService));
            var clientid = string.Empty;

            context.Ticket.Properties.Items.TryGetValue("client_id", out clientid);

            if (string.IsNullOrEmpty(clientid))
            {
                return(Task.FromResult(0));
            }

            var refreshTokenId = Guid.NewGuid().ToString("n");

            Client client = _authService.FindClient(clientid);

            var refreshTokenLifeTime = client.RefreshTokenLifeTime;

            var token = new RefreshToken()
            {
                Id         = refreshTokenId,
                ClientId   = clientid,
                Subject    = context.Ticket.Principal.Identity.Name,
                IssuedUtc  = DateTime.Now,
                ExpiresUtc = DateTime.Now.AddMinutes(Convert.ToDouble(refreshTokenLifeTime))
            };

            context.Ticket.Properties.IssuedUtc  = token.IssuedUtc;
            context.Ticket.Properties.ExpiresUtc = token.ExpiresUtc;


            token.ProtectedTicket = context.DataFormat.Protect(context.Ticket);

            var result = _authService.AddRefreshToken(token);

            if (result)
            {
                context.RefreshToken = refreshTokenId;
            }

            return(Task.FromResult <object>(null));
        }
        private async Task StoreRefreshToken(SerializeRefreshTokenContext context)
        {
            var principal  = context.Ticket.Principal;
            var properties = context.Ticket.Properties;

            var command = new CreateRefreshTokenCommand(
                context.Ticket.GetTicketId(),
                context.Request.ClientId,
                principal.GetClaim(ClaimTypes.NameIdentifier),
                principal.GetClaim(ClaimTypes.Name),
                context.HttpContext.Connection.RemoteIpAddress?.ToString(),
                properties.IssuedUtc.GetValueOrDefault(),
                properties.ExpiresUtc.GetValueOrDefault());

            var result = await ExecuteMessage(context, command);

            if (!result.Succeeded)
            {
                throw new InvalidOperationException("Could not store the refreshtoken");
            }
        }
        public override Task SerializeRefreshToken(SerializeRefreshTokenContext context)
        {
            try
            {
                int    userId   = Convert.ToInt32(context.Ticket.Properties.Items["UserId"]);
                string clientId = context.Ticket.Properties.Items["ClientId"];

                var token = _authService.AddRefreshToken(
                    context.Ticket.GetTokenId(),
                    userId,
                    clientId,
                    DateTime.UtcNow,
                    DateTime.UtcNow.AddMinutes(_configuration.RefreshTokenLifetimeMinutes));

                context.Ticket.Properties.IssuedUtc  = token.IssuedUtc;
                context.Ticket.Properties.ExpiresUtc = token.ExpiresUtc;
            }
            catch (Exception ex)
            {
            }
            return(Task.CompletedTask);
        }
示例#8
0
            /// <summary>
            /// Processes the event.
            /// </summary>
            /// <param name="context">The context associated with the event to process.</param>
            /// <returns>
            /// A <see cref="Task"/> that can be used to monitor the asynchronous operation.
            /// </returns>
            public async Task HandleAsync([NotNull] ProcessSigninResponseContext context)
            {
                if (context == null)
                {
                    throw new ArgumentNullException(nameof(context));
                }

                var principal = context.Principal.Clone(_ => true)
                                .SetTokenId(Guid.NewGuid().ToString())
                                .SetCreationDate(DateTimeOffset.UtcNow);

                var lifetime = context.Principal.GetRefreshTokenLifetime() ?? context.Options.RefreshTokenLifetime;

                if (lifetime.HasValue)
                {
                    principal.SetExpirationDate(principal.GetCreationDate() + lifetime.Value);
                }

                var notification = new SerializeRefreshTokenContext(context.Transaction)
                {
                    Principal = principal
                };

                await _provider.DispatchAsync(notification);

                if (!notification.IsHandled)
                {
                    throw new InvalidOperationException(new StringBuilder()
                                                        .Append("The refresh token was not correctly processed. This may indicate ")
                                                        .Append("that the event handler responsible of generating refresh tokens ")
                                                        .Append("was not registered or was explicitly removed from the handlers list.")
                                                        .ToString());
                }

                context.Response.RefreshToken = notification.Token;
            }
 public override async Task SerializeRefreshToken(SerializeRefreshTokenContext context)
 {
     await StoreRefreshToken(context);
 }
 public Task SerializeRefreshToken(SerializeRefreshTokenContext context)
 {
     throw new NotImplementedException();
 }
示例#11
0
        public override async Task SerializeRefreshToken(SerializeRefreshTokenContext context)
        {
            context.RefreshToken = await context.SerializeTicketAsync();

            await StoreRefreshToken(context);
        }