示例#1
0
        public async Task CreateAsync(AuthenticationTokenCreateContext context)
        {
            context.AssertNotNull("context");

            var clientId = new ClientId(context.Ticket.Properties.Dictionary[Core.Constants.TokenClientIdKey]);
            var username = new Username(context.Ticket.Identity.Name);

            var refreshTokenLifeTime = context.OwinContext.Get <int>(Core.Constants.TokenRefreshTokenLifeTimeKey);

            if (refreshTokenLifeTime == default(int))
            {
                throw new InvalidOperationException("Refresh token lifetime not found.");
            }

            var refreshToken = await this.tryGetRefreshToken.HandleAsync(
                new TryGetRefreshTokenQuery(clientId, username));

            var now = this.timestampCreator.Now();

            RefreshTokenId refreshTokenId;

            if (refreshToken != null && refreshToken.ExpiresDate > now)
            {
                refreshTokenId = this.encryptionService.DecryptRefreshTokenId(
                    new EncryptedRefreshTokenId(refreshToken.EncryptedId));
            }
            else
            {
                refreshTokenId = RefreshTokenId.Create();

                var issuedDate  = now;
                var expiresDate = issuedDate.AddMinutes(refreshTokenLifeTime);

                context.Ticket.Properties.IssuedUtc  = issuedDate;
                context.Ticket.Properties.ExpiresUtc = expiresDate;

                await this.createRefreshToken.HandleAsync(
                    new SetRefreshTokenCommand(
                        refreshTokenId,
                        clientId,
                        username,
                        context.SerializeTicket(),
                        issuedDate,
                        expiresDate));
            }

            context.SetToken(refreshTokenId.Value);
        }