2016-01-19 6 views
5

Ich habe Web-API mit OWIN-Authentifizierung in Web MVC. Ich verwende <authentication> in Web.Config für meine Web MVC, so dass es auf die Anmeldeseite umleiten.Lassen Sie die Web-API-Authentifizierung 401 zurückgeben und nicht zur Anmeldeseite umleiten

<authentication mode="Forms"> 
    <forms name="WEB.AUTH" loginUrl="~/login" domain="" protection="All" 
    timeout="43200" path="/" requireSSL="false" slidingExpiration="true" /> 
</authentication> 

Ich verwende [System.Web.Http.Authorize] Attribut auf meine Web-API-Autorisierung. Aber irgendwie, die API umleiten auf Login-Seite wie meine MVC-App wegen der oben genannten Konfiguration.

was ich tun möchte, ist Weiterleitungsfunktion für das Web MVC, aber 401 für Web API zurückgeben. Wie kann ich das erreichen? Soll ich ein benutzerdefiniertes Autorisierungsattribut für die Web-API erstellen?

--EDIT--

fand ich die Antwort von diesem Posten SuppressDefaultHostAuthentication in WebApi.Owin also suppressing authentication outside webapi

ich fügen Sie einfach ein paar Zeilen in mein Startup.cs So. Ich hatte alle meine Controller mit einer "api" Präfix-Route konfiguriert.

HttpConfiguration config = new HttpConfiguration(); 
//..some OWIN configuration 
app.Map("/api", inner => 
{ 
    inner.UseWebApi(config); 
}); 

stellen Sie sicher, app.Map() nach Web Api-Konfiguration Linien setzen. Andernfalls wird die MVC-Anwendung fehlerhaft angezeigt.

Antwort

1

Erstellen eines benutzerdefinierten AuthorizeAttribute:

public class MyAuthorizeAttribute : AuthorizeAttribute 
{ 
    protected override void HandleUnauthorizedRequest(HttpActionContext actionContext) 
    { 
     actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Unauthorized"); 
    } 
} 

Wenn Sie in Zukunft die web.config Sachen überspringen und owin zur Einrichtung Ihrer Authentifizierung verwenden, könnten Sie in Ihrem Startup.cs tun:

var provider = new CookieAuthenticationProvider(); 
var originalHandler = provider.OnApplyRedirect; 
provider.OnApplyRedirect = context => 
{ 
    if (!context.Request.Uri.LocalPath.StartsWith(VirtualPathUtility.ToAbsolute("~/api"))) 
    { 
     context.RedirectUri = new Uri(context.RedirectUri).PathAndQuery; 
     originalHandler.Invoke(context); 
    } 
}; 

app.UseCookieAuthentication(new CookieAuthenticationOptions 
{ 
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, 
    CookieName = FormsAuthentication.FormsCookieName, 
    LoginPath = new PathString("/Account/LogOn"), 
    ExpireTimeSpan = TimeSpan.FromMinutes(240), 
    Provider = provider 
}); 
+0

Es funktioniert nicht für mich. Ich habe jedoch die Lösung gefunden. Bitte überprüfe meinen bearbeiteten Beitrag. – vantian

0

Diese hat für mich funktioniert.

Erstellen eines benutzerdefinierten Attributs:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)] 
public class NoRedirectAuthorizeAttribute : AuthorizeAttribute 
{   
    protected override void HandleUnauthorizedRequest(HttpActionContext actionContext) 
    { 
     actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Forbidden); 
    } 
} 

das Attribut in Ihrem Controller verwenden:

[HttpDelete] 
    [NoRedirectAuthorizeAttribute(Roles = "Admin")] 
    [Route("api/v3/thingstodelete/{id=id}")] 
    public IHttpActionResult DeleteThingToDelete(Guid id) 
    { 
     //delete code 
    } 

Hier sind zwingende nur die HandleUnauthorizedRequest Methode des AuthorizeAttribute. Statt also eine Weiterleitung (304) an die Anmeldeseite zu senden, senden wir den HTTP-Statuscode Forbidden (403).

Verwandte Themen