我正在尝试使用没有身份的Owin。在我的登录过程中,我正在添加如下声明:
[HttpPost]
[AllowAnonymous]
public ActionResult Login(Domain.Model.User.User model, string returnUrl)
{
var response = someFunctionCall();
AuthData data = response.authdata;
IEnumerable<Claim> claim = new List<Claim>(){
new Claim(ClaimTypes.CookiePath, MvcApplication.ApplicationPath),
new Claim(ClaimTypes.Name, model.UserId),
new Claim(Constants.ClaimsConstants.1customClaim, data.1customClaim),
new Claim(Constants.ClaimsConstants.2customClaim, data.2customClaim)
};
ClaimsIdentity id = new ClaimsIdentity(claim, CookieAuthenticationDefaults.AuthenticationType);
HttpContext.GetOwinContext().Authentication.SignIn(new AuthenticationProperties() { IsPersistent = true }, id);
return RedirectToAction("Index", "Home");
}
在我的启动类中,我在提供程序中的OnResponseSigned中设置我将Thread.CurrentPrinipal Context.OwinContext.Authentcation设置为IPrincipal。像这样:
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
CookieSecure = CookieSecureOption.Always,
LoginPath = new PathString("/Account/Login"),
AuthenticationMode = AuthenticationMode.Active,
Provider = new CookieAuthenticationProvider
{
OnResponseSignedIn = (context =>
{
OnSignedInResponse(context);
})
)}
}
private void OnSignedInResponse(CookieResponseSignedInContext context)
{
Thread.CurrentPrincipal = context.OwinContext.Authentication as IPrincipal;
}
稍后在应用程序中我需要接受索赔,但我似乎无法做到这一点。
private static readonly ClaimsPrincipal user = Thread.CurrentPrincipal as ClaimsPrincipal;
private static readonly IEnumerable<Claim> claims = user.Claims;
public static CustomUserInfo Idenitiy
{
get
{
UserInfo user = new UserInfo()
{
Custom1 = claims.Where(c => c.Type == Constants.ClaimsConstants.1customClaim).First().Value,
Custom2 = claims.Where(c => c.Type == Constants.ClaimsConstants.2customClaim).First().Value
};
return user;
}
}
不确定我是否应该使用Owin上下文或者我是否可以使用Thread.current上下文。当我检查Thread.CurrentPrincipal时,似乎没有声明。有什么想法吗?
答案 0 :(得分:0)
这是一个解决方法,但为了解决这个问题,我去了并获得了owin上下文而不是使用Thread.CurrentPrincipal。像这样:
private static readonly ClaimsPrincipal user = System.Web.HttpContext.Current.GetOwinContext().Authentication.User as ClaimsPrincipal;
private static readonly IEnumerable<Claim> claims = user.Claims;
public static CustomUserInfo Idenitiy
{
get
{
UserInfo user = new UserInfo()
{
Custom1 = claims.Where(c => c.Type == Constants.ClaimsConstants.1customClaim).First().Value,
Custom2 = claims.Where(c => c.Type == Constants.ClaimsConstants.2customClaim).First().Value
};
return user;
}
}
仍然不确定为什么Thread.CurrentPrincipal不起作用。