成功登录后,返回的值始终为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
。
答案 0 :(得分: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);
}
});