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

查看:197
本文介绍了添加授权属性时,Web API核心返回404的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是.net核心的新手,我正在尝试创建Web api核心,该核心实现了jwt以便进行身份验证和授权.

I am new to .net core, and I am trying to create web api core which implements jwt for authentication and authorization purposes.

在内部启动类中,我是这样配置的:

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]属性添加到处理身份验证方法(登录/注册)的控制器.您的罪魁祸首是授权"属性.由于您使用的是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身份验证

这篇关于添加授权属性时,Web API核心返回404的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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