2016-07-27 4 views
0

Meine Website benutzt "Login-Formular mit IPrincipal und IIdentityAnmeldung Identität - Nicht in Httpcontext Arbeits

Der Code kann gesehen below._iTs großartige Arbeit wird

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Security.Principal; 
using System.Web; 

namespace FREELANCER.Models 
{ 
    public class UserPrincipal : IPrincipal 
    { 
     private LoginModel LoginInfo; 
     private DemoUsers d = new DemoUsers(); 


     public UserPrincipal(LoginModel log) 
     { 
      LoginInfo = log; 
      Identity = new GenericIdentity(log.Emailaddress); 
     } 

     public IIdentity Identity 
     { 
      get; 
      private set; 

     } 

     public bool IsInRole(string role) 
     { 
      var roles = role.Split(new char[] { ',' }); 
      return roles.Any(r => this.LoginInfo.Roles.Contains(r)); 
     } 
    } 
} 

Aber ich kann das nicht erreichen. Arbeit:

   string name = User.Identity.Name; 
      string AuthenticationType = User.Identity.AuthenticationType; 
      bool ss = User.Identity.IsAuthenticated; 
      bool Inrole =User.IsInRole("Admin"); 

sie sind immer leer, Warum

Ist es wahr, dass das Objekt von IPrincipa? l und IIdentity wird zu HttpContext kopiert und ist daher auf der gesamten Website verfügbar?

NB: namespace FREELANCER.Security 
{ 
    public class UserAuthorize : AuthorizeAttribute 
    { 

     public override void OnAuthorization(AuthorizationContext filterContext) 
     { 
      if (String.IsNullOrEmpty(SessionPersister.UserName)) 
       filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { Controller = "Login", Action = "Login" })); 
      else 
      { 
       DemoUsers ds = new DemoUsers(); 
       UserPrincipal mp = new UserPrincipal(ds.FindUser(SessionPersister.UserName)); 

       if (!mp.IsInRole(Roles)) 
        filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { Controller = "AccessDenied", Action = "Index" })); 
      } 
     } 
    } 
} 

Antwort

0

Nach dem neuen Haupt Objekt erstellen, müssen Sie es auch auf Objektstrom Httpcontext befestigen.

UserPrincipal mp = new UserPrincipal(ds.FindUser(SessionPersister.UserName)); 
HttpContext.Current.User = mp; 
Thread.CurrentPrincipal = mp; 

Zweite Zeile ist Option, wenn Sie Userprincipal von aktuellen Thread nennen entscheiden - Thread.CurrentPrincipal as UserPrincipal.

+0

Bedeutet dies, dass ich dies in Logout tun muss: HttpContext.Current.User = null; Thread.CurrentPrincipal = null; ? – LalA

+0

Nein, Sie müssen null für die Abmeldung nicht zuweisen. Standardmäßig ist "HttpContext.Current.User" bei jeder Anforderung NULL, bis Sie das Principal-Objekt anfügen. – Win

Verwandte Themen