Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net MVC 6 + WebAPI Auth - Redirect MVC to logon but 401 if WebAPI

I have a AngularJS + MVC + WebAPI where I'm trying to: - Use standard (individual accounts) for MVC authentication; - Use those same users and password for WebAPI based authentication.

Problem, from AngularJS everything works fine, the cookie exchange happens, and Web API returns the value, but when I'm trying to access the WebAPI from Postman, I get a redirect to logon page instead of a 401 Unauthorized.

What is the easiest way to achieve this? Do I have to subclass Authorize and implement the logic manually?

Thank you

like image 983
Joao Sousa Avatar asked Dec 14 '22 11:12

Joao Sousa


1 Answers

For the ASP.Net 5 latest beta8, the answer is to add the following to ConfigureServices on Startup.cs:

         services.Configure<IdentityOptions>(config =>
        {
            options.Cookies.ApplicationCookie.LoginPath = "/Account/Login";
            options.Cookies.ApplicationCookie.CookieHttpOnly = true;
            options.Cookies.ApplicationCookie.CookieSecure = CookieSecureOption.SameAsRequest;
            options.Cookies.ApplicationCookie.Events = new CookieAuthenticationEvents()
            {
                OnRedirect = ctx =>
                {
                    if (ctx.Request.Path.StartsWithSegments("/api") &&
                    ctx.Response.StatusCode == 200)
                    {
                        ctx.Response.StatusCode = 401;
                        return Task.FromResult<object>(null);
                    }
                    else
                    {
                        ctx.Response.Redirect(ctx.RedirectUri);
                        return Task.FromResult<object>(null);
                    }
                }
            };
        });
like image 188
Joao Sousa Avatar answered May 19 '23 06:05

Joao Sousa