【发布时间】: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