ASP.Net Kern - keine Umleitung auf API auth Fehler
In meinem ASP.NET Core-Projektes bekam ich ein paar API-Controller mit jwt-Berechtigung wie diese:
[Route("api/v1/[controller]")]
public class MyController : Controller
{
[HttpGet("[action]")]
[Authorize(Policy = MyPolicy)]
public JsonResult FetchAll()
{
}
}
Wenn die Autorisierung für den Zugriff auf die Aktion FetchAll() schlägt Fehl, ich will HttpStatusCode.Forbidden als Antwort. Statt Mvc macht eine Umleitung auf Konto/Login?ReturnUrl=[...]
Ich versucht den Redirect-Ereignisse und die Rückkehr Verboten/Unauthorized überschreiben der Cookie Ereignisse ohne Erfolg:
app.UseIdentity();
var tokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = TokenController.DummyKey,
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
ClockSkew = TimeSpan.FromMinutes(0)
};
app.UseJwtBearerAuthentication(new JwtBearerOptions
{
AutomaticAuthenticate = true,
AutomaticChallenge = true,
TokenValidationParameters = tokenValidationParameters,
});
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AutomaticAuthenticate = false,
AutomaticChallenge = false,
AuthenticationScheme = "BsCookie",
CookieName = "access_token",
TicketDataFormat = new CustomJwtDataFormat(SecurityAlgorithms.HmacSha256, tokenValidationParameters),
Events = new CookieAuthenticationEvents
{
OnRedirectToLogin = context =>
{
if (context.Request.Path.StartsWithSegments("/api") && context.Response.StatusCode == (int)HttpStatusCode.OK)
context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
else
context.Response.Redirect(context.RedirectUri);
return Task.FromResult(0);
},
OnRedirectToAccessDenied = context =>
{
if (context.Request.Path.StartsWithSegments("/api") && context.Response.StatusCode == (int)HttpStatusCode.OK)
context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
else
context.Response.Redirect(context.RedirectUri);
return Task.FromResult(0);
}
},
});
Beide Ereignisse werden nie genannt, und das Visual-Studio-Ausgabe Zeigt, dass fetchall schlägt Fehl, und der Account/Login-Daten zurückgegeben werden, statt:
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/1.1 GET http://localhost:6460/api/v1/Lehrer/GetAll application/json
Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerMiddleware:Information: Successfully validated the token.
Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerMiddleware:Information: HttpContext.User merged via AutomaticAuthentication from authenticationScheme: Bearer.
Microsoft.AspNetCore.Authorization.DefaultAuthorizationService:Information: Authorization failed for user: (null).
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
Microsoft.AspNetCore.Mvc.ChallengeResult:Information: Executing ChallengeResult with authentication schemes ().
Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerMiddleware:Information: AuthenticationScheme: Bearer was forbidden.
Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware:Information: AuthenticationScheme: Identity.Application was challenged.
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executed action Sam.Learning2.Controllers.LehrerController.GetAll (Sam.Learning2) in 49.7114ms
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 121.6106ms 302
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/1.1 GET http://localhost:6460/Account/Login?ReturnUrl=%2Fapi%2Fv1%2FLehrer%2FGetAll
Möchte ich meine APIs zurück 401/403 statt der Umleitung zu Login - wie kann ich erreichen, das wenn der obige code funktioniert nicht?
app.UseIdentity()
registriert auch einen Cookie-Authentifizierung, middleware, welche AutomaticChallange = true
. Bist du zufällig noch mit ASP.NET Core 1.0? Ich glaube zu erinnern, dass es sollte nicht möglich sein, haben Sie mehr als eine middleware mit AutomaticChallange
in die neuere VersionInformationsquelleAutor Sam | 2017-01-09
Du musst angemeldet sein, um einen Kommentar abzugeben.
Update ASP.NET Core 2.x
Die Berechtigung ein wenig geändert in ASP.NET Core 2.0. Die Antwort unten ist nur gültig für ASP.NET Kern 1.x. Für ASP.NET Core 2.0 finden Sie auf dieser Antwort und diese GitHub Nachricht.
ASP.NET Kern 1.x
Was Sie scheint vergessen zu haben, ist, dass
app.UseIdentity()
auch registriert die cookie-middleware.und die ASP.NET Kern-Identität legt die
AutomaticChallange
zutrue
für cookie (ApplicationCookie
) middleware (siehe Quelle). Daher die Umleitung zu/Account/Login?ReturnUrl
. Sie tun müssen, deaktivieren Sie diese option in der Identität.Wenn Sie wirklich möchten, eine Identität, die Auth (login-Webseite) und JWT, würden Sie brauchen, zu registrieren, die middlewares basieren auf der url. So also
app.UseIdentity()
ist nur registriert, für nicht-api-urls und Jwt middleware ist nur für registrierte urls beginnend mit/api
.Können Sie dies mit der
.MapWhen
(docs).Nun
branch.UseIdentity()
nur verwendet werden, für URLs, die nicht mit/api
, die in der Regel Ihre MVC-Ansichten, wo die Umleitung zu/Account/Login
gewünscht ist.Schön, deine Antwort, die das problem behob: stackoverflow.com/questions/41473672/...
Diese Ankündigung kann auch nützlich sein, github.com/aspnet/Announcements/issues/210 sowie der verlinkten Themen innerhalb der it
InformationsquelleAutor Tseng
Ich habe gerade mit Barry Dorrans Asp Net Berechtigungs-Workshop
in
ConfigureServices
ich nur hinzufügenservices.AddAuthorization();
.und in
Configure
fügen Sie diesen code:In Mvc-reroute to Account/Login?ReturnUrl=[...] und in der API erhalten Sie 401 oder 403.
InformationsquelleAutor akaco
Microsoft web api-stack eingerichtet ist, das zu tun diese out-of-the-box. Die Lösung ist auf der client-Seite.
Fügen Sie diesen header der client-Anfrage:
Web-api sieht für die Kopfzeile. Wenn präsentieren ein 401 zurück, wenn die Anfrage nicht authentifiziert. Wenn der header nicht vorhanden ist, gibt die Umleitung auf die login-Seite.
Sehen diese https://github.com/aspnet/Security/issues/1394#issuecomment-326445124
Ich denke, Sie müssen nur die komplexeren code in der cookie-Ereignissen, wenn Sie nicht ändern Sie die client.
InformationsquelleAutor RichardHowells