简体   繁体   English

Mvc,授权反弹授权用户

[英]Mvc, Authorize bounces authorized users

I'm trying to make a section of a MVC 5 webpage restricted to users of a certain Active directory group, however the [Authorize] attribute (on controller) blocks logged in users aswell. 我正在尝试将MVC 5网页的一部分限制为某个Active目录组的用户,但[Authorize]属性(在控制器上)阻止登录用户。

My Login page code behind looks as follows: 我的登录页面代码如下所示:

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

The user passes and is redirected to Index in Home controller. 用户通过并重定向到Home控制器中的Index。

This controller however has the [Authorized] value set as follows: 但是,该控制器的[授权]值设置如下:

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

And here the user in bounced back to the loginpage, as if he was not Authorized. 在这里,用户反弹回登录页面,好像他没有被授权。

Also this is web.config: 这也是web.config:

In the browser i can see the ADAuthCookie. 在浏览器中,我可以看到ADAuthCookie。

Edit: Ading pictures of Request data: 编辑:找到请求数据的图片:

Account Post: 帐号邮报:

在此输入图像描述

Fiddler: 小提琴手:

在此输入图像描述

Index Get: 索引获取:

在此输入图像描述

Fiddler: 小提琴手:

在此输入图像描述

EDIT: Question has been solved, after going trough the amazing guide linked by in the comments i realised i was never handling my cooke in the Global.asaz.cs Class. 编辑:问题已经解决,经过评论中链接的惊人指南,我意识到我从未在Global.asaz.cs类中处理我的库克。

Adding an overide to Application_PostAuthenticateRequest solved my problem. 在Application_PostAuthenticateRequest上添加一个Overover解决了我的问题。

The code i added ended up using: 我添加的代码最终使用:

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

In global.asax and i also added: 在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);

To my login page. 到我的登录页面。

AuthorizeAttribute checks the HttpContext.User value (an IPrincipal implementation) and the HttpContext.User.Identity value (an IIdentity implementation) . AuthorizeAttribute 检查HttpContext.User值( IPrincipal实现)和HttpContext.User.Identity值( IIdentity实现)

All of the security frameworks (Identity, Membership, etc.) from Microsoft use these interfaces to communicate with MVC/ASP.NET. Microsoft的所有安全框架(身份,成员资格等)都使用这些接口与MVC / ASP.NET进行通信。 If you are using a custom security framework, you also need to implement these interfaces and set them in the AcquireRequestState (if using session state) or PostAuthorizeRequest event. 如果您使用的是自定义安全框架,则还需要实现这些接口并将它们设置在AcquireRequestState (如果使用会话状态)或PostAuthorizeRequest事件中。

See ASP.NET MVC - Set custom IIdentity or IPrincipal for an example of the latter along with custom IPrincipal and IIdentity implementations. 请参阅ASP.NET MVC - 设置自定义IIdentity或IPrincipal以获取后者的示例以及自定义IPrincipalIIdentity实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 对授权和未授权用户使用ASP.NET MVC Controller Action - Using ASP.NET MVC Controller Action with authorized and unauthorized users asp.net MVC安全根文件夹仅适用于授权用户 - asp.net MVC secure root folder only for authorized users 如何在ASP.NET MVC 5中验证未经授权的用户 - How to verify not authorized users in ASP.NET MVC 5 使用 MVC controller 中的 [Authenticate] 属性使用会话授权用户? - Use [Authenticate] attribute in MVC controller using sessions to authorize users? 授权所有未在MVC中分配角色的用户 - Authorize all users that don't have a role assigned in MVC 如何在ASP.NET MVC 4中为特定的授权用户显示特定的html元素 - How to show a specific html elements for specific authorized users in ASP.NET MVC 4 .net MVC:如何仅向授权用户提供静态文件 - .net MVC:How do I serve static files only to authorized users 在 Asp.Net MVC 中存储 Authorize 属性的用户列表的最佳方法是什么? - What is the best way to store Users list for a Authorize attribute in Asp.Net MVC? 如何在asp.net mvc中授权所有页面的用户并根据请求的类型(是否为ajax)进行响应? - how to authorize users in all pages and respond according to the type of request(ajax or not) in asp.net mvc? 如何使用从 ajax 调用获得的 JWT 令牌按 MVC 控制器中的角色授权用户 - How to authorize users by role in MVC Controllers using a JWT token obtained from ajax call
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM