aspnet / AspNetKatana

Microsoft's OWIN implementation, the Katana project
Apache License 2.0
967 stars 334 forks source link

Owin : Unauthorised webapi call returning login page rather than 401 #65

Closed Yassine-Khechane closed 7 years ago

Yassine-Khechane commented 7 years ago

In my mvc application, i've configured OpenIdConnect and CookieAuthentication middlewares.

When i trigger web api call from ajax, the web api, depending on the inputs data, returns Unauthorized code, the problem is that the request is captured and transformed to 302 to display the login page !

Tratcher commented 7 years ago

If you have them set to Active then they will trigger logins for 401 responses. Are you getting the OIDC or Cookie login page? If it's OIDC then you either need to set that to not Active, or explicity challenge Cookies and then this logic will take over: https://github.com/aspnet/AspNetKatana/blob/b850cd8b4de61e65bbd7127ce02b5df7c4cb6db5/src/Microsoft.Owin.Security.Cookies/Provider/DefaultBehavior.cs#L16

Yassine-Khechane commented 7 years ago

Its OIDC middleware that catch the 401 and turn it to 302, when I disable it (set the authentication mode to passive), I get 401 from my api, the problem is when I request a secure page on my application, I get also a 401 instead of redirecting the user to the login page. If I explicitly request the login page and set the challenge type (owinContext.Authentication.Challenge(authenticationProperties, "opid");) it works fine

Yassine-Khechane commented 7 years ago

Thanck you for your help, it works now..., i changed my custome auth attribute

public void OnAuthorization(AuthorizationContext filterContext) {
if (!filterContext.HttpContext.User.Identity.IsAuthenticated) { filterContext.HttpContext.GetOwinContext().Authentication.Challenge("oidc"); filterContext.Result = new System.Web.Mvc.HttpUnauthorizedResult(); } .... }