【问题标题】:Identity.IsAuthenticated return false in an ASP.Net Web APIIdentity.IsAuthenticated 在 ASP.Net Web API 中返回 false
【发布时间】:2019-09-06 14:20:45
【问题描述】:

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

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

客户端代码:

登录.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');
                    }
                });
            });
        });

陌陌.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

【问题讨论】:

    标签: javascript c# jquery .net asp.net-web-api


    【解决方案1】:

    您需要在每个请求中将令牌发送到服务器。将以下内容添加到您的 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);
                    }
                });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-05
      • 2013-01-14
      • 2015-01-05
      • 1970-01-01
      • 2020-03-21
      • 1970-01-01
      • 2018-07-17
      相关资源
      最近更新 更多