[英]Blazor Web Assembly Hosted - Bearer error=“invalid_token”, error_description=“The signature key was not found”
[英]ASP.NET Core WebAPI: Bearer error="invalid_token", error_description="The signature key was not found"
我正在構建 ASP .NET Core WebAPI 應用程序並嘗試為我的應用程序提供令牌身份驗證:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services
.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer("Bearer", jwtBearerOptions =>
{
jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters
{
//ValidIssuer = "Issuer"
ValidateIssuer = false,
////ValidAudience = "WishlistAppClient",
//ValidateAudience = false,
////ClockSkew = TimeSpan.FromSeconds(5),
//ValidateLifetime = false,
//RequireExpirationTime = false,
//RequireSignedTokens = false,
};
});
services.AddMvc().AddJsonOptions(options =>
{
options.SerializerSettings.ContractResolver = new DefaultContractResolver()
{
NamingStrategy = new SnakeCaseNamingStrategy()
};
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
services.AddDbContext<SchemaContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection"), optionBuilder => optionBuilder.MigrationsAssembly("EventManager.DAL")
));
new DALRegistration().ConfigureServices(services);
var mappingConfig = new MapperConfiguration(configuration =>
{
configuration.AddProfile(new MappingProfile());
});
IMapper mapper = mappingConfig.CreateMapper();
services.AddSingleton(mapper);
services
.AddIdentity<SystemUser, SystemRole>()
.AddEntityFrameworkStores<SchemaContext>()
.AddDefaultTokenProviders();
services.AddScoped<IUserManager, UserManager>();
services.AddScoped<ILoginProvider, LoginProvider>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/dist";
});
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
c.DescribeAllEnumsAsStrings();
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");
});
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSpaStaticFiles();
var todayDate = DateTime.Now.ToShortDateString().Replace('/', '.');
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
c.DocExpansion(DocExpansion.None);
});
loggerFactory.AddFile(Path.Combine(Directory.GetCurrentDirectory(), "LogInformation", $"{DateTime.Now.ToShortDateString().Replace('/','.')}.txt"));
var logger = loggerFactory.CreateLogger("New Logger");
app.Use(async (context, next) =>
{
logger.LogTrace("Processing request {0}", context.Request.Path);
await next.Invoke();
});
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
spa.Options.StartupTimeout = new TimeSpan(0, 2, 0);
if (env.IsDevelopment())
{
spa.UseAngularCliServer(npmScript: "start");
}
});
}
}
API 代碼受 [Authorize(AuthenticationSchemes = "Bearer")] 保護 當我使用任何令牌發送請求時,我總是收到 401。問題是,我關閉了所有令牌驗證,但這沒有幫助。
Postman里面有一張請求圖片
響應正文為空。 響應標頭(如果您無法加載圖像):
要求:
這是我如何實施的示例
services.AddAuthentication()
.AddCookie()
.AddJwtBearer(cfg =>
{
cfg.TokenValidationParameters = new TokenValidationParameters()
{
ValidIssuer = Configuration["Tokens:Issuer"],
ValidAudience = Configuration["Tokens:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Tokens:Key"]))
};
});
在控制器上,類似於你的
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
在身份驗證控制器中,它由具有憑據的登錄頁面調用。 檢查用戶名和密碼是否正確后,您必須執行以下代碼
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, user.Email),
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
_config["Tokens:Issuer"],
_config["Tokens:Audience"],
claims,
expires: DateTime.Now.AddMinutes(30),
signingCredentials: creds);
var results = new
{
token = new JwtSecurityTokenHandler().WriteToken(token),
expiration = token.ValidTo
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.