【问题标题】:How to response status 401 on ASP.NET 5 ASP.NET Identity 3.0 RC1如何在 ASP.NET 5 ASP.NET Identity 3.0 RC1 上响应状态 401
【发布时间】:2015-12-04 15:30:26
【问题描述】:

在我使用代码的所有教程中

 app.UseCookieAuthentication(ctx =>
            {
                ctx.AutomaticChallenge = true;
                ctx.Events = new CookieAuthenticationEvents()
                {
                    OnRedirectToLogin = context =>
                    {
                        context.Response.Headers["Location"] = context.RedirectUri;
                        context.Response.StatusCode = 401;
                        return Task.FromResult(0);
                    }
                };
            });

需要使用状态码 401 创建重定向,但因为我使用 ASP.NET 身份,我总是会自动重定向到帐户/登录页面。

有人可以帮助我并告诉我如何不被重定向到帐户/登录并返回状态 401。 如果我使用任何其他状态(如 403 工作正常但 401 我可以返回)。 谢谢。

【问题讨论】:

  • 那为什么要使用身份中间件呢?
  • 是的,这是个好问题,但我想为用户和其他具有 Authorize 属性的实体使用 EF Identity 实现,但我也希望如果我有 WEB API 返回 401 而不是状态 200,因为被重定向.
  • 我实际上正在尝试这种方法:wildermuth.com/2015/9/10/ASP_NET_5_Identity_and_REST_APIs
  • 我猜您可以创建自己的中间件并获取重定向并将其更改为 401,如果您在 cookie 身份验证/身份之后运行它。
  • 感谢您的 cmets,但我认为我会选择 IdentityServer3,因为我这样做是为了保护我的 API 调用,也许 IdentityServer3 是目前​​最好的解决方案,其他方法是现在对我来说不太可靠。非常感谢您的 cmets,您对我的决定有很大帮助。

标签: asp.net-core http-status-code-401 asp.net-identity-3


【解决方案1】:

对此的解决方法是将其添加到身份提供者,而不是作为其自己的身份验证步骤。

所以:

public void Configure(IApplicationBuilder app, ...) 
{
    ...
    app.UseIdentity();
    ...
    // Ignored, because identity does its own auth and is before it in the middleware
    app.UseCookieAuthentication(...):

而是将您的 cookie 设置添加到身份配置中:

public void ConfigureServices(IServiceCollection services)
{
    ...
    // Configure identity service
    services.AddIdentity<AppUser, AppRole>(options =>
    {
        // Set cookie options for that service
        var ctx = options.Cookies.ApplicationCookie;

        // Your code
        ctx.AutomaticChallenge = true;
        ctx.Events = new CookieAuthenticationEvents
        {
            OnRedirectToLogin = context =>
            {
                context.Response.Headers["Location"] = context.RedirectUri;
                context.Response.StatusCode =
                    (int) HttpStatusCode.Unauthorized; 
                return Task.CompletedTask;
            }
        };
    });

【讨论】:

  • 我会使用:context.Response.StatusCode = (int)HttpStatusCode.Unauthorized; return Task.CompletedTask; 稍微好一点
猜你喜欢
  • 1970-01-01
  • 2016-09-06
  • 1970-01-01
  • 2016-04-25
  • 2016-04-20
  • 2019-02-11
  • 1970-01-01
  • 1970-01-01
  • 2016-04-04
相关资源
最近更新 更多