簡體   English   中英

ASP.Net Core 3.0 JWT Bearer Token 沒有可用的 SecurityTokenValidator

[英]ASP.Net Core 3.0 JWT Bearer Token No SecurityTokenValidator available

我使用 ASP.Net Core 3.0 API 和 EntityFramework Core 作為 UserStorage。 啟動.cs:

        public void ConfigureServices(IServiceCollection services)
            {
             using Microsoft.AspNetCore.Authentication.JwtBearer;
             using Microsoft.AspNetCore.Builder;
             using Microsoft.AspNetCore.Hosting;
             using Microsoft.AspNetCore.Identity;
             using Microsoft.AspNetCore.SpaServices.AngularCli;
             using Microsoft.EntityFrameworkCore;
             using Microsoft.Extensions.Configuration;
             using Microsoft.Extensions.DependencyInjection;
             using Microsoft.Extensions.Hosting;
             using Microsoft.IdentityModel.Tokens;
             using System;
             using System.Collections.Generic;
             using System.Linq;
             using System.Text;
             using System.Threading.Tasks;
                .
                .
                .

                //Add Identity Provider with EntityFramework
                services.AddIdentity<User, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDBContext>()
                .AddDefaultTokenProviders();

                //Initialize EntityFramework
                services.AddDbContext<ApplicationDBContext>(options => options.UseSqlite(Configuration.GetConnectionString("localDB")));

                //Initialize JWT Authentication
                services.AddAuthentication(options => {
                    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                }).AddJwtBearer(jwtBearerOptions =>
                {
                    jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters()
                    {
                        ValidateIssuer = true,
                        ValidateAudience = true,
                        ValidateLifetime = true,
                        ValidateIssuerSigningKey = true,

                        ValidIssuer = "http://localhost:44352",
                        ValidAudience = "http://localhost:44352",
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration.GetSection("Secrets")["jwt"]))
                    };
                }
                );
                services.AddMvc(options => options.EnableEndpointRouting = false)
                    .AddNewtonsoftJson();

                // In production, the Angular files will be served from this directory
                services.AddSpaStaticFiles(configuration =>
                {
                    configuration.RootPath = "ClientApp/dist";
                });
            }

            .
            .
            .


                app.UseHttpsRedirection();
                app.UseStaticFiles();
                app.UseSpaStaticFiles();

                //Enable Authentication
                app.UseAuthentication();
                app.UseAuthorization();

                .
                .
                .

                app.UseMvc(routes =>
                {
                    routes.MapRoute(
                        name: "default",
                        template: "{controller}/{action=Index}/{id?}");
                });


    .
    .
    .

這是我發出 JWT 令牌的代碼:


public async Task<IActionResult> Login()
        {
            using (var reader = new StreamReader(Request.Body))
            {
                var body = await reader.ReadToEndAsync();
                var cred = JsonConvert.DeserializeObject<Credentials>(body);
                var result = (await userService.LoginUser(cred.userName, cred.password));
                if (result == 200)
                {

                    var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration.GetSection("Secrets")["jwt"]));
                    var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256Signature);

                    var roles = await userService.GetRoleFromUsername(cred.userName);
                    var rolesString = JsonConvert.SerializeObject(roles);

                    var tokeOptions = new JwtSecurityToken(
                                issuer: "http://localhost:44352",
                                audience: "http://localhost:44352",
                                claims: new List<Claim>(new List<Claim> {
                                        new Claim("userName",cred.userName),
                                        new Claim("roles", rolesString)
                                }),
                                expires: DateTime.Now.AddHours(1),
                                signingCredentials: signinCredentials
                    );

這是我使用授權的 API 調用:


[Route("api/videos/add")]
[Authorize(Roles = "Admin")]
[HttpPost]
public async Task<IActionResult> AddVideo()
{
    using (var reader = new StreamReader(Request.Body))
    {
        var body = await reader.ReadToEndAsync();
        var video = JsonConvert.DeserializeObject<Video>(body);
        await videoService.AddVideo(video);
        return Ok();
    }
}

我的 NuGet 包是:

  • Microsoft.EntityFrameworkCore {3.0.0-preview5.19227.1}
  • Microsoft.EntityFrameworkCore.Sqlite {3.0.0-preview5.19227.1}
  • Microsoft.AspNetCore.Authentication.JwtBearer {3.0.0-preview4-19216-03}
  • Microsoft.EntityFrameworkCore.Sqlite.Core {3.0.0-preview5.19227.1}
  • Microsoft.NETCore.Platforms {3.0.0-preview4.19212.13}
  • Microsoft.AspNetCore.Mvc.NewtonsoftJson {3.0.0-preview5-19227-01}
  • Microsoft.AspNetCore.SpaServices.Extensions {3.0.0-preview5-19227-01}
  • Microsoft.AspNetCore.Identity.EntityFrameworkCore {3.0.0-preview5-19227-01}
  • runtime.win-x64.Microsoft.NETCore.DotNetAppHost {3.0.0-preview4-27615-11}

我遇到的問題是,如果我調用該 API 部分,則會收到錯誤消息:

信息:承載未通過身份驗證。 失敗消息:沒有 SecurityTokenValidator 可用於令牌:

任何幫助將不勝感激,因為我找不到錯誤

如果要將角色添加為聲明,請嘗試使用ClaimTypes.Role而不是roles

var tokeOptions = new JwtSecurityToken(
                            issuer: "http://localhost:44352",
                            audience: "http://localhost:44352",
                            claims: new List<Claim>(new List<Claim> {
                                    new Claim("userName",cred.userName),
                                    new Claim(ClaimTypes.Role, "Admin")                                      
                            }),
                            expires: DateTime.Now.AddHours(1),
                            signingCredentials: signinCredentials
                );

感謝鄒興,我找到了錯誤的根源。 問題是我發送了帶引號的不記名令牌。

要求

現在API中的錯誤消失了,問題是現在API中的授權失敗並返回403。

編輯:

我發現了有關錯誤 403 的問題。似乎只允許您在承載令牌中發送一個角色,以便 ASP.Net 對其進行驗證。 userManager.GetRolesAsync 的返回類型表明用戶可以擁有多個角色,這些角色可以包含在 JWT 不記名令牌中。

這意味着我的問題已解決。

我要感謝大家的回答。 沒有你,我不會得到它!

我是這樣處理這個問題的:

client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token.Replace("\"", "")}");

不是最好的解決方案,但它奏效了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM