Я пытаюсь добавить пользовательские свойства к ApplicationUser для веб-сайта с использованием аутентификации MVC5 и OWIN. Я читал qaru.site/info/13508/..., и мне нравится, как он интегрируется с базовым контроллером для легкого доступа к новым свойствам. Моя проблема в том, что когда я устанавливаю свойство HTTPContext.Current.User в свой новый IPrincipal, я получаю ошибку с нулевой ссылкой:
[NullReferenceException: Object reference not set to an instance of an object.]
System.Web.Security.UrlAuthorizationModule.OnEnter(Object source, EventArgs eventArgs) +127
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +136
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +69
Вот мой код:
protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
ApplicationUser user = userManager.FindByName(HttpContext.Current.User.Identity.Name);
PatientPortalPrincipal newUser = new PatientPortalPrincipal();
newUser.BirthDate = user.BirthDate;
newUser.InvitationCode = user.InvitationCode;
newUser.PatientNumber = user.PatientNumber;
//Claim cPatient = new Claim(typeof(PatientPortalPrincipal).ToString(), );
HttpContext.Current.User = newUser;
}
}
public class PatientPortalPrincipal : ClaimsPrincipal, IPatientPortalPrincipal
{
public PatientPortalPrincipal(ApplicationUser user)
{
Identity = new GenericIdentity(user.UserName);
BirthDate = user.BirthDate;
InvitationCode = user.InvitationCode;
}
public PatientPortalPrincipal() { }
public new bool IsInRole(string role)
{
if(!string.IsNullOrWhiteSpace(role))
return Role.ToString().Equals(role);
return false;
}
public new IIdentity Identity { get; private set; }
public WindowsBuiltInRole Role { get; set; }
public DateTime BirthDate { get; set; }
public string InvitationCode { get; set; }
public string PatientNumber { get; set; }
}
public interface IPatientPortalPrincipal : IPrincipal
{
WindowsBuiltInRole Role { get; set; }
DateTime BirthDate { get; set; }
string InvitationCode { get; set; }
string PatientNumber { get; set; }
}
Я не нашел много информации о том, как это сделать, я прочитал следующие статьи:
http://blogs.msdn.com/b/webdev/archive/2013/10/16/customizing-profile-information-in-asp-net-identity-in-vs-2013-templates.aspx
http://blogs.msdn.com/b/webdev/archive/2013/07/03/understanding-owin-forms-authentication-in-mvc-5.aspx
Комментарии во второй ссылке указывали мне, возможно, на использование претензий (http://msdn.microsoft.com/en-us/library/ms734687.aspx?cs-save-lang=1&cs-lang=csharp), но связанная с ней статья не показывает как добавить те к IPrincipal
(это то, что HttpContext.Current.User
), или где в конвейере вы должны добавить их в ClaimsIdentity
(который является конкретным классом User
). Я склоняюсь к использованию претензий, но мне нужно знать, где добавить эти новые требования к пользователю.
Даже если претензии - это путь, мне любопытно, что я делаю неправильно с моим обычным IPrincipal, поскольку я, кажется, реализовал все, что ему нужно.
Ответ 1
Я могу заставить что-то работать, используя Claims
основанную на безопасности, поэтому, если вы хотите быстро что-то сделать, это то, что у меня есть на данный момент:
В процессе входа в AccountController
(мой метод находится в SignInAsync
) добавьте новое требование к идентификатору, созданному UserManager
:
private async Task SignInAsync(ApplicationUser user, bool isPersistent)
{
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
identity.AddClaim(new Claim("PatientNumber", user.PatientNumber)); //This is what I added
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
}
Затем в моих базовых классах контроллера я просто добавил свойство:
private string _patientNumber;
public string PatientNumber
{
get
{
if (string.IsNullOrWhiteSpace(_patientNumber))
{
try
{
var cp = ClaimsPrincipal.Current.Identities.First();
var patientNumber = cp.Claims.First(c => c.Type == "PatientNumber").Value;
_patientNumber = patientNumber;
}
catch (Exception)
{
}
}
return _patientNumber;
}
}
Эта ссылка была полезна для информации о требованиях: http://msdn.microsoft.com/en-us/library/ms734687.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1
Обновление для проблемы с IPrincipal
Я отследил его до свойства Identity
. Проблема заключалась в том, что я предоставлял конструктор по умолчанию в классе PatientPortalPrincipal
, который не устанавливал свойство Identity. То, что я закончил делать, это удалить конструктор по умолчанию и вызвать правильный конструктор из Application_PostAuthenticateRequest
, обновленный код ниже
protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
ApplicationUser user = userManager.FindByName(HttpContext.Current.User.Identity.Name);
PatientPortalPrincipal newUser = new PatientPortalPrincipal(user);
newUser.BirthDate = user.BirthDate;
newUser.InvitationCode = user.InvitationCode;
newUser.PatientNumber = user.PatientNumber;
//Claim cPatient = new Claim(typeof(PatientPortalPrincipal).ToString(), );
HttpContext.Current.User = newUser;
}
}
Это заставляет все работать!
Ответ 2
Вы получаете исключение, потому что HttpContext.Current.User.Identity.IsAuthenticated
возвращает false в точке проверки (например, HttpContext.Current.Request.IsAuthenticated
).
Если вы удалите оператор if (HttpContext.Current.User.Identity.IsAuthenticated)
, он будет работать нормально (по крайней мере, эта часть кода).
Я пробовал простую вещь вроде этого:
BaseController.cs
public abstract class BaseController : Controller
{
protected virtual new CustomPrincipal User
{
get { return HttpContext.User as CustomPrincipal; }
}
}
CustomPrincipal.cs
public class CustomPrincipal : IPrincipal
{
public IIdentity Identity { get; private set; }
public bool IsInRole(string role) { return false; }
public CustomPrincipal(string username)
{
this.Identity = new GenericIdentity(username);
}
public DateTime BirthDate { get; set; }
public string InvitationCode { get; set; }
public int PatientNumber { get; set; }
}
Global.asax.cs
protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
CustomPrincipal customUser = new CustomPrincipal(User.Identity.Name);
customUser.BirthDate = DateTime.Now;
customUser.InvitationCode = "1234567890A";
customUser.PatientNumber = 100;
HttpContext.Current.User = customUser;
}
HomeController.cs
public ActionResult Index()
{
ViewBag.BirthDate = User.BirthDate;
ViewBag.InvitationCode = User.InvitationCode;
ViewBag.PatientNumber = User.PatientNumber;
return View();
}
И это работает нормально. Так что если этот код:
userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
ApplicationUser user = userManager.FindByName(HttpContext.Current.User.Identity.Name);
не возвращает действительный (пользовательский) пользовательский объект, проблема связана с оператором if()
.
Ваше обновление выглядит хорошо, и если вы с удовольствием храните данные в виде файлов cookie, вы можете пойти с ним, хотя я лично ненавижу блок catch try {}
.
Вместо этого я делаю следующее:
BaseController.cs
[AuthorizeEx]
public abstract partial class BaseController : Controller
{
public IOwinContext OwinContext
{
get { return HttpContext.GetOwinContext(); }
}
public new ClaimsPrincipal User
{
get { return base.User as ClaimsPrincipal; }
}
public WorkContext WorkContext { get; set; }
}
Я украшаю класс базового контроллера специальным атрибутом.
AuthorizeExAttribute.cs:
public class AuthorizeExAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
Ensure.Argument.NotNull(filterContext);
base.OnAuthorization(filterContext);
IPrincipal user = filterContext.HttpContext.User;
if (user.Identity.IsAuthenticated)
{
var ctrl = filterContext.Controller as BaseController;
ctrl.WorkContext = new WorkContext(user.Identity.Name);
}
}
}
И WorkContext.cs:
public class WorkContext
{
private string _email;
private Lazy<User> currentUser;
private IAuthenticationService authService;
private ICacheManager cacheManager;
public User CurrentUser
{
get
{
var cachedUser = cacheManager.Get<User>(Constants.CacheUserKeyPrefix + this._email);
if (cachedUser != null)
{
return cachedUser;
}
else
{
var user = currentUser.Value;
cacheManager.Set(Constants.CacheUserKeyPrefix + this._email, user, 30);
return user;
}
}
}
public WorkContext(string email)
{
Ensure.Argument.NotNullOrEmpty(email);
this._email = email;
this.authService = DependencyResolver.Current.GetService<IAuthenticationService>();
this.cacheManager = DependencyResolver.Current.GetService<ICacheManager>();
this.currentUser = new Lazy<User>(() => authService.GetUserByEmail(email));
}
Затем я обращаюсь к WorkContext следующим образом:
public class DashboardController : BaseController
{
public ActionResult Index()
{
ViewBag.User = WorkContext.CurrentUser;
return View();
}
}
Я использую Ninject Dependency Resolver для разрешения authService
и cacheManager
, но вы можете пропустить кэширование и заменить authService на идентификатор ASP.NET UserManager
Я считаю.
Я также хотел отдать должное, когда класс WorkContext сильно вдохновлен проектом NugetGallery.
Ответ 3
Я ставлю HttpContext.Current.User - null. Поэтому вместо этого:
if (HttpContext.Current.User.Identity.IsAuthenticated)
вы можете попробовать следующее:
if (HttpContext.Current.Request.IsAuthenticated)
Ответ 4
У меня была такая же ошибка.
Моя проблема заключалась в том, что с анонимными пользователями я не устанавливал параметр IIdentity на IPrincipal. Я сделал это, только когда пользователи вошли в систему с именем пользователя. В противном случае значение IIdentity было нулевым.
Мое решение состояло в том, чтобы всегда устанавливать значение IIdentity. Если пользователь не аутентифицирован (анонимный пользователь), то для параметра IIdentity.IsAuthenticated установлено значение false. В противном случае, true.
Мой код:
private PrincipalCustom SetPrincipalIPAndBrowser()
{
return new PrincipalCustom
{
IP = RequestHelper.GetIPFromCurrentRequest(HttpContext.Current.Request),
Browser = RequestHelper.GetBrowserFromCurrentRequest(HttpContext.Current.Request),
/* User is not authenticated, but Identity must be set anyway. If not, error occurs */
Identity = new IdentityCustom { IsAuthenticated = false }
};
}