MVC中,授权反弹授权用户 [英] Mvc, Authorize bounces authorized users

查看:158
本文介绍了MVC中,授权反弹授权用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做出限制在一定的Active Directory组的用户MVC 5网页的一部分,但是[授权]属性(控制器),登录的用户藏汉块。

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.

我的登录页code后面看起来如下:

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

用户通过与被重定向到指数Home控制器。

The user passes and is redirected to Index in Home controller.

此控制器已但是在[授权]值设置如下:

This controller however has the [Authorized] value set as follows:

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

和这里反弹到loginpage,好像他没有被授权用户。

And here the user in bounced back to the loginpage, as if he was not Authorized.

另外这是web.config中:

Also this is web.config:


        
    

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

In the browser i can see the ADAuthCookie.

编辑:请求数据Ading图片:

Ading pictures of Request data:

帐户帖子:

在这里输入的形象描述

菲德勒:

在这里输入的形象描述

指数获得:

在这里输入的形象描述

菲德勒:

在这里输入的形象描述

编辑:问题已经解决,去槽惊人的导游在评论链接我意识到我从来没有处理我在Global.asaz.cs类库克之后

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.

添加到超越控制解决Application_PostAuthenticateRequest我的问题。

Adding an overide to Application_PostAuthenticateRequest solved my problem.

在$ C C I添加结束了使用:

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

在Global.asax中,我也补充说:

In global.asax and i also added:

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 检查 HttpContext.User中值(的IPrincipal 实施)和 HttpContext.User.Identity 值(的IIdentity 实施)

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

所有微软的安全框架(身份,会员等)使用这些接口与MVC / ASP.NET进行通信。如果您使用的是自定义的安全框架,还需要实现这些接口,并设置他们在的AcquireRequestState (如果使用会话状态)或 PostAuthorizeRequest 事件。

All of the security frameworks (Identity, Membership, etc.) from Microsoft use these interfaces to communicate with 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.

请参阅 ASP.NET MVC - 设置自定义的IIdentity或IPrincipal的后者沿自定义<$ C为例$ C>的IPrincipal 和的IIdentity 的实现。

See ASP.NET MVC - Set custom IIdentity or IPrincipal for an example of the latter along with custom IPrincipal and IIdentity implementations.

这篇关于MVC中,授权反弹授权用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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