问题描述
当我从我的 Angular 应用程序向我的 .Net Core 2 API 发出请求时,JWT 与请求标头中发送的不同.
When I make a request to my .Net Core 2 API from my Angular app the JWT is not the same as the one sent in the request header.
Startup.cs
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
_config = builder.Build();
}
IConfigurationRoot _config;
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton(_config);
services.AddDbContext<ApplicationDbContext>(ServiceLifetime.Transient);
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
services.AddSingleton<IUserTwoFactorTokenProvider<ApplicationUser>, DataProtectorTokenProvider<ApplicationUser>>();
// Add application services.
// Add application repositories.
// Add options.
services.AddOptions();
services.Configure<StorageAccountOptions>(_config.GetSection("StorageAccount"));
// Add other.
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddTransient<ApiExceptionFilter>();
// this makes "this.User" reflect the properties of the jwt sent in the request
services.AddTransient<ClaimsPrincipal>(s => s.GetService<IHttpContextAccessor>().HttpContext.User);
services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
// set password complexity requirements
options.Password.RequireDigit = true;
options.Password.RequireLowercase = true;
options.Password.RequireUppercase = false;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequiredLength = 6;
options.Tokens.ProviderMap.Add("Default",
new TokenProviderDescriptor(typeof(IUserTwoFactorTokenProvider<ApplicationUser>)));
}).AddEntityFrameworkStores<ApplicationDbContext>();
services.AddAuthentication(options =>
{
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(config =>
{
config.RequireHttpsMetadata = false;
config.SaveToken = true;
config.TokenValidationParameters = new TokenValidationParameters()
{
ValidIssuer = _config["Tokens:Issuer"],
ValidAudience = _config["Tokens:Audience"],
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"])),
ValidateLifetime = true
};
});
services.AddAuthorization(config =>
{
config.AddPolicy("Subscribers", p => p.RequireClaim("Subscriber", "True"));
config.AddPolicy("Artists", p => p.RequireClaim("Artist", "True"));
config.AddPolicy("Admins", p => p.RequireClaim("Admin", "True"));
});
services.Configure<DataProtectionTokenProviderOptions>(o =>
{
o.Name = "Default";
o.TokenLifespan = TimeSpan.FromHours(1);
});
services.Configure<AuthMessageSenderOptions>(_config);
// Add framework services.
services.AddMvc(opt =>
{
//opt.Filters.Add(new RequireHttpsAttribute());
}
).AddJsonOptions(opt =>
{
opt.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(_config.GetSection("Logging"));
loggerFactory.AddDebug();
app.Use(async (context, next) =>
{
// just to check the context.User.Claims on request
var temp = context;
await next();
});
app.UseAuthentication();
app.UseMvc();
}
}
这是颁发令牌的地方(在应用登录时)
This is where the token gets issued (on app login)
AuthController.cs
private async Task<IList<Claim>> CreateUserClaims(ApplicationUser user)
{
var userClaims = await _userManager.GetClaimsAsync(user);
var newClaims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.NameId, user.Id)
}.Union(userClaims).ToList();
return newClaims;
}
private Object CreateToken(IList<Claim> claims)
{
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: _config["Tokens:Issuer"],
audience: _config["Tokens:Audience"],
claims: claims,
expires: DateTime.UtcNow.AddDays(29),
signingCredentials: creds
);
return new
{
token = new JwtSecurityTokenHandler().WriteToken(token),
expiration = token.ValidTo
};
}
private async Task<Object> CreateToken(ApplicationUser user)
{
var claims = await CreateUserClaims(user);
var token = CreateToken(claims);
return token;
}
[HttpPost("token")]
[AllowAnonymous]
public async Task<IActionResult> CreateToken([FromBody] CredentialModel model)
{
var user = await _userManager.FindByNameAsync(model.UserName);
if (user != null)
{
if (_hasher.VerifyHashedPassword(user, user.PasswordHash, model.Password)
== PasswordVerificationResult.Success)
{
var token = await CreateToken(user);
return Ok(token);
}
}
throw new ApiException("Bad email or password.");
}
我已通过 Chrome 调试器网络选项卡确认我的请求中的 JWT 是我希望 API 获取的 JWT.
I have confirmed through the Chrome debugger Network tab that the JWT in my request is the JWT I want the API to get.
因此,我将在这篇文章中保留 Angular 请求代码.
这是一个通过 UserId 返回项目的控制器
Here is a Controller that returns items by UserId
[HttpGet]
public async Task<IActionResult> Get()
{
var artists = await _manageArtistService.GetAllByUser(this.User);
if (artists == null) return NotFound($"Artists could not be found");
return Ok(artists);
}
这是控制器调用的服务
public async Task<IEnumerable<ManageArtistView>> GetAllByUser(ClaimsPrincipal user)
{
// gets all artists of a given user, sorted by artist
var userId = _userService.GetUserId(user);
var artists = await _manageArtistRepository.GetAllByUser(userId);
return artists;
}
在 UserService.cs
中,我尝试了几种访问当前用户的不同方法.我检查了从控制器传递的 this.User
.
In the UserService.cs
I have attempted a few different means of accessing the current user. I check the this.User
that was passed from the Controller.
我还在 _context
中检查当前上下文 - 您可以在 Startup.cs
中看到一个单例.
I also check the current context in _context
- a Singleton you can see in the Startup.cs
.
还有 _caller
来自 Startup.cs
services.AddTransient<ClaimsPrincipal>(s => s.GetService<IHttpContextAccessor>().HttpContext.User);
当我检查任何这些变量时,Claims
对象不包含与请求期间发送的 JWT 相同的声明.
When I inspect any of those variables, the Claims
object does not contain the same claims as the JWT that was sent during the request.
我已通过检查 jwt.io 上的声明验证声明不匹配.
I have verified the claims do not match by checking the claims at jwt.io.
具体来说,我给出一个场景:
To be specific, I'll give a scenario:
我使用电子邮件 user@example.com
登录我的应用程序.然后,该电子邮件在 AuthController.cs
的 CreateUserClaims()
函数中设置为声明 (Sub) 为 user.UserName
::p>
I sign into my app with email user@example.com
. That email is then set as a claim (Sub) as user.UserName
inside the CreateUserClaims()
function in the AuthController.cs
:
var newClaims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.NameId, user.Id)
}.Union(userClaims).ToList();
然后设置一些其他属性,最终将令牌返回给客户端.客户端将其存储在 localStorage
中.
Then some other properties are set and eventually the token is returned to the client. The client stores it in localStorage
.
然后客户端发出请求,包括标头中的 JWT,并将其添加到请求选项中,如下所示(Angular 服务):
The client then makes a request, including the JWT in the header and adds it to the request options like this (Angular service):
private headers = new Headers(
{
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + this.authService.token
});
private options = new RequestOptions({ headers: this.headers });
我在网络"选项卡中检查标题,它包含 JWT - 我在 jwt.io 上检查它看起来不错 - 有正确的电子邮件和其他声明.
I check the Header in the Network tab and it contains the JWT - I check it on jwt.io and it looks good - has the proper email and other claims.
现在我可以退出应用程序,以其他用户身份登录,获取新的 JWT,然后向上面显示的同一控制器发出请求,JWT 将收到之前的电子邮件,而不是我刚刚登录的新用户.
Now I can logout of the app, sign in as a different user, get a new JWT, and make the request to that same controller shown above and the JWT will have the previous email, not the new one that I just signed in as.
我确实进行了相同的检查,检查了网络选项卡上标题中的 JWT,以确保声明包含作为 sub
的新电子邮件以及其他声明.
And I did go through the same checks, checking the JWT in the Header on the Network tab to ensure the claims contain the new email as the sub
as well as the other claims.
这意味着我在新登录时获得了正确的 JWT,但不知何故 API 仍在查看旧的 JWT.
So that means I was issued the proper JWT on the new sign in, but somehow the API is still looking at the old JWT.
这有多疯狂?
我注意到的另一件事是,即使在第一次登录时(假设我刚刚使用 dotnet run
启动 API,然后我向上面显示的同一个控制器发出第一个请求,它也会丢失nameid
声明.我可以去检查在 Header 请求中发送的 JWT,它确实有 nameid
声明. 所以,再次,api 会发出正确的 JWT,但是当我在请求中通过 HTTP 将其发回时,API 的 JWT 与我在请求中发送的不同.
Something else I have noticed is that even on that first login (pretend I just started the API with dotnet run
and then I make my first request to the same controller shown above it will be missing the nameid
claim. I can go check the JWT that was sent in the Header request and it does have the nameid
claim. So, again, the api will issue the proper JWT but when I send it back over HTTP in a request the API does not have the same JWT that I sent in the request.
还有一件事为简单起见,我将 JWT 记录在控制台中.我回去发现我今天早上 9 点开始使用的第一个.它的 jti
与当前在 .net 核心 API 中的相同.现在是下午 4 点 45 分.在这两次(上午 9 点和下午 4 点 45 分)之间,我的控制台中有 9 个不同的 JTW,它们都是从 API 发出的.但该 API 似乎保留了它今天早上创建的第一个 - 即使在我多次停止并启动该项目之后也是如此.
ONE MORE THING
I log the JWT in the console for simplicity. I went back and found the first one I started using today, at 9am. Its jti
is the same as the one that is currently in the .net core API. It's now 4:45pm. I have 9 different JTWs in my console between those two times (9am and 4:45pm), all issued from the API. But the API seems to have kept the first one it created this morning - even after I have stopped and started the project numerous times.
请帮助我理解我做错了什么.我一定没有完全理解 JWT 的处理方式.
Please help me understand what I am doing wrong. I must not be fully understanding how JWTs are handled.
推荐答案
我已经解决了部分问题.
I have figured out part of my problem.
我说来自 UI 的令牌不同于 .net API 接收的令牌是错误的.我说我正在检查网络选项卡中的标题,我是,但不是正确的请求.我的 UI 发送了几个请求——来自不同的 Angular 模块.我在每个模块中注入了一个新的身份验证服务(我的令牌存储在其中).在注销时,模块不会被刷新,因此那些没有保留其旧令牌副本的模块.因此,在登录时,只有受影响的模块(在我的例子中是我的主 app.module.ts
)被刷新.那些没有被触及的保留他们相同的身份验证服务副本.
I was wrong in saying the token coming from the UI was different than what the .net API was receiving. I said I was inspecting the Header in the Network tab, and I was, but just not the correct request. My UI was sending several requests - from different Angular modules. I was injecting a new authentication service (where my token is stored) in each module. On logout, not ever module was getting refreshed, so those that were not kept their old copy of the token. Therefore, upon login, only the affected modules (in my case, my main app.module.ts
) were getting refreshed. The ones that had not been touched kept their same copy of the authentication service.
我从每个模块中删除了注入,并让它们从主 app.module.ts
继承这解决了 UI 和 API 似乎具有不同令牌的问题.
I removed the injection from each module and let them inherit from the main app.module.ts
That fixed the issue of the UI and API appearing to have different tokens.
我提到的另一个无法看到 nameid
声明的问题已部分解决.我在 User
内共有 10 个 Claims
.当我解码 JWT 时,它说我有 sub
和 nameid
.但是,当我在 UserService.cs
中检查 Claims
时,它们并未列为 nameid
和 sub
,而是http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier
和 http://schemas.xmlsoap.org/ws/2005/05/identity/声明/名称标识符
.每个都有正确的 Value
.我不确定这是在哪里或如何发生的.我创建了以下自定义中间件代码,以查看进入时令牌是什么,它具有 Claim
作为 sub
和 nameid
.
The other issue I mentioned of not being able to see the nameid
claim is partially resolved. I have a total of 10 Claims
inside User
. When I decode the JWT it says I have sub
and nameid
. However, when I inspect Claims
in my UserService.cs
they are not listed as nameid
and sub
, but rather http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier
and http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier
. Each have the correct Value
. I am not sure where or how this happens. I created the following custom middleware code to see what the token was when coming in and it has the Claim
as sub
and nameid
.
app.Use(async (context, next) =>
{
var authHeader = context.Request.Headers["Authorization"].ToString();
if (authHeader != null && authHeader.StartsWith("bearer", StringComparison.OrdinalIgnoreCase))
{
var tokenStr = authHeader.Substring("Bearer ".Length).Trim();
System.Console.WriteLine(tokenStr);
var handler = new JwtSecurityTokenHandler();
var token = handler.ReadToken(tokenStr) as JwtSecurityToken;
var nameid = token.Claims.First(claim => claim.Type == "nameid").Value;
var identity = new ClaimsIdentity(token.Claims);
context.User = new ClaimsPrincipal(identity);
}
await next();
});
所以,变量 nameid
是正确的并且包含预期值.Type
正在从 nameid
和 sub
更改为 http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier
So, the variable nameid
is right and contains the expected value. Somewhere along the line the Type
is changing from nameid
and sub
to http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier
这篇关于Request Header 中的 JWT 在接收 .Net Core API 时不一样的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!