我创建了一个包含MVC5和WebAPI的新Web应用程序。现在我添加了一个新的API-Controller,并添加了一个Authorize-Atribute(System.Web.Http)。认证工作正常,值也能被返回。但是当授权失败时,会返回登录页和状态200。但在这种情况下,我需要返回错误和状态401。
我尝试过将app.UseCookieAuthentication移除,这样可以返回正确的状态 - 但我需要cookie认证来启用普通MVC部分的身份验证。
当然,我可以重写Authorization属性以抑制表单重定向,如此解决方案中建议的那样,但我想这不是正确的方法,因为存在2个authorizeattributes和许多配置项。
我的启动认证:
我的OAuth提供者:
我尝试过将app.UseCookieAuthentication移除,这样可以返回正确的状态 - 但我需要cookie认证来启用普通MVC部分的身份验证。
当然,我可以重写Authorization属性以抑制表单重定向,如此解决方案中建议的那样,但我想这不是正确的方法,因为存在2个authorizeattributes和许多配置项。
我的启动认证:
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);
}
}