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 逻辑谓词和消解原理的运用
  • ¥15 请求分析基于spring boot+vue的前后端分离的项目
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥200 关于#c++#的问题,请各位专家解答!网站的邀请码
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?