为什么未经授权的控制器不返回401 ASP.Net Core?

时间:2019-08-09 09:45:20

标签: c# asp.net-core

我正在使用Visual Studio代码,并且正在为RestAPI使用点网核心框架。当我访问执行具有“ Authorize”属性的控制器时,它应该返回401请求,但在邮递员中不返回任何内容。只是一片空白。

我认为它应该来自我的启动代码。

我将在启动文件中与您共享我的configure方法。

最感谢您的帮助。如果您可以在Internet上找到解决方案,则只需共享即可(我已经在寻找了,但是...也许我没有输入正确的关键字。)

公共类启动     {         公共启动(IConfiguration配置)         {             配置=配置;         }

    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)
    {
        ConfigureContext(services);

        services.AddCors();
        services.AddAutoMapper(typeof(Startup));

        // configure strongly typed settings objects
        var appSettingsSection = Configuration.GetSection("AppSettings");
        services.Configure<AppSettings>(appSettingsSection);

        // configure jwt authentication
        var appSettings = appSettingsSection.Get<AppSettings>();
        var key = Encoding.ASCII.GetBytes(appSettings.Secret);
        services.AddAuthentication(x =>
        {
            x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        })
        .AddJwtBearer(x =>
        {
            x.Events = new JwtBearerEvents
            {
                OnTokenValidated = context =>
                {
                    var userService = context.HttpContext.RequestServices.GetRequiredService<IUserService>();
                    var userId = int.Parse(context.Principal.Identity.Name);
                    var user = userService.GetById(userId);
                    if (user == null)
                    {
                        // return unauthorized if user no longer exists
                        context.Fail("Unauthorized");
                    }
                    return Task.CompletedTask;
                }
            };
            x.RequireHttpsMetadata = false;
            x.SaveToken = true;
            x.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(key),
                ValidateIssuer = false,
                ValidateAudience = false
            };
        });

        // Register the Swagger generator, defining 1 or more Swagger documents
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo
            {
                Title = "dotnetcore-api-core",
                Version = "v1"
            });
        });
        services.AddScoped<IUserService, UserService>();
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseAuthentication();
        app.UseMvc();
        app.UseStaticFiles();
        app.UseHttpsRedirection();
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        // Enable middleware to serve generated Swagger as a JSON endpoint.
        app.UseSwagger();
        // Security JWT
        app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());

        // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
        // specifying the Swagger JSON endpoint.
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "dotnetcore-api-core V1");
        });
    }

    public void ConfigureContext(IServiceCollection services)
    {
        // Database injection
        services.AddDbContext<UserContext>(options =>
            options.UseMySql(Configuration.GetConnectionString("AppDatabase")));
    }
}

我的未返回401未经授权的控制器:

    [Authorize]
    [Route("api/users")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly IUserService _userService;
        private IMapper _mapper;

        public UserController(
            IUserService userService,
            IMapper mapper)
        {
            _userService = userService;   
            _mapper = mapper;
        }

        [HttpGet]
        public async Task<ActionResult<IEnumerable<User>>> GetUsers()
        {
            IEnumerable<User> users = await _userService.GetAll();

            if(users == null)
            {
                return NotFound();
            }

            return Ok(users);
        }

我遵循了本教程-> https://jasonwatmore.com/post/2018/08/14/aspnet-core-21-jwt-authentication-tutorial-with-example-api

邮递员中的示例图片:Image example of empty body postman

4 个答案:

答案 0 :(得分:1)

您的呼叫返回401。在邮递员中清晰可见。正文当然是空的,但是如果您看上去更高一些,并且在正确的网站上(它与正文,Cookie,标题标签相同,则显示在同一行中),您会看到“状态”行显示“ 401未经授权”。它还显示了此响应花费了多少时间以及响应的大小。enter image description here

答案 1 :(得分:0)

尝试将此行移至 Configure 方法的顶部:

app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());

例如:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
    app.UseAuthentication();
    app.UseMvc();

    // the rest of you code here
}

答案 2 :(得分:0)

我认为您的问题是相同的。您可以添加以下几行代码(在Startup.cs文件中):

选项1:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseCors(pol => pol.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
    app.UseAuthentication();

    if (env.IsDevelopment())
        app.UseDeveloperExceptionPage();

    app.UseStatusCodePages(async context =>
    {
        if (context.HttpContext.Request.Path.StartsWithSegments("/api"))
        {
            if (!context.HttpContext.Response.ContentLength.HasValue || context.HttpContext.Response.ContentLength == 0)
            {
                // You can change ContentType as json serialize
                context.HttpContext.Response.ContentType = "text/plain";
                await context.HttpContext.Response.WriteAsync($"Status Code: {context.HttpContext.Response.StatusCode}");
            }
        }
        else
        {
            // You can ignore redirect
            context.HttpContext.Response.Redirect($"/error?code={context.HttpContext.Response.StatusCode}");
        }
    });

    app.UseMvc();
}

选项2

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
       app.UseDeveloperExceptionPage();
    }

    app.UseExceptionHandler("/api/errors/500");
    app.UseStatusCodePagesWithReExecute("/api/errors/{0}");

    app.UseRouting();

    ...
}

然后,创建ErrorController,如:

[ApiController]
[Route("api/errors")]
public class ErrorController : Controller
{
    [HttpGet("{code}")]
    public async Task<IActionResult> Get(int code)
    {
        return await Task.Run(() =>
        {
            return StatusCode(code, new ProblemDetails()
            {
                Detail = "See the errors property for details.",
                Instance = HttpContext.Request.Path,
                Status = code,
                Title = ((HttpStatusCode)code).ToString(),
                Type = "https://my.api.com/response"
            });
        });
    }
}

我希望这会有所帮助。

答案 3 :(得分:0)

将路线添加到您的GetUsers操作:

selection = input("1 for earth 2 for animals")

with open('questionnaire.csv') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    for row in csv_reader:
        key = row[0]
        subject = row[1]
        question = row[2]
        option1 = row[3]
        option2 = row[4]
        option3 = row[5]
        option4 = row[6]
        prompt = "Which option do you pick? "
        answer = row[7]
        
        user_prompt = (f"" + question + "\n" + option1 + "\n" + option2 + "\n" +
                       option3 + "\n" + option4 + "\n" + prompt)

        if key == selection:
            user_answer = input(user_prompt)

然后在邮递员中这样称呼它... api / Users / GetUsers