一、IS4服務端配置
1、配置Client
new Client { ClientId = "xamarin", ClientSecrets = { new Secret("secret".Sha256()) }, AccessTokenLifetime = 1800,//設置AccessToken過期時間 AllowedGrantTypes = GrantTypes.ResourceOwnerPassword, RefreshTokenExpiration = TokenExpiration.Absolute, AbsoluteRefreshTokenLifetime = 3600, AllowOfflineAccess = true,//如果要獲取refresh_tokens ,必須把AllowOfflineAccess設置爲true AllowedScopes = new List<string> { "api", StandardScopes.OfflineAccess, //如果要獲取refresh_tokens ,必須在scopes中加上OfflineAccess StandardScopes.OpenId,//如果要獲取id_token,必須在scopes中加上OpenId和Profile,id_token需要通過refresh_tokens獲取AccessToken的時候才能拿到(還未找到原因) StandardScopes.Profile//如果要獲取id_token,必須在scopes中加上OpenId和Profile } }
2、實現IResourceOwnerPasswordValidator接口,自定義用戶登錄
public class ResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator { public Task ValidateAsync(ResourceOwnerPasswordValidationContext context) { //根據context.UserName和context.Password與數據庫的數據做校驗,判斷是否合法 if (context.UserName == "test" && context.Password == "test") { context.Result = new GrantValidationResult( subject: context.UserName, authenticationMethod: OidcConstants.AuthenticationMethods.Password); } else { //驗證失敗 context.Result = new GrantValidationResult( TokenRequestErrors.InvalidGrant, "invalid custom credential" ); } return Task.FromResult(0); } }
3、在Startup中加入如下配置
services.AddIdentityServer() .AddDeveloperSigningCredential() .AddInMemoryApiResources(Config.GetApis()) .AddInMemoryIdentityResources(Config.GetIdentityResources()) .AddInMemoryClients(Config.GetClients()) .AddProfileService<ProfileService>() .AddResourceOwnerValidator<ResourceOwnerPasswordValidatorService>();//注入自定義用戶登錄驗證
二、客戶端獲取access_token+refresh_token
如果是後臺代碼需要獲取access_token+refresh_token,則可以參考官方Samples,https://github.com/IdentityServer/IdentityServer4.Samples/tree/release/Clients/src/ConsoleResourceOwnerFlowRefreshToken
如果是前端需要獲取access_token+refresh_token,則可以通過 http://localhost:5000/connect/token 接口獲取
1、獲取access_token+refresh_token
獲取access_token+refresh_token的參數配置如下,Content-Type的值是 application/x-www-form-urlencoded
2、通過第一步獲取到的refresh_token去刷新access_token
注意:
- grant_type改爲refresh_token,表明刷新token
- username與password不需要帶了
- 添加參數refresh_token,值爲獲取accecc_token時的refresh_token值
原文地址:https://www.wandouip.com/t5i43236/