我想在Asp核心2.0中使用JwtBearerAuthentication,我遇到了兩個主要問題。ASP核心2.0 JwtBearerAuthentication不工作
啓動的配置方法是這樣的:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
{
HotModuleReplacement = true
});
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseTestSensitiveConfiguration(null);
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
routes.MapSpaFallbackRoute(
name: "spa-fallback",
defaults: new { controller = "Home", action = "Index" });
});
}
和像波紋管的ConfigureServices:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver())
.AddJsonOptions(options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);
services.AddDbContext<FGWAContext>(options => options.UseSqlServer(connection));
services.AddIdentity<User, Role>()
.AddEntityFrameworkStores<FGWAContext>()
.AddDefaultTokenProviders();
services.Configure<IdentityOptions>(options =>
{
// Password settings
options.Password.RequireDigit = false;
options.Password.RequiredLength = 4;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = false;
options.Password.RequireLowercase = false;
// Lockout settings
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
options.Lockout.MaxFailedAccessAttempts = 10;
// User settings
options.User.RequireUniqueEmail = true;
});
//// If you want to tweak Identity cookies, they're no longer part of IdentityOptions.
//services.ConfigureApplicationCookie(options => options.LoginPath = "/Account/LogIn");
//services.AddAuthentication();
//// If you don't want the cookie to be automatically authenticated and assigned to HttpContext.User,
//// remove the CookieAuthenticationDefaults.AuthenticationScheme parameter passed to AddAuthentication.
//services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
// .AddCookie(options =>
// {
// options.LoginPath = "/Account/LogIn";
// options.LogoutPath = "/Account/LogOff";
// });
//services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
// .AddJwtBearer(jwtBearerOptions =>
// {
// //jwtBearerOptions.Events.OnChallenge = context =>
// //{
// // context.Response.Headers["Location"] = context.Request.Path.Value;
// // context.Response.StatusCode = 401;
// // return Task.CompletedTask;
// //};
// jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters
// {
// ValidateIssuerSigningKey = true,
// IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your secret goes here")),
// ValidateIssuer = true,
// ValidIssuer = "The name of the issuer",
// ValidateAudience = true,
// ValidAudience = "The name of the audience",
// ValidateLifetime = true, //validate the expiration and not before values in the token
// ClockSkew = TimeSpan.FromMinutes(5) //5 minute tolerance for the expiration date
// };
// });
// Enable Dual Authentication
services.AddAuthentication()
.AddCookie(cfg => cfg.SlidingExpiration = true)
.AddJwtBearer(cfg =>
{
cfg.RequireHttpsMetadata = false;
cfg.SaveToken = true;
cfg.TokenValidationParameters = new TokenValidationParameters()
{
ValidIssuer = Configuration["Tokens:Issuer"],
ValidAudience = Configuration["Tokens:Issuer"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Tokens:Key"]))
};
});
services.AddTransient<IModelsService, ModelsService>();
services.AddTransient<IRestaurantService, RestaurantService>();
}
和兩個主要問題:
1 - 它不工作!我所說的方法生成令牌http://localhost:59699/api/accountapi/login
的答案是這樣的:
{"access_token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJmb29kdGVzdGdldHVzckBnbWFpbC5jb20iLCJqdGkiOiIyZGQ0MDhkNy02NDE4LTQ2MGItYTUxYi1hNTYzN2Q0YWYyYzgiLCJpYXQiOiIxMC8xMi8yMDE3IDM6NDA6MDYgQU0iLCJuYmYiOjE1MDc3Nzk2MDYsImV4cCI6MTUwNzc3OTkwNiwiaXNzIjoiRXhhbXBsZUlzc3VlciIsImF1ZCI6IkV4YW1wbGVBdWRpZW5jZSJ9.of-kTEIG8bOoPfyCQjuP7s6Zm32yFFPlW_T61OT8Hqs","expires_in":300}
那麼我所說的保護資源是這樣的:
,但受保護的資源不可訪問。
2-未通過身份驗證後,會將請求重定向到登錄頁面。我怎樣才能禁用這種自動挑戰行爲?
在你開始回答之前,我必須告訴你,我已經試過https://wildermuth.com/2017/08/19/Two-AuthorizationSchemes-in-ASP-NET-Core-2來驗證身份,這也是https://docs.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/identity-2x;而且這ASP.NET Core 2.0 disable automatic challenge禁用自動挑戰,但他們沒有工作。
任何想法和線索是受歡迎的。提前致謝。 TG。
// ***** UPDATE 1 所需的配置是在webapi調用中使用jwtbearerauthentication,其他人使用cookie。然後,在使用前者時,我想對未授權的請求返回未授權(401)響應,而對於後者,我想要重定向。
我真的很困惑這個問題。任何關於我的錯誤的暗示都會對我非常有幫助。