Security icon indicating copy to clipboard operation
Security copied to clipboard

HttpContext.Authentication.SignInAsync() does not set User.Identity.IsAuthenticated to TRUE

Open christiandelbianco opened this issue 9 years ago • 6 comments

I have this simple code:

    [Route("Account")]
    public class LoginController : Controller
    {
        [HttpPost("LogIn")]
        public async Task<IActionResult> LogIn(CredentialsViewModel credentialsViewModel)
        {
            if (this.ModelState.IsValid)
            {
                var claims = new List<Claim> {new Claim(ClaimTypes.Name, credentialsViewModel.UserName)};
                var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
                var principal = new ClaimsPrincipal(identity);

                await HttpContext.Authentication.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);

                // Enable ajax to send authentication cookie in subsequent requests
                this.HttpContext.Response.Headers.Add("Access-Control-Allow-Credentials", "true");
                this.HttpContext.Response.Headers.Add("Access-Control-Allow-Methods", "POST, GET");
            }

            return this.Json(new { IsAuthenticated = this.User.Identity.IsAuthenticated });
        }

        [HttpGet("LogOff")]
        [Authorize(ActiveAuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]
        public async Task<IActionResult> LogOff()
        {
            await HttpContext.Authentication.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            return this.Json(new { IsAuthenticated = this.User.Identity.IsAuthenticated });
        }
    }

It is used async by this page:

<div class="container" style="margin-top: 50px">
    <form>
        USER: <input data-bind="value: user" /><br />
        PASS: <input data-bind="value: password" /><br />

        <hr />

        <input type="button" value="ASYNC LOGIN" data-bind="click:login, visible:!isAuthenticated()" />
        <input type="button" value="LOGOUT" data-bind="click:logout, visible:isAuthenticated()" />
        <a href="/">RELOAD</a>
    </form>
</div>

@section Scripts
{
    <script type="text/javascript">
        $(document).ready(function () {
            var viewModel = function (userName, isAuthenticated)
            {
                var self = this;

                self.user = ko.observable(userName);
                self.password = ko.observable('');
                self.isAuthenticated = ko.observable(isAuthenticated);

                self.login = function ()
                {
                    var antiforgeryTokenModel = {
                        UserName: self.user(),
                        Password: self.password()
                    };

                    $.ajax({
                        url: "/Account/LogIn",
                        type: "POST",
                        dataType: "json",
                        contentType: "application/x-www-form-urlencoded",
                        data: ko.toJS(antiforgeryTokenModel),
                        success: function (result)
                        {
                            self.isAuthenticated(result.IsAuthenticated);
                        },
                        error: function (xhr, ajaxOptions, thrownError)
                        {
                            alert(thrownError);
                        }
                    });
                };

                self.logout = function ()
                {
                    $.ajax({
                        url: "/Account/LogOff",
                        type: "GET",
                        dataType: "json",
                        success: function (result)
                        {
                            self.isAuthenticated(result.IsAuthenticated);
                        },
                        error: function (xhr, ajaxOptions, thrownError)
                        {
                            alert(thrownError);
                        }
                    });
                };
            }

            ko.applyBindings(new viewModel(
                '@this.ViewContext.HttpContext.User.Identity.Name',
                @this.ViewContext.HttpContext.User.Identity.IsAuthenticated.ToString().ToLower()));
        });
    </script>
}

After HttpContext.Authentication.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal) execution, the User.Identity.IsAuthenticated is false.

ezgif com-video-to-gif

The Authentication cookie is sent back to client: indeed, after reloading the page, I can execute the logoff operation.

Anyone can tell me what is wrong ?

In attach zip file containing the project.

WebApplication1.zip

christiandelbianco avatar Feb 18 '17 22:02 christiandelbianco

Nothing is wrong, the sign in operation doesn't change the current request user principal. That only happens on incoming requests once the cookie or bearer token (or whatever thing the type of auth requires to create an identity) is set.

davidfowl avatar Feb 18 '17 23:02 davidfowl

Right, SignIn and SignOut persist (or de-persist) the user for future requests, not this one. You can set HttpContext.User if you want to.

Tratcher avatar Feb 19 '17 04:02 Tratcher

Set it to what?

smiller781 avatar Feb 20 '18 21:02 smiller781

The same ClaimsPrincipal passed to SignIn.

Tratcher avatar Feb 27 '18 21:02 Tratcher

I had this problem as well but then, thanks to the code provided by @christiandelbianco I realised I was creating the ClaimsIdentity without providing the scheme name. This solved my problem.

var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

I wonder why this is necessary, since we are already passing the scheme name to SignInAsync.

BrightSoul avatar Mar 18 '18 20:03 BrightSoul

That's just how IsAuthenticated is implemented: https://github.com/dotnet/corefx/blob/b5c1ceeb5595cf7c923914b7da9f9a4b487d640f/src/System.Security.Claims/src/System/Security/Claims/ClaimsIdentity.cs#L273-L276

Tratcher avatar Mar 18 '18 22:03 Tratcher