繁体   English   中英

ASP.Net Web API中的Identity.IsAuthenticated返回false

[英]Identity.IsAuthenticated return false in an ASP.Net Web API

成功登录后,返回的值始终为false 我使用的是Microsoft.Identity提供的默认身份验证系统(“单个用户帐户”选项),没有进行任何修改。 有什么想法吗?

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

客户端代码:

的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)返回false

您需要将每个请求将令牌发送到服务器。 将以下内容添加到您的Ajax调用中:

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

您可以这样重写代码:

      $(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);
                }
            });

暂无
暂无

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

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