How to read MVC OWIN AuthenticationProperties?

2019-04-03 22:29发布

I'm setting IsPersistent when signing the user in, how to read that value back?

var identity = await UserManager.CreateIdentityAsync(appUser, DefaultAuthenticationTypes.ApplicationCookie);
HttpContext.GetOwinContext().Authentication.SignIn(new AuthenticationProperties() { IsPersistent = false }, identity);

7条回答
一夜七次
2楼-- · 2019-04-03 23:10
var authenticationInfo = await HttpContext.Authentication.GetAuthenticateInfoAsync(DefaultAuthenticationTypes.ApplicationCookie);
authenticationInfo.Properties ...

I asume DefaultAuthenticationTypes.ApplicationCookie contains cookie authentication scheme.

查看更多
疯言疯语
3楼-- · 2019-04-03 23:13

Since there isn't much description, I am not sure about the context. Anyway, you can get all the AuthenticationProperties that were provided with the sign in call when you perform authentication on the current request. Code would be..

AuthenticateResult authenticateResult = await HttpContext.GetOwinContext().Authentication.AuthenticateAsync(DefaultAuthenticationTypes.ApplicationCookie);

AuthenticationProperties yourAuthenticationProperties = authenticateResult.Properties;
查看更多
再贱就再见
4楼-- · 2019-04-03 23:20

AspNet.Identity gives you access to the bool value of IsPersistent for the session. The most direct way to read its value is to call AuthenticateAsync():

@using Microsoft.AspNet.Identity;
var authenticateResult = await HttpContext.GetOwinContext()
                           .Authentication.AuthenticateAsync(
                               DefaultAuthenticationTypes.ApplicationCookie
                           );
var isPersistent = authenticateResult.Properties.IsPersistent; //// true or false

Note that you will need to wrap this in an async method, such as:

@using System.Threading.Tasks;
public async Task<ActionResult> SomeMethodName(...) { //etc }
查看更多
Luminary・发光体
5楼-- · 2019-04-03 23:20

AuthenticateResult authenticateResult = await HttpContext.GetOwinContext().Authentication.AuthenticateAsync(DefaultAuthenticationTypes.ApplicationCookie);

AuthenticationProperties yourAuthenticationProperties = authenticateResult.Properties;

查看更多
Explosion°爆炸
6楼-- · 2019-04-03 23:24

can you please try this, I haven't test it

IAuthenticationManager AuthenticationManager
{
  get { return HttpContext.GetOwinContext().Authentication; }
}
查看更多
啃猪蹄的小仙女
7楼-- · 2019-04-03 23:24

As @Nkosi said you can not retrieve the information from the OWIN, because it's not stored there, you need to retrieve the cookie itself and parse the information manually, but for that you will need a OWIN Middleware like this one so you can manipulate your cookie as you want.

查看更多
登录 后发表回答