JWT Bearer Token 不适用于 ASP.Net Core 3.1 + Identity Server 4
JWT Bearer Token not working with ASP.Net Core 3.1 + Identity Server 4
我目前正在尝试为我正在开发的移动应用程序创建一个网络 api。
我决定使用 ASP.Net Core 3.1 和随附的 Indentity Server 来使用 OpenID Connect + PKCE 进行身份验证。
用户将通过 WebView 授权应用程序,访问令牌将用于对 api 的后续调用。 api 的控制器装饰有 [Authorize]
属性。
我尝试使用一些脚手架代码进行身份验证,但现在我很挣扎,因为 jwt 令牌在某些情况下似乎无法识别。
在脚手架代码中,Startup Class 中的 ConfigureServices
方法调用了 services.AddDefaultIdentity<ApplicationUser>()
。
问题在于,这还添加了我没有添加的所有默认身份端点 need/want(/Account/Manage/Disable2fa、/Account/Manage/PersonalData 等)。
因此我将代码更改为 services.AddIdentity<ApplicationUser, IdentityRole>()
,因为我现在多次阅读 AddDefaultIdentity()
显然与 AddIdentity()
相同但也调用 .AddDefaultUI()
测试登录流程后,发现 api 控制器在进行更改后不再接受 Authorization: Bearer ...
Header 并且 api 调用总是被重定向进入登录页面,就好像用户没有登录一样
当我将代码更改回 AddDefaultIdentity 时,JWT Bearer Token 再次被正确验证,我可以使用 [Authorize] 属性访问控制器,但随后我又遇到了默认身份页面的问题...
我的问题是:如何使用 [Authorize] Arribute 和 JWT Bearer Header 保护我的 API 控制器,而不必包含默认身份 UI?
Startup.cs
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Munchify.Web.Data;
using Munchify.Web.Models;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using APIBackend.Web.Services;
namespace APIBackend.Web
{
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.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.ConfigureApplicationCookie(options =>
{
options.LoginPath = "/Identity/Account/Login";
});
services.AddIdentityServer()
.AddApiAuthorization<ApplicationUser, ApplicationDbContext>();
services.AddAuthentication()
.AddIdentityServerJwt();
services.AddTransient<IEmailSender, EmailSender>();
services.AddControllersWithViews();
services.AddRazorPages();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
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.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseIdentityServer();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
}
}
}
我设法修复了它
我基本上就是换了
services.AddIdentity<ApplicationUser, IdentityRole>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
和
services.AddAuthentication(o =>
{
o.DefaultScheme = IdentityConstants.ApplicationScheme;
o.DefaultSignInScheme = IdentityConstants.ExternalScheme;
})
.AddIdentityCookies(o => { });
var identityService = services.AddIdentityCore<ApplicationUser>(o =>
{
o.Stores.MaxLengthForKeys = 128;
o.SignIn.RequireConfirmedAccount = true;
})
.AddDefaultTokenProviders()
.AddEntityFrameworkStores<ApplicationDbContext>();
identityService.AddSignInManager();
identityService.Services.TryAddTransient<IEmailSender, EmailSender>();
因为这就是 AddDefaultIdentity() 在没有 UI 部分的情况下在幕后所做的事情。
现在我的 JWT Header 身份验证再次起作用
希望这对遇到同样问题的人有所帮助:)
我目前正在尝试为我正在开发的移动应用程序创建一个网络 api。
我决定使用 ASP.Net Core 3.1 和随附的 Indentity Server 来使用 OpenID Connect + PKCE 进行身份验证。
用户将通过 WebView 授权应用程序,访问令牌将用于对 api 的后续调用。 api 的控制器装饰有 [Authorize]
属性。
我尝试使用一些脚手架代码进行身份验证,但现在我很挣扎,因为 jwt 令牌在某些情况下似乎无法识别。
在脚手架代码中,Startup Class 中的 ConfigureServices
方法调用了 services.AddDefaultIdentity<ApplicationUser>()
。
问题在于,这还添加了我没有添加的所有默认身份端点 need/want(/Account/Manage/Disable2fa、/Account/Manage/PersonalData 等)。
因此我将代码更改为 services.AddIdentity<ApplicationUser, IdentityRole>()
,因为我现在多次阅读 AddDefaultIdentity()
显然与 AddIdentity()
相同但也调用 .AddDefaultUI()
测试登录流程后,发现 api 控制器在进行更改后不再接受 Authorization: Bearer ...
Header 并且 api 调用总是被重定向进入登录页面,就好像用户没有登录一样
当我将代码更改回 AddDefaultIdentity 时,JWT Bearer Token 再次被正确验证,我可以使用 [Authorize] 属性访问控制器,但随后我又遇到了默认身份页面的问题...
我的问题是:如何使用 [Authorize] Arribute 和 JWT Bearer Header 保护我的 API 控制器,而不必包含默认身份 UI?
Startup.cs
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Munchify.Web.Data;
using Munchify.Web.Models;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using APIBackend.Web.Services;
namespace APIBackend.Web
{
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.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.ConfigureApplicationCookie(options =>
{
options.LoginPath = "/Identity/Account/Login";
});
services.AddIdentityServer()
.AddApiAuthorization<ApplicationUser, ApplicationDbContext>();
services.AddAuthentication()
.AddIdentityServerJwt();
services.AddTransient<IEmailSender, EmailSender>();
services.AddControllersWithViews();
services.AddRazorPages();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
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.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseIdentityServer();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
}
}
}
我设法修复了它
我基本上就是换了
services.AddIdentity<ApplicationUser, IdentityRole>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
和
services.AddAuthentication(o =>
{
o.DefaultScheme = IdentityConstants.ApplicationScheme;
o.DefaultSignInScheme = IdentityConstants.ExternalScheme;
})
.AddIdentityCookies(o => { });
var identityService = services.AddIdentityCore<ApplicationUser>(o =>
{
o.Stores.MaxLengthForKeys = 128;
o.SignIn.RequireConfirmedAccount = true;
})
.AddDefaultTokenProviders()
.AddEntityFrameworkStores<ApplicationDbContext>();
identityService.AddSignInManager();
identityService.Services.TryAddTransient<IEmailSender, EmailSender>();
因为这就是 AddDefaultIdentity() 在没有 UI 部分的情况下在幕后所做的事情。
现在我的 JWT Header 身份验证再次起作用
希望这对遇到同样问题的人有所帮助:)