简体   繁体   中英

Identity.IsAuthenticated return false in an ASP.Net Web API

After a successful login, the returned value is always false . I'm using the default Authentication system that's provided by Microsoft.Identity ("Individual User Accounts" option) with no modifications. Any thoughts?

        [HttpGet]
        [Route("get-userId")]
        public bool CurrentUserId()
        {
            return User.Identity.IsAuthenticated;
        }

Client-side codes:

Login.html:

        $(document).ready(function () {

            $('#btnLogin').click(function () {
                $.ajax({

                    url: '/token',
                    method: 'POST',
                    contentType: 'application/json',
                    data: {
                        username: $('#txtUsername').val(),
                        password: $('#txtPassword').val(),
                        grant_type: 'password'
                    },
                    success: function (response) {
                        sessionStorage.setItem("accessToken", response.access_token);
                        window.location.href = "Momo.html";
                    },

                    error: function (jqXHR) {
                        $('#divErrorText').text(jqXHR.responseText);
                        $('#divError').show('fade');
                    }
                });
            });
        });

Momo.html:

    $(document).ready(function () {
                if (sessionStorage.getItem('accessToken') == null) {
                    window.location.href = "Login.html";
                }

                $.ajax({
                    url: '/api/Account/get-userId',
                    method: 'GET',
                    success: function (response) {
                        console.log(response);
                    }
                });

console.log(response) returns false .

You need to send the token to the server with each request. Add the following to your Ajax call:

headers: { "Authorization": 'Bearer ' + token }

You can rewrite your code like this:

      $(document).ready(function () {
            var token = sessionStorage.getItem('accessToken');
            if (token == null) {
                window.location.href = "Login.html";
            }

            $.ajax({
                url: '/api/Account/get-userId',
                method: 'GET',
                headers: { "Authorization": 'Bearer ' + token },
                success: function (response) {
                    console.log(response);
                }
            });

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