[英]How Jwt token issued by IdentiyServer is validate in Web Api Application
I am using IdentiyServer to issue a JWT Token to a client, token contains role claims and some other claims, this part works fine, I get the the access token with desired claims.我正在使用 IdentiyServer 向客户端发出 JWT 令牌,令牌包含角色声明和其他一些声明,这部分工作正常,我得到了带有所需声明的访问令牌。
And in my web API application I have added the following code to support JWT authentication:在我的 web API 应用程序中,我添加了以下代码以支持 JWT 身份验证:
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.RequireHttpsMetadata = false;
options.Authority = "http://localhost:5004";
IdentityModelEventSource.ShowPII = true;
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidateAudience = false,
ValidateIssuer = false,
ValidateLifetime = false,
ValidateIssuerSigningKey = true,
IssuerSigningKey = "what is this ?"
};
The question is, suppose a hacker generates a JWT token with whatever header and body and claims he wants and signs it, how does my web api application validate the signature? The question is, suppose a hacker generates a JWT token with whatever header and body and claims he wants and signs it, how does my web api application validate the signature? How can I share IssuerSigningKey with identityServer and my web api application?
如何与 identityServer 和我的 web api 应用程序共享 IssuerSigningKey?
Is IssuerSigningKey the same as ClientSecrets in identityServer? IssuerSigningKey 是否与 IdentityServer 中的 ClientSecrets 相同?
I have gone through IdentityServer documentation, but couldn't find an answer.我浏览了 IdentityServer 文档,但找不到答案。
While a hacker can certainly generate a bogus JWT with some header and claims, he cannot sign the token using the server's private key, unless he also hacks your server to steal the key.虽然黑客当然可以生成伪造的 JWT 和一些 header 并声称,但他无法使用服务器的私钥签署令牌,除非他还入侵您的服务器以窃取密钥。 So, in practice, a JWT usually bears a checksum at the end of the token, which is a hash based on the token's content and the server key.
因此,在实践中,JWT 通常在令牌末尾带有校验和,即基于令牌内容和服务器密钥的 hash。 If your server receives an incoming JWT and the checksum does not validate, then it should reject that JWT.
如果您的服务器收到传入的 JWT 并且校验和未验证,那么它应该拒绝该 JWT。
When you use AddJwtBearer, it will download the public signing key from your IdentityServer (http://localhost:5004) and use this public key to verify that the signature in the received JWT token was issued by the expected issuer.当您使用 AddJwtBearer 时,它将从您的 IdentityServer (http://localhost:5004) 下载公共签名密钥,并使用此公共密钥来验证收到的 JWT 令牌中的签名是否由预期的颁发者颁发。 AddJwtBearer will refresh the downloaded public key every 24 hours by default.
AddJwtBearer 默认每 24 小时刷新一次下载的公钥。
IssuerSigningKey you do not need to set in the API.您不需要在 API 中设置 IssuerSigningKey。 In general you should disable as few checks as possible in he TokenValidationParameters object.
一般来说,您应该在 TokenValidationParameters object 中禁用尽可能少的检查。
In production you should try to set ShowPII to false, because otherwise things like tokens and other secrets might end up in the logs.在生产环境中,您应该尝试将 ShowPII 设置为 false,否则令牌和其他机密等内容可能最终会出现在日志中。
Is IssuerSigningKey the same as ClientSecrets in identityServer?
IssuerSigningKey 是否与 IdentityServer 中的 ClientSecrets 相同?
No, they are two separate things.不,它们是两个不同的东西。 ClientSecret is like a password for the client, when it authenticates against IdentityServer.
ClientSecret 就像客户端的密码,当它针对 IdentityServer 进行身份验证时。
SigningKey you set in IdentityServer and it represents the public/private siging key.您在 IdentityServer 中设置的 SigningKey 代表公钥/私钥签名密钥。 The key can either be an RSA or ECDSA key.
密钥可以是 RSA 或 ECDSA 密钥。
In the question as it seems, that complete OAuth flow using an OAuth or Open Id server is not very clear, let's consider various questions and options.在看起来的问题中,使用 OAuth 或 Open Id 服务器的完整 OAuth 流程不是很清楚,让我们考虑各种问题和选项。
I am using IdentiyServer to issue a JWT Token to a client, token contains role claims and some other claims, this part works fine, I get the the access token with desired claims.
我正在使用 IdentiyServer 向客户端发出 JWT 令牌,令牌包含角色声明和其他一些声明,这部分工作正常,我得到了带有所需声明的访问令牌。
Let's segregate the Authentication server from Authorization, generally when we integrate any of the social logins, what they do is provide an access token and we use callback to generate a JWT Authroization token at our server, which we control like Backend server让我们将身份验证服务器与授权分开,通常当我们集成任何社交登录时,它们所做的是提供访问令牌,我们使用回调在我们的服务器上生成 JWT 授权令牌,我们像后端服务器一样控制它
What's the difference between two?
两者有什么区别?
Authentication server generally know very few details about us, mostly they just verify email and return success, they have no ability to assign roles and other details, which vary from application to application认证服务器一般对我们了解的很少,大多只是验证 email 并返回成功,无法分配角色等细节,因应用而异
What shall we do then?
那我们该怎么办?
Receive Access Token, fetch details like email from it, fetch all details related to that email, create a json payload, use an algorithm with either Symmetric (only one key) or Asymmetric encryption (generate private public key pair), check this video to know details about JWT with much more clarity.接收访问令牌,从中获取诸如 email 之类的详细信息,获取与该email相关的所有详细信息,创建 json 有效负载,或使用对称加密算法与对称公钥(仅一个)更清楚地了解有关 JWT 的详细信息。 In Symmetric encryption we use same key to encode / decode, while in Asymmetric encryption we encode using private key and decode using public key.
在对称加密中,我们使用相同的密钥进行编码/解码,而在非对称加密中,我们使用私钥进行编码并使用公钥进行解码。 As you would check In JWT encoding and decoding simply means hashing
header.payload
and comparing the two to ensure no tampering正如您将在 JWT 中检查的那样,编码和解码只是意味着散列
header.payload
并比较两者以确保没有篡改
Remaining questions regarding type of encryption and hacker:
关于加密类型和黑客的剩余问题:
header.jsonpayload
header.jsonpayload
ASP.Net Web API Specific Changes
ASP.Net Web API 具体改动
I code in Python using Fast API, what we do is use a middleware
, which is similar to interceptor / filter in Asp.Net, which will intercept all the calls to the controller / api, fetch the token, decode, verify and allow the call to continue or throw an error to relogin, please note encoding happens in the callback
from the authentication server. I code in Python using Fast API, what we do is use a
middleware
, which is similar to interceptor / filter in Asp.Net, which will intercept all the calls to the controller / api, fetch the token, decode, verify and allow the调用以继续或抛出错误以重新登录,请注意编码发生在来自身份验证服务器的callback
中。 A sample code in Python, https://pyjwt.readthedocs.io/en/latest/usage.html Python、 https://pyjwt.readthedocs.io/en/latest/usage.html中的示例代码
For C# this link is a good option, https://www.c-sharpcorner.com/article/asp-net-web-api-2-creating-and-validating-jwt-json-web-token/对于 C# 这个链接是一个不错的选择, https://www.c-sharpcorner.com/article/asp-net-web-api-2-creating-and-validating-jwt-json-web-token/
Here as you can see the code, where explicit Filter is added to verify the token.在这里您可以看到代码,其中添加了显式过滤器以验证令牌。 It use a decorator,
[Authorize]
to invoke the authorization filter它使用装饰器
[Authorize]
来调用授权过滤器
public static void Register(HttpConfiguration config) {
// Web API configuration and services
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new {
id = RouteParameter.Optional
}
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.