繁体   English   中英

登录后c#owin无法获取User.Identity

[英]c# owin can't get User.Identity after signin

完成登录代码后

        var identity = new ClaimsIdentity(claims, OAuthConfigur.AuthenticationType);

        this.AuthenticationManager.SignIn(new AuthenticationProperties
        {
            ExpiresUtc = DateTimeOffset.Now.AddMinutes(30),
            IsPersistent = false
        }, identity);

        return RedirectToAction("Index", "Home");

在RedirectToAction之后,浏览器中有cookie。
但是,当Authorize属性没有授权时。
在我的自定义“授权”操作过滤器中,

httpContext.User.Identity.IsAuthenticated

总是返回false。

我在下面找到一种获得身份的方法:

    private ClaimsIdentity GetIdentity(HttpContextBase httpContext)
    {
        var ticket = httpContext.GetOwinContext().Authentication
                .AuthenticateAsync(OAuthConfigur.AuthenticationType).Result;
        var identity = ticket != null ? ticket.Identity : null;
        return identity;
    }

使用此功能后,我可以获得用户身份。

这个对吗??

如果我需要用户登录信息,则每次执行操作时都需要调用此函数?

谢谢回复!

这是我的Startup.cs

 public void ConfigureAuth(IAppBuilder app)
    {
        // Enable Application Sign In Cookie
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = OAuthConfigur.AuthenticationType,
            AuthenticationMode = AuthenticationMode.Passive,
            LoginPath = new PathString(OAuthPaths.LoginPath),
            LogoutPath = new PathString(OAuthPaths.LogoutPath),
            ExpireTimeSpan = TimeSpan.FromMinutes(20)
        });

        // Setup Authorization Server
        app.UseOAuthAuthorizationServer(new CustomerOAuthAuthorizationServerOptions());
    }

以防万一将来有人偶然发现这一点。 我遇到了同样的问题,当我意识到自己已经设置好

CookieSecure = CookieSecureOption.Always

在CookieAuthenticationOptions类上:/

因此很明显,cookie只能通过https访问,并且因为我的本地环境未使用https设置(过去是),因此无法读取cookie。

在将应用程序发布到生产服务器时,我遇到一种情况,调用httpContext.GetOwinContext()。Authentication .AuthenticateAsync(“ Application”)在IE浏览器中始终返回null。 对于这种情况,请转到IE浏览器的Internet选项->可信站点,将您的身份服务器应用程序URL添加为可信站点。 系统即可正常工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM