gpt4 book ai didi

ASP.NET Web API 2 Bearer Token 重定向到登录页面而不是返回 401

转载 作者:行者123 更新时间:2023-12-02 10:59:32 26 4
gpt4 key购买 nike

我创建了一个包含 MVC5 和 WebAPI 的新 Web 应用程序。现在我添加了一个新的 API Controller 并添加了一个授权属性 (System.Web.Http)。授权工作正常,并且返回值。但是当授权失败时,会返回login-page和status 200。但在这种情况下我需要返回错误和状态 401。

我尝试过,当我删除 app.UseCookieAuthentication 时,会返回正确的状态 - 但我需要 cookie 身份验证才能在正常的 MVC 部分中启用身份验证。

当然,我可以重写授权属性来抑制表单重定向,如 this solution 中建议的那样。但我想这不是正确的方法,因为存在 2 个授权属性和很多配置内容。

我的启动授权:

public void ConfigureAuth(IAppBuilder app)
{
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager,
ApplicationUser>(TimeSpan.FromMinutes(30),
(manager, user) => user.GenerateUserIdentityAsync(manager))
}
});


app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

app.UseOAuthBearerTokens( new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/api/Account/Token"),
Provider = new SimpleAuthorizationServerProvider(),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
AllowInsecureHttp = true,
});
}

我的oauth提供商:

public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
{
public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
// Resource owner password credentials does not provide a client ID.
if (context.ClientId == null)
{
context.Validated();
}

return Task.FromResult<object>(null);
}

public override Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context)
{
if (context.ClientId == "self")
{
Uri expectedRootUri = new Uri(context.Request.Uri, "/");

if (expectedRootUri.AbsoluteUri == context.RedirectUri)
{
context.Validated();
}
}

return Task.FromResult<object>(null);
}

public override Task TokenEndpoint(OAuthTokenEndpointContext context)
{
foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)
{
context.AdditionalResponseParameters.Add(property.Key, property.Value);
}

return Task.FromResult<object>(null);
}

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
var info = await userManager.FindAsync(context.UserName, context.Password);
if (info == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}

var oAuthIdentity = await userManager.CreateIdentityAsync(info, context.Options.AuthenticationType);
var cookiesIdentity = await userManager.CreateIdentityAsync(info, CookieAuthenticationDefaults.AuthenticationType);
var properties = new AuthenticationProperties(new Dictionary<string, string> {
{ "userName", info.UserName }
});
var ticket = new AuthenticationTicket(oAuthIdentity, properties);
context.Validated(ticket);
context.Request.Context.Authentication.SignIn(cookiesIdentity);
}
}

最佳答案

您可以覆盖 302 响应:

var c = new CookieAuthenticationOptions;

// Make ASP.NET give us the 302 redirect when cookie is missing/broke
c.AutomaticChallenge = true;

c.Events = new CookieAuthenticationEvents
{
// Override the 302 redirection with the 401 we actually want
OnRedirectToLogin = context =>
{
context.Response.StatusCode = 401;
return Task.FromResult(0); ;
}
};

这是一个令人不快的黑客行为,它有效,但是 I'd love to know a better way of making the built in authentication middleware work as expected

关于ASP.NET Web API 2 Bearer Token 重定向到登录页面而不是返回 401,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24475747/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com