[英]HttpContext.Current.User.Identity.Name is always null
[英]HttpContext.Current.User.Identity.Name is null after setting custom principal in GrantResourceOwnerCredentials in my owin authorization provider
這是我的GrantResourceOwnerCredentials方法:
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
AccountModels.UserProfile user = ApplicationUserManager.UserLogin(new AccountModels.LoginModel { UserName = context.UserName , Password = context.Password, RememberMe= false });
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
else
{
if (user.IsLoggedIn = false)
{
context.SetError("invalid_grant", "The user is no longer active. Please contact support for account activation");
return;
}
else
{
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
identity.AddClaim(new Claim(ClaimTypes.Role, user.UserRole));
var roles = new string[] {user.UserRole};
AuthenticationProperties properties = CreateProperties(user.UserName, roles, user.IsEmilConfirmed);
AuthenticationTicket ticket = new AuthenticationTicket(identity, properties);
context.Validated(ticket);
MyCustomPrincipal newUser = new MyCustomPrincipal(user.UserName);
newUser.Id = user.UserID;
newUser.Email = user.UserName;
newUser.Role = user.UserRole;
SetPrincipal(newUser);
context.Request.Context.Authentication.SignIn(identity);
}
}
}
我必須實現一個自定義登錄邏輯來支持我的舊數據庫模式,登錄后我想在httpcontext.current.user中設置剛剛登錄的用戶。
這是我的SetPrincipal方法:
private static void SetPrincipal(IPrincipal principal)
{
Thread.CurrentPrincipal = principal;
if (HttpContext.Current != null)
{
HttpContext.Current.User = principal;
}
}
授權后,每當我在控制器中調用HttpContext.Current.User.Identity.Name時,我都會得到null值。 我在這里失蹤了什么? 任何人都可以給我任何想法嗎?
嘗試使用控制器中的User
對象:
var principal = User as ClaimsPrincipal;
附注:來電SetPrincipal
沒有必要在GrantResourceOwnerCredentials如果您使用OWIN托管。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.