問題描述
我是 .net 核心的新手,我正在嘗試創建實現 jwt 以進行身份??驗證和授權的 web api 核心.
I am new to .net core, and I am trying to create web api core which implements jwt for authentication and authorization purposes.
在 Startup 類中我是這樣配置的:
Inside Startup class I configured it this way:
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<MandarinDBContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("MyConnection")));
services.AddIdentity<User, Role>()
.AddEntityFrameworkStores<MyDBContext>()
.AddDefaultTokenProviders();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "yourdomain.com",
ValidAudience = "yourdomain.com",
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes("My secret goes here"))
};
options.RequireHttpsMetadata = false;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
// Add application services.
services.AddTransient<IUserService, UserService>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseMvc();
}
}
但是當我嘗試調用以下操作時:
But when I try to call the following action:
[Authorize]
[HttpGet]
[Route("api/Tokens")]
public IActionResult TestAuthorization()
{
return Ok("You're Authorized");
}
我得到 404 未找到.如果我刪除 Authorize 屬性它正在工作.
I get 404 not found. If I remove Authorize attribute it's working .
你能指導我解決這個問題嗎?
Could you please guide me to solve that issue?
推薦答案
當您的 API 未經授權且您的重定向 URL 不存在時會發生這種情況.當身份驗證失敗時,Web API 將發送一個 401 代碼.現在,如果您在客戶端處理此代碼并為授權失敗執行重定向,請確保重定向的 Url 存在.此外,請勿將 [Authorize] 屬性添加到處理身份驗證方法(登錄/注冊)的控制器.您的罪魁禍首似乎是 Authorize 屬性.由于您使用的是 JWT 身份驗證方案.您的授權屬性應遵循
It happens when your API is not authorized and your redirect URL doesn't exist. When authentication fails, Web API will send a 401 code. Now if you are handling this code on the client side and doing a redirect for an authorization failure, then make sure that the redirected Url exists. Also, Do not add the [Authorize] attribute to the controller that handles Authentication methods (Login/Register). Your culprit looks to be the Authorize attribute. Since you are using JWT authentication scheme. Your authorize attribute should be following
[Authorize(AuthenticationSchemes = "Bearer")]
[HttpGet]
[Route("api/Tokens")]
public IActionResult TestAuthorization()
{
return Ok("You're Authorized");
}
要使其成為默認身份驗證方案,請將 AddIdentity 更改為 AddIdentityCore.這是一篇非常好的文章.
To make it default authentication scheme, Change AddIdentity to AddIdentityCore. here is a very good article.
在僅 API 的 ASP.NET Core 項目中使用 JwtBearer 身份驗證
這篇關于添加 Authorize 屬性時 Web api 核心返回 404的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!