public async Task <TokenResponse> GetTokenAsync( string grandType, string code, string userName, string password, string oldRefreshTokenValue, string ipAddress, string userAgent, List <string> clientScopes, string audience, CancellationToken ct) { switch (grandType) { case GrandType.AuthorizationCode: { var profileWithClaims = _codesService.Get(code); if (profileWithClaims == null) { return(new TokenResponse("Invalid code")); } var accessToken = _accessTokensService.Create(audience, profileWithClaims.Claims); var refreshToken = await _refreshTokensService.CreateAsync(profileWithClaims.Claims, profileWithClaims.Profile, ipAddress, userAgent, ct); return(new TokenResponse(accessToken, refreshToken)); } case GrandType.Password: { var identityTypes = new[] { IdentityType.LoginAndPassword }; var identity = await _identitiesService.GetVerifiedByKeyAndTypesAsync(userName, identityTypes, ct); if (identity == null) { return(new TokenResponse("Invalid credentials")); } var profile = await _profilesService.GetAsync(identity.ProfileId, ct); if (profile == null) { return(new TokenResponse("Invalid credentials")); } var isPasswordCorrect = _identitiesService.IsPasswordCorrect(identity, password); if (!isPasswordCorrect) { return(new TokenResponse("Invalid credentials")); } var claims = await _claimsService.GetByScopesAsync(clientScopes, profile, ct); var accessToken = _accessTokensService.Create(audience, claims); var refreshToken = await _refreshTokensService.CreateAsync(claims, profile, ipAddress, userAgent, ct); return(new TokenResponse(accessToken, refreshToken)); } case GrandType.RefreshToken: { var oldRefreshToken = await _refreshTokensService.GetByValueAsync(oldRefreshTokenValue, ct); if (oldRefreshToken == null) { return(new TokenResponse("Invalid refresh token")); } if (oldRefreshToken.ExpirationDateTime < DateTime.UtcNow) { return(new TokenResponse("Refresh token is expired")); } await _refreshTokensService.SetExpiredAsync(oldRefreshToken.Id, ct); var profile = await _profilesService.GetAsync(oldRefreshToken.ProfileId, ct); if (profile == null) { return(new TokenResponse("Invalid refresh token")); } var claims = await _claimsService.GetByRefreshTokenAsync(oldRefreshToken, profile, ct); var accessToken = _accessTokensService.Create(audience, claims); var refreshToken = await _refreshTokensService.CreateAsync(claims, profile, ipAddress, userAgent, ct); return(new TokenResponse(accessToken, refreshToken)); } default: return(new TokenResponse("Invalid grand type")); } }