2016-05-27 7 views
4

Я пытаюсь сделать раздел веб-страницы MVC 5 ограниченным для пользователей определенной группы Active-каталогов, однако атрибут [Authorize] (на контроллере) также входит в систему для пользователей.Mvc, Authorize отскакивает авторизованных пользователей

Мой Логин кодовую страницу за выглядит следующим образом:

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

Пользователь проходит и перенаправляется на индекс в главном контроллере.

Этот контроллер, однако, имеет [Авторизованный] значение устанавливается следующим образом:

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

А вот пользователя в отыгрался на LoginPage, как если бы он не был уполномочен.

Кроме того, это web.config:

В браузере я могу увидеть ADAuthCookie.

Edit: ADING фотографии Запрос данных:

счета Сообщение:

enter image description here

Скрипач:

enter image description here

Индекс Получить:

enter image description here

Скрипач:

enter image description here

EDIT: Вопрос был решен, после того, как происходит корыто удивительного руководства, объединенное в комментариях я понял, я никогда не был моей обработкой Cooke в Global.asaz.cs классе ,

Добавление справки к 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); 

На моей странице входа.

+0

Вы отлаживали сеанс http с помощью отладчика http, такого как Fiddler? Вы уверены, что файл cookie существует и передается вместе с запросом на домашний/индекс? –

+0

Я добавил фидлер и визуальный студийный вывод/account/login post и следующего/Home/index Получить результаты. – Tobias

ответ

3

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

Все интерфейсы безопасности (Identity, Membership и т. Д.) От Microsoft используют эти интерфейсы для связи с MVC/ASP.NET. Если вы используете настраиваемую инфраструктуру безопасности, вам также необходимо реализовать эти интерфейсы и установить их в AcquireRequestState (при использовании состояния сеанса) или PostAuthorizeRequest.

См. ASP.NET MVC - Set custom IIdentity or IPrincipal для примера последних, а также пользовательские варианты IPrincipal и IIdentity.