【发布时间】:2019-01-03 18:16:52
【问题描述】:
我有 ASP.Net MVC 客户端应用程序、API.Net Web API 2 项目和身份服务器 4。我想保护我的 API 免受未经授权的访问,因此我从 IS4 获取 JWT 令牌,然后将标头作为 Bearer 传递调用 API 时的令牌。所有这些工作正常(登录到应用程序,获取 JWT 令牌,然后传递给 API,以便在授权令牌后调用它)。我正在使用 IdentityModel 3.9.0 版本与 Identity server 4 端点进行交互。
我正在尝试从身份服务器 4 获取刷新令牌,这就是问题所在。我无法通过调用授权端点来获取它。我在那里很困惑。下面是我在配置文件中的文件 IS4 GetClients 方法
我使用的是 HybridAndClientCredentials,然后发现使用客户端凭据不支持刷新令牌流。
public static IEnumerable<Client> GetClients()
{
return new List<Client>
{
new Client
{
ClientId = "client",
AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,
AccessTokenLifetime = 1800,
AllowOfflineAccess = true,
// secret for authentication
ClientSecrets =
{
new Secret("secret".Sha256())
},
// scopes that client has access to
AllowedScopes = { "nidhiapi", "offline_access" }
}
};
我刚刚创建了一个基本控制台应用程序来测试我的身份验证服务器,下面是 main 方法中的代码
var discoveryClient = await DiscoveryClient.GetAsync("http://localhost:5000/");
if (discoveryClient.IsError)
{
Console.WriteLine(discoveryClient.Error);
return;
}
// request the token from the Auth server
var tokenClient = new TokenClient(discoveryClient.TokenEndpoint, "client", "secret");
var tokenResponse = await tokenClient.RequestClientCredentialsAsync("nidhiapi");
我能够使用定义的客户端和 HybridClientCredentials 流在 tokenResponse 变量中获取 AccessToken
因为我想从 Authorize 端点获取 RefreshToken。我尝试使用相同的 GetClients 方法更改我的客户端代码
var tokenResponse = await tokenClient.RequestClientCredentialsAsync("offline_access");
使用上面的代码行,我得到一个错误为“Invalid_Scope”。我阅读了它,发现我们需要使用offline_access来获取刷新令牌
另外,我还有一个问题。当我试图找出解决方案时,我想到了使用 AuthorizeEndPoint 创建一个 tokenClient,但除非我验证我的客户端凭据,否则下面的语句是没有用的。
还有一件事:我应该在 RequestRefreshToken 方法中传递什么,因为它需要一个令牌
var authTokenClient = new TokenClient(discoveryClient.AuthorizeEndpoint, "client", "secret");
var refreshTokenResponse = await tokenClient.RequestRefreshTokenAsync("offline_access");
然后我尝试将我的 GetClients 方法更改为仅使用混合流而不使用 HybridClientCredentials,因为我还读到 RefreshToken 流不适用于 ClientCredentials。
其实我现在很困惑。我的要求是从 IS4 获取令牌,然后使用刷新令牌刷新它,这样 MVC 客户端应用程序就不必在到期时登录
请提供建议/解决方案?
【问题讨论】:
-
我认为在使用客户端凭据进行访问时不支持(或不需要)刷新令牌,因为当当前访问令牌过期时,客户端只能使用其凭据来请求新的访问令牌。有关更多信息,请参阅此 SO 问题:stackoverflow.com/questions/29233772/…
标签: c# asp.net-mvc asp.net-mvc-3 identityserver4