ASP.NET MVC 5 [Authorize]属性在浏览器中生成登录弹出窗口,而不是重定向到302登录页面 [英] ASP.NET MVC 5 [Authorize] attribute is generating login pop-up in browser instead of redirecting to 302 login page

本文介绍了ASP.NET MVC 5 [Authorize]属性在浏览器中生成登录弹出窗口,而不是重定向到302登录页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从来没有见过这种情况:我已经用 [Authorize(Roles =Admin)属性装饰了一个控制器,而不是发送未注册/未签名的用户通过302重定向到登录视图,Chrome浏览器中会显示一个JavaScript生成的登录提示:





输入他或她的凭据后,用户将收到401错误。对于设置< authentication mode> a href =http://stackoverflow.com/questions/21652808/asp-net-mvc-5-web-config-formsauthenticationmodule-or-formsauthentication?lq=1>删除< FormsAuthenticationModule> ; 在Web.Config不改变这种行为我以前创建了另一个项目使用完全相同的控制器,参考库等,从未遇到过这种不良行为。



现在我的大盲点是是否有某种OWIN冲突发生。要在启动时观察我的应用程序的行为,我在 app.UseCookieAuthentication()方法中创建了一个测试变量并设置断点。我在调试期间观察到这个方法根本没有被调用(见下面的完整代码块):

  app.UseCookieAuthentication new CookieAuthenticationOptions 
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString(/ Account / Login),
Provider = new CookieAuthenticationProvider
{
//使应用程序在用户登录时验证安全戳
//这是一个安全功能,当您更改密码或向您的帐户添加外部登录时使用
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity< ApplicationUserManager,ApplicationUser>(
validateInterval:TimeSpan.FromMinutes(30),
regenerateIdentity:(manager,user)=> user.GenerateUserIdentityAsync(manager)),
OnApplyRedirect = ctx =>
{
var t = 2;
}
}
});

为了更清楚地说明这里的装饰控制器与不合作的 [Authorize] / code>属性。

  [Authorize(Roles =Admin)] 
public ActionResult BlogPostsAdmin )
{
return View(db.BlogPosts.ToList());
}



这里是AccountController应该返回登录视图:

  [AllowAnonymous] 
public ActionResult Login(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}

有任何帮助吗?



UPDATE:我现在只是想从现在开始一起加入一个自定义的authorize属性,虽然这不是生产中需要的:

  using System; 
using System.Collections.Generic;
using System.Linq;
使用System.Web;
using System.Web.Mvc;

namespace PortfolioSite.Framework
{

public class SiteAuthorizeAttribute:AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
base.HandleUnauthorizedRequest(filterContext);

filterContext.HttpContext.Response.Redirect(/ Account / Login);
}
}
}


解决方案>

web配置应该覆盖IIS express配置,但在这种情况下它似乎它不。你可以尝试做的是在IIS级别关闭它。



你可以去这个目录\IISExpress\config\applicationhost.config打开此文件并设置

 < windowsAuthentication enabled =false/& 


I've never seen this happen before: I've decorated a controller with an [Authorize (Roles = "Admin"]attribute, but instead of sending unregistered/un-signed users to the Login View via 302 redirect, a javascript-generated sign-in prompt appears in the Chrome browser:

After entering in his or her credentials, the user is then given a 401 error. The suggestions on SO for setting the <authentication mode> and removing the <FormsAuthenticationModule> in Web.Config don't alter this behavior. I have previously created another project using the exact same controllers, reference libraries, etc. and never encountered this undesired behavior.

The big blind spot for me right now is whether there is some sort of OWIN conflict going on. To observe my app's behavior at startup, I created a test variable inside app.UseCookieAuthentication() method and set a breakpoint. I observed during debug that this method wasn't being called at all (see full code block below):

 app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            Provider = new CookieAuthenticationProvider
            {
                // Enables the application to validate the security stamp when the user logs in.
                // This is a security feature which is used when you change a password or add an external login to your account.  
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)),
                OnApplyRedirect = ctx =>
                {
                    var t = 2;
                }
            }
        });

To provide more clarity here's the decorated controller with the uncooperative [Authorize] attribute.

    [Authorize(Roles = "Admin")]
    public ActionResult BlogPostsAdmin()
    {
        return View(db.BlogPosts.ToList());
    }

Here's the AccountController that is supposed to return the Login View:

 [AllowAnonymous]
    public ActionResult Login(string returnUrl)
    {
        ViewBag.ReturnUrl = returnUrl;
        return View();
    }

Any help?

UPDATE: I am just going to hack together a custom authorize attribute from now, though this is not desirable for production:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace PortfolioSite.Framework
{

    public class SiteAuthorizeAttribute : AuthorizeAttribute
    {
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            base.HandleUnauthorizedRequest(filterContext);

            filterContext.HttpContext.Response.Redirect("/Account/Login");
        }
    }
}

解决方案

The web config should overwrite the IIS express config but in this case it seems it does not. What you can try to do is to turn it off on the IIS level as well.

You can go to this directory \IISExpress\config\applicationhost.config open up this file and set the

 <windowsAuthentication enabled="false" />

这篇关于ASP.NET MVC 5 [Authorize]属性在浏览器中生成登录弹出窗口,而不是重定向到302登录页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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