[英]Identity.IsAuthenticated return false in an ASP.Net Web API
After a successful login, the returned value is always false
. 成功登录后,返回的值始终为false
。 I'm using the default Authentication system that's provided by Microsoft.Identity
("Individual User Accounts" option) with no modifications. 我使用的是Microsoft.Identity
提供的默认身份验证系统(“单个用户帐户”选项),没有进行任何修改。 Any thoughts? 有什么想法吗?
[HttpGet]
[Route("get-userId")]
public bool CurrentUserId()
{
return User.Identity.IsAuthenticated;
}
Client-side codes: 客户端代码:
Login.html: 的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: 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)
returns false
. console.log(response)
返回false
。
You need to send the token to the server with each request. 您需要将每个请求将令牌发送到服务器。 Add the following to your Ajax call: 将以下内容添加到您的Ajax调用中:
headers: { "Authorization": 'Bearer ' + token }
You can rewrite your code like this: 您可以这样重写代码:
$(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.