提问人:user22761301 提问时间:11/4/2023 最后编辑:jpsuser22761301 更新时间:11/5/2023 访问量:177
调用API时如何使用相同的cookie?
How to use same cookie when call API?
问:
我有 .Net Core API 7 的应用程序,我的应用程序将在用户登录时按会话保存用户信息,就像这段代码一样
public int _UserId
{
get
{
if (HttpContext.Session.GetInt32("UserId") == null)
{
HttpContext.Session.SetInt32("UserId", 0);
}
return (int)HttpContext.Session.GetInt32("UserId");
}
set
{
HttpContext.Session.SetInt32("UserId", value);
}
}
当用户调用其他 api 时,我的程序将自动获取会话并使用它。当我使用 Postman 和 Swagger Ui 时,它运行良好。
问题是当我通过js调用api时,它不在同一个cookie中(我真的不知道该怎么称呼它)。在下面的代码中,我调用登录 API,成功后,我的程序将保存会话。然后我调用 api 来获取我之前保存的会话,但我无法获得结果,因为我调用的两个函数不在同一个 cookie 中GetCurrentUser
async function callApiLogin(username, password) {
const xhttp = new XMLHttpRequest();
const url = "http://localhost:5296/api/Account/Login";
xhttp.open("POST", url, true);
xhttp.setRequestHeader("Content-Type", "application/json");
xhttp.onload = function () {
if (xhttp.status === 200) {
const response = xhttp.responseText;
console.log(response);
} else {
// Handle error
}
};
const data = {
username: username,
password: password,
};
xhttp.send(JSON.stringify(data));
}
callApiLogin("string1", "string");
console.log("Login completed");
setTimeout(() => {
const xhttp = new XMLHttpRequest();
const url = "http://localhost:5296/api/User/GetCurrentUser"; // Replace with the actual API endpoint
xhttp.open("GET", url, true);
xhttp.setRequestHeader("Content-Type", "application/json");
xhttp.onload = function () {
if (xhttp.status === 200) {
const response = xhttp.responseText;
console.log(response);
} else {
// Handle error
}
};
xhttp.send();
}, 5000);
如何像 Swagger 和 Postman 一样在同一个 cookie 中通过 js 调用 API?
我应该使用 JWT 令牌而不是会话吗?
答:
0赞
Long Trương
11/5/2023
#1
在这种情况下,XML 请求不会自动包含 cookie。尝试这样的事情:
评论
0赞
user22761301
11/9/2023
我不能在我的 .net 核心代码中允许凭据。我尝试类似 learn.microsoft.com/en-us/aspnet/core/security/...。但它不起作用
0赞
user22761301
11/10/2023
哦,我自己做。只需使用 Althought,我使用 .当我使用 api 登录时,后端代码仍然没有返回我已保存的会话app.UseCors(x => x .AllowAnyMethod() .AllowAnyHeader() .SetIsOriginAllowed(origin => true) // allow any origin //.WithOrigins("https://localhost:44351")); // Allow only this origin can also have multiple origins separated with comma .AllowCredentials()); // allow credentials
xhttp.withCredentials = true
0赞
abeomer
11/5/2023
#2
从 JavaScript 发出请求时,您需要确保在请求中包含 cookie。您可以使用 fetch API 或 Axios 执行此操作。下面是一个使用 fetch 的示例。
const loginData = {
username: "your_username",
password: "your_password"
};
// Perform a login request
fetch('http://localhost:5296/api/Account/Login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(loginData),
credentials: 'include', // Include credentials (cookies)
})
.then(response => {
if (response.ok) {
// Successfully logged in
// You can make other authenticated requests here
} else {
// Handle login error
}
});
评论
0赞
abeomer
11/5/2023
我忘了提:您需要在后端服务中添加 cookie 身份验证,并且您还需要添加 CORS 策略并启用 allowcredentials 以确保 cookie 不受约束。
0赞
user22761301
11/9/2023
我不能在我的 .net 核心代码中允许凭据。我尝试类似 learn.microsoft.com/en-us/aspnet/core/security/...。但它不起作用
0赞
user22761301
11/10/2023
哦,我自己做。只需使用 Althought,我使用 xhttp.withCredentials = true。当我使用 api 登录时,后端代码仍然没有返回我已保存的会话app.UseCors(x => x .AllowAnyMethod() .AllowAnyHeader() .SetIsOriginAllowed(origin => true) // allow any origin //.WithOrigins("https://localhost:44351")); // Allow only this origin can also have multiple origins separated with comma .AllowCredentials()); // allow credentials
评论