ASP.Net MVC 6 + WebAPI Auth - MVC redirection for logging in, but 401 if WebAPI

I have AngularJS + MVC + WebAPI, where I try: - to use standard (individual accounts) for MVC authentication; - Use the same users and password for WebAPI authentication.

The problem is, everything works fine from AngularJS, the cookie exchange occurs, and the Web API returns a value, but when I try to access the WebAPI from Postman, I get a redirect to the login page instead of 401 Unauthorized.

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

thanks

+4
source share
3 answers

For the latest beta version of ASP.Net 5, you need to add the following to ConfigureServices in 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);
                    }
                }
            };
        });
+7
source

You can simply apply a special action for the Redirect event. In App_Start/Startup.Auth.csfind the file app.UseCookieAuthentication()and modify it as follows:

public void ConfigureAuth(IAppBuilder app)
{
    // some omitted configurations 

    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        // some omitted configurations 

        Provider = new CookieAuthenticationProvider
        {
            // some omitted configurations 

            OnApplyRedirect = context => 
            {
                // assuming your API url starts with /api
                if(!context.Request.Path.StartsWithSegments(new PathString("/api")))
                    context.Response.Redirect(context.RedirectUri);
            }
        }
    });
}
+3
source

RC1-Final (VS2015.1) : Identity AutomaticChallenge false ApplicationCookieAuthenticationScheme = "ApplicationCookie":

services.AddIdentity<AppUser>(options =>
        {
            // cut

            options.Cookies.ApplicationCookie.AutomaticAuthenticate = true;
            options.Cookies.ApplicationCookie.AutomaticChallenge = false;
            options.Cookies.ApplicationCookieAuthenticationScheme = "ApplicationCookie";
        })
            .AddUserStore<AppUserStore<AppUser, AppDbContext>>()
            .AddDefaultTokenProviders();

, , ActiveAuthenticationSchemes = "ApplicationCookie"

[Authorize(ActiveAuthenticationSchemes = "ApplicationCookie")]
    public async Task<IActionResult> Logout()
    {
        // cut
    }

(WebAPI ). Authorize .

AuthenticationOptions.cs AutomaticChallenge:

If false, the authentication middleware will only modify responses explicitly specified in AuthenticationScheme.

+2
source

Source: https://habr.com/ru/post/1612609/


All Articles