身份服务器 4 在部署到生产环境时收到连接/令牌端点"invalid_grant"错误



我使用Identityserver4来实现OAUTH2,服务器支持ResourceOwnerPasswordcode流。我使用AWS的EC2来托管用于生产的应用程序。

奇怪的是,即使应用程序在我的开发机器上运行得很好,在部署到AWS后,我一直得到这个invalid_grant,我不知道出了什么问题。

这是我的代码:

services.AddIdentityServer()
//.AddDeveloperSigningCredential()
.AddSigningCredential(Certificate.GetCertificate())
.AddInMemoryIdentityResources(Config.GetIdentityResources())
.AddInMemoryApiResources(Config.GetApiResources())
.AddInMemoryClients(Config.GetClients())
.AddTestUsers(Config.GetUsers());
new Client
{
ClientId = "client",
ClientName = "client",
ClientSecrets =
{
new Secret("secret".Sha256())
},
RequireClientSecret = false,
RedirectUris = new List<string>(new string[] { "https://www.getpostman.com/oauth2/callback", "http://localhost:8002", "http://192.168.1.5:8002","app.buyingagent:/oauthredirect"}),
AllowedGrantTypes = GrantTypes.Code,
//RequirePkce = true,
AllowedScopes = { "api" },
AllowOfflineAccess = true
}
public static X509Certificate2 GetCertificate()
{
using (var store = new X509Store(StoreName.Root, StoreLocation.LocalMachine))
{
store.Open(OpenFlags.OpenExistingOnly);
var certs = store.Certificates.Find(X509FindType.FindBySubjectName, "cert", false);
return certs.Count > 0 ? certs[0] : null;
}
}

我知道把信息保存在内存中不是一个好的做法,但我只想先得到概念的证明。对于传递给AddSigningCredential用于签名令牌的x509 certificate,我使用makecert在本地机器中创建了一个自唱证书,然后通过RDP将其导出到AWS中的可信存储。(makecert在AWS的命令行中似乎不可用)

我使用了以下命令:makecert -pe -ss MY -$ individual -n "CN=cert" -len 2048 -r

该应用程序在本地运行find,但在生产中,我一直收到这个"invalid_grant"错误。(我使用Postman获取令牌)我可以访问connect/authorize端点(在那里我可以输入客户端id和密码)

流在connect/authorize终点失败。

错误消息如下:

POST http://{url}/connect/token
Request Headers:
undefined:undefined
Request Body:
grant_type:"authorization_code"
code:"7cb58d345975af02332f2b67cb71958ba0a48c391e34edabd0d9dd1500e3f24e"
redirect_uri:"https://www.getpostman.com/oauth2/callback"
client_id:"client"
Response Headers:
undefined:undefined
Response Body:
error:"invalid_grant"
invalid_grant
Error

我知道输入的信息(客户端id、重定向url)都是正确的(在本地都能正常工作),一旦部署到生产中,这里会出现什么问题?证书在生产中是否不受信任,或者我无法使用客户端和资源的内存存储?我不认为这是由于redirect_url,因为即使我使用甚至不需要redirect_urlpassword流,它在生产中仍然失败。

注意:如果删除这一行AddSigningCredential(Certificate.GetCertificate())(不向identityserver4传递证书),我将获得相同的"invalid_grant。所以,也许从我的开发机器导入到AWS的证书是无效的?

打开日志后,问题是keyset does not exist应用程序无权读取证书中的私钥。添加权限后,问题就解决了。最初的invalid_grant是如此误导。。。

当我以无穷的智慧将accessToken的到期时间设置为refreshToken的到期时间,并且只有在access到期时才要求refresh时,我就遇到了这个问题。

最新更新