weixin_33696822 2017-06-11 15:34 采纳率: 0%
浏览 33

发送已验证的请求

I have an MVC project secured with a asp.net identity:

This is my Login function:

self.login = function () {
    event.preventDefault();
    if (!$('#formLogin').valid()) {
        return false;
    }
    var loginData = {
        grant_type: 'password',
        username: self.userName(),
        password: self.password()
    };
    $.ajax({
        type: 'POST',
        url: '/API/Token',
        data: loginData
    }).done(function (data) {
        // Cache the access token in session storage.
        sessionStorage.setItem(tokenKey, data.access_token);
        self.authenticate();
        //change status of Login button to Logout
        self.redirect('Users');
    }).fail(showError);
}

self.authenticate = function () {
    self.token = sessionStorage.getItem(tokenKey);
    var headers = {};
    console.log(self.token);
    if (self.token) {
        headers.Authorization = 'Bearer ' + self.token;
    }
    $.ajaxSetup({
        headers: headers
    });
}

That works fine, I get the token successfully and the headers are set up correctly.

The problem is that when I try to send a request- for example:

self.getUsers = function () {
    $.get("/API/Users/GetUsers/");
}

I get a 401 error from the server:

"message": "Authorization has been denied for this request."

What am I doing wrong?

  • 写回答

1条回答 默认 最新

  • weixin_33747129 2017-06-11 20:22
    关注

    According to the official documentation of the jQuery.ajax, use this to set custom headers of each request:

    $.ajaxSetup({
        beforeSend: function(xhr) {
            xhr.setRequestHeader('Authorization', '...');
        }
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办