c# - Mvc,授权退回授权用户

标签 c# asp.net-mvc authentication forms-authentication owin

我正在尝试将 MVC 5 网页的一部分限制为特定 Active directory 组的用户,但是 [Authorize] 属性(在 Controller 上)也会阻止登录用户。

我的登录页面代码如下:

public class AccountController: Controller
{

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

    // POST: /Account/Login
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Login(LoginModel model, string returnUrl)
    {
        if (ModelState.IsValid)
        {
            ActiveDirectoryHelper ad = new ActiveDirectoryHelper();

            if (Membership.ValidateUser(model.UserName, model.Password))
            {
                if (ad.CheckGroupMembership(model.UserName))
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);

                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Credentials are correct but you are no authorised \n You Need membership in group: HKF-HIT-FortigateAPI-GS");
                }
            }
            else
            {
                ModelState.AddModelError("", "The user name or password provided is incorrect");
            }
        }
        // if we got this far, something failed, redisplay form
        return View(model);
    }
    // POST: /Account/LogOff
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult LogOff()
    {
        FormsAuthentication.SignOut();
        return RedirectToAction("Index", "Home");
    }
}
public class ActiveDirectoryHelper
{
    string group = "HKF-HIT-FortigateAPI-GS";
     public bool CheckGroupMembership(string name)
    {
        var context = new PrincipalContext(
                            ContextType.Domain,
                            "AD-Domain", @"Username", "Password");

        var userPrincipal = UserPrincipal.FindByIdentity(
                            context,
                            IdentityType.SamAccountName,
                            name);

        var test = userPrincipal;

        if (userPrincipal.IsMemberOf(context,
             IdentityType.Name,
             group))
        {
            return true;
        }
        return false;
    }
}

用户通过并被重定向到 Home Controller 中的 Index。

然而,此 Controller 的 [Authorized] 值设置如下:

[Authorize]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
}

此时用户跳回登录页面,就好像他没有获得授权一样。

这也是 web.config:

在浏览器中我可以看到 ADAuthCookie。

编辑:添加请求数据图片:

帐号发布:

enter image description here

fiddler :

enter image description here

索引获取:

enter image description here

fiddler :

enter image description here

编辑:问题已经解决,在阅读了评论中链接的惊人指南后,我意识到我从未在 Global.asaz.cs 类中处理过我的 cooke。

向 Application_PostAuthenticateRequest 添加覆盖解决了我的问题。

我添加的代码最终使用:

protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
    HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];

    if (authCookie != null)
    {
        FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);

        JavaScriptSerializer serializer = new JavaScriptSerializer();

        CustomPrincipalSerializeModel serializeModel = serializer.Deserialize<CustomPrincipalSerializeModel>(authTicket.UserData);

        CustomPrincipal newUser = new CustomPrincipal(authTicket.Name);
        newUser.Name = serializeModel.Name;
        HttpContext.Current.User = newUser;
    }
}

在 global.asax 中,我还添加了:

CustomPrincipalSerializeModel serializeModel = new CustomPrincipalSerializeModel();
serializeModel.Name = model.UserName;

JavaScriptSerializer serializer = new JavaScriptSerializer();

string userData = serializer.Serialize(serializeModel);

FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
         1,
         model.UserName,
         DateTime.Now,
         DateTime.Now.AddMinutes(15),
         false,
         userData);

string encTicket = FormsAuthentication.Encrypt(authTicket);
HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
Response.Cookies.Add(faCookie);

到我的登录页面。

最佳答案

AuthorizeAttribute checks the HttpContext.User value (an IPrincipal implementation) and the HttpContext.User.Identity value (an IIdentity implementation) .

Microsoft 的所有安全框架(身份、成员资格等)都使用这些接口(interface)与 MVC/ASP.NET 进行通信。如果您使用自定义安全框架,您还需要实现这些接口(interface)并在 AcquireRequestState(如果使用 session 状态)或 PostAuthorizeRequest 事件中设置它们。

参见 ASP.NET MVC - Set custom IIdentity or IPrincipal有关后者以及自定义 IPrincipalIIdentity 实现的示例。

关于c# - Mvc,授权退回授权用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37483817/

相关文章:

c# - 如何获取每个 DbContext 下的所有 DbContext 类和所有 DbSet

javascript - 我想要一个 jquery 函数来显示成功登录时隐藏的列表项

javascript - 使用 JavaScript 隐藏特定日期的面板

asp.net - 限制每页表中的行数

android - Google Plus 单点登录服务器流程 - Google_AuthException 获取 OAuth2 访问 token 时出错,消息 : 'invalid_grant'

c# - Xamarin 从 INavigationService 形成 MVVM 清晰导航堆栈

c# - MySqlCommand.ExecuteReader() 在初始化时抛出 System.Format 异常

asp.net - 当值不为空时在 ASP.NET MVC View 中输出值的简洁方法

javascript - 为什么我的用户登录逻辑不起作用?

windows-7 - RDP 中的用户名或密码不正确