添加 Authorize 属性时 Web api 核心返回 404 [英] Web api core returns 404 when adding Authorize attribute

查看:41
本文介绍了添加 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆