添加 Authorize 属性时 Web api 核心返回 404

Web api core returns 404 when adding Authorize attribute(添加 Authorize 属性时 Web api 核心返回 404)
本文介绍了添加 Authorize 属性时 Web api 核心返回 404的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 .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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)