コード例 #1
0
        protected OAuthTokenResponse GenerateTokenResponse(string username, string deviceId)
        {
            // Construct an identity
            var claims = Context.Services.UserService.GetUserClaims(username);

            var identity = new ClaimsIdentity("OAuth");

            identity.AddClaim(new Claim(ClaimTypes.Name, username));
            identity.AddClaim(new Claim(OAuth.ClaimTypes.Realm, Context.Realm));

            if (!deviceId.IsNullOrWhiteSpace())
            {
                identity.AddClaim(new Claim(OAuth.ClaimTypes.DeviceId, deviceId));
            }

            identity.AddClaims(claims);

            var response = new OAuthTokenResponse
            {
                access_token = Context.Services.TokenService.GenerateToken(identity, Context.Options.AccessTokenLifeTime),
                token_type   = "bearer",
                expires_in   = Context.Options.AccessTokenLifeTime * 60
            };

            // If we have a token store, create a refresh token
            if (Context.Services.RefreshTokenStore != null)
            {
                var refreshTokenId       = Guid.NewGuid().ToString("n");
                var refreshTokenLifeTime = Client?.RefreshTokenLifeTime ?? Context.Options.RefreshTokenLifeTime;

                var token = new OAuthRefreshToken
                {
                    Key             = refreshTokenId.GenerateHash(),
                    Subject         = username,
                    UserType        = Context.Services.UserService.UserType,
                    Realm           = Context.Realm,
                    ClientId        = Client != null ? Client.ClientId : OAuth.DefaultClientId,
                    DeviceId        = deviceId.IsNullOrWhiteSpace() ? null : deviceId,
                    IssuedUtc       = DateTime.UtcNow,
                    ExpiresUtc      = DateTime.UtcNow.AddMinutes(refreshTokenLifeTime),
                    ProtectedTicket = response.SerializeToJson().Encrypt(Context.Options.SymmetricKey)
                };

                Context.Services.RefreshTokenStore.AddRefreshToken(token);

                response.refresh_token = refreshTokenId;
            }

            return(response);
        }