简体   繁体   中英

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

After i finish my login code

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

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

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

After RedirectToAction , there is the cookie in broswer.
But when Authorize attribute there is no Authorize.
In my custom Authorize actionfilter ,

httpContext.User.Identity.IsAuthenticated

always return false.

I find a way to get identity below:

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

after this function, i can get the useridenttity.

Is this correct??

If i need users login info , i need call this function everytime is action?

Thank you reply!

Here's my 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());
    }

Just in case someone stumbles upon this in the future. I had the same issue and I was pulling my hair out when I realised that I had set the

CookieSecure = CookieSecureOption.Always

on the CookieAuthenticationOptions class :/

So obviously cookies were only access over https and because my local environment was not setup with https (It used to be) it could not read the cookie.

I have one scenario when published the application to Production server the call httpContext.GetOwinContext().Authentication .AuthenticateAsync("Application") always return null in IE browser. For this case, go to IE browser Internet Options -> Trusted sites, add your identity server application url as trusted site. System works then.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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