【问题标题】:AuthorizeCore not working for custom authorize attributeAuthorizeCore 不适用于自定义授权属性
【发布时间】:2017-06-15 11:27:04
【问题描述】:

我正在尝试在我的应用程序中使用自定义 Authorize 属性来处理来自客户和管理员的请求。

我在不同的应用程序中使用了相同的方法,唯一的区别是身份验证类型。一个基于 Microsoft 帐户,另一个基于联合服务。

我在 AuthorizationCore 方法的覆盖中设置了一个断点,我的问题是当用户第一次尝试访问应用程序时它只会被触发一次,然后它将用户重定向到登录页。在此之后,它不会再次被解雇。每次用户访问控制器/操作时,我都需要它触发,以便我们可以检查用户是否具有正确的角色,据我了解,这就是 Authorize 属性的用途。

我的代码:

public class AuthorizeUserAttribute : AuthorizeAttribute
{
    /// <summary>
    /// The Role required by the Action or Controller
    /// </summary>
    public UserRole RequireRole { get; set; }

    /// <summary>
    /// Authorization Logic
    /// </summary>
    /// <param name="httpContext"></param>
    /// <returns></returns>
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {

        //Result = new AuthorizationResult();
        bool isAuthorized = base.AuthorizeCore(httpContext);

        if (isAuthorized)
        {
            using (ApplicationDbContext context = new ApplicationDbContext())
            {
                ApplicationUser user = context.ApplicationUsers.FirstOrDefault(u => u.EmailAddress.Equals(httpContext.User.Identity.Name, StringComparison.OrdinalIgnoreCase));
            }


            // ... Check if user has the required role
        }

        return isAuthorized;
    }

    /// <summary>
    /// Redirect the user
    /// </summary>
    /// <param name="filterContext"></param>
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        // Handle the request if the user does not have the required role

        base.HandleUnauthorizedRequest(filterContext);
    }
}

我使用的属性如下

    [AuthorizeUser(RequireRole = Core.Models.Users.UserRole.User)]
    public ActionResult Index()
    {

        return View();
    }

任何帮助将不胜感激。 谢谢

【问题讨论】:

  • 您如何使用AuthorizeUserAttribute?请发布一些代码示例。
  • 你在哪里将isAuthorized设置为false?
  • @NightOwl888 我添加了实现
  • @S.Dav 这只是基本布局,我还没有添加任何逻辑
  • 就像现在一样,一旦用户登录,它将始终返回 true,因为 isAuthorized 在任何地方都没有设置为 false

标签: c# asp.net-mvc


【解决方案1】:

我觉得自己不得不承认这一点

我的代码运行良好,问题是身份验证提供程序在通过身份验证后将我重定向到我的 https 站点,我没有意识到它重定向我的端口。它重定向到的端口是我的 IIS 中的测试应用程序,而不是我的 IIS Express 中的开发应用程序。呵呵!

【讨论】:

  • 我在重定向时遇到了类似的情况,这很有帮助。谢谢!
猜你喜欢
  • 2014-10-28
  • 1970-01-01
  • 1970-01-01
  • 2011-07-01
  • 1970-01-01
  • 2015-03-03
  • 1970-01-01
相关资源
最近更新 更多