![](/img/trans.png)
[英]How to use JWT in MVC application for authentication and authorization?
[英]JWT Authorization in .NET 5 MVC Application
我想知道如何在 .net 5 webapp 中為我的 mvc 控制器使用 jwt 來處理授權。 令牌生成函數已經編寫完畢,它在 postman 中完美運行(通過傳遞不記名令牌),但從 controller 重定向到具有 [Authorize] 屬性的其他函數的微不足道的工作 - 401 響應。 我檢查了請求和授權的詳細信息 header 似乎丟失了。 Should i create my own middleware to refill authorization header in every request / redirect to other mvc controller or jwt framework for .net do it for me by passing few rules in eg Startup class? 它應該如何工作?
HomeController(主頁)
[HttpGet]
public IActionResult Redirect()
{
var token = new JWTService().GenerateToken("test").Token;
return Redirect("~/Person");
}
個人控制器
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public IActionResult Index()
{
return View();
}
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.AddControllersWithViews();
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidAudience = "aaaa",
ValidIssuer = "aaaa",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"))
};
});
}
// 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();
}
else
{
app.UseExceptionHandler("/Home/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.UseRouting();
app.UseStaticFiles();
app.UseAuthentication();
app.UseAuthorization();
app.UseCookiePolicy();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
您使用AddJwtBearer來保護API ,通常您使用傳入請求中的授權 header 提供 JWT訪問令牌,並且 AddJwtBearer 會將令牌轉換為用戶實例。
這段代碼沒有意義:
[HttpGet]
public IActionResult Redirect()
{
var token = new JWTService().GenerateToken("test").Token;
return Redirect("~/Person");
}
因為您無法通過重定向在授權響應 header 中包含必要的令牌。 重定向適用於訪問您的 web 站點的人,而不適用於 API 訪問。
所以我認為你混淆了瀏覽器/用戶可以做什么,以及 API 訪問意味着什么。
我將首先創建一個 ASP.NET 核心服務供人類訪問,然后為 API 創建一個單獨的服務實例,第一個服務可以向其發送請求。
此外, AddJwtBearer 通常不會接受您自己生成的任何令牌,而是您應該有一個授權服務(如IdentityServer ),為您頒發令牌。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.