ASP.Net MVC 6 + WebAPI身份验证-将MVC重定向为登录,但如果WebAPI为401 [英] ASP.Net MVC 6 + WebAPI Auth - Redirect MVC to logon but 401 if WebAPI

查看:279
本文介绍了ASP.Net MVC 6 + WebAPI身份验证-将MVC重定向为登录,但如果WebAPI为401的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用AngularJS + MVC + WebAPI: -使用标准(个人帐户)进行MVC身份验证; -使用相同的用户名和密码进行基于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.

问题,从AngularJS一切正常,发生了cookie交换,并且Web API返回了值,但是当我尝试从Postman访问WebAPI时,我得到了重定向到登录页面的信息,而不是401 Unauthorized.

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?

谢谢

推荐答案

对于ASP.Net 5最新beta8,答案是在Startup.cs上的ConfigureServices中添加以下内容:

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);
                    }
                }
            };
        });

这篇关于ASP.Net MVC 6 + WebAPI身份验证-将MVC重定向为登录,但如果WebAPI为401的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆