我正在为我的 React 应用程序使用 Oauth 2.0。当我从用户那里获得 google 登录同意时,重定向网址为“http://localhost:3000/google/auth”,我在其中处理 获取访问令牌、注册/记录用户和发送 JWT饼干 零件。
JWT cookie 设置为 http://localhost:5173 这是我的 vite React 前端,我很难理解这个 cookie 是如何设置的,因为请求实际上来自 google 同意页面到 google/auth 路由,而不是来自 localhost:5173 前端。
cookie 是否始终设置为请求最终来自的原始主机?
oAuthrRedect (/oauth) 负责使用 Auth 服务器 url 提供前端登录页面。
oAuthCallback (/google/auth) 负责来自同意页面的回调
logIn(子功能)执行用户创建/登录、设置JWT cookie等
const oAuthRedirect = async (req, res) => {
const state = "some_state";
const scopes = GOOGLE_OAUTH_SCOPES.join(" ");
const GOOGLE_OAUTH_CONSENT_SCREEN_URL = `${GOOGLE_OAUTH_URL}?client_id=${GOOGLE_CLIENT_ID}&redirect_uri=${GOOGLE_CALLBACK_URL}&access_type=offline&response_type=code&state=${state}&scope=${scopes}`;
res.send(GOOGLE_OAUTH_CONSENT_SCREEN_URL);
// window.location.href=GOOGLE_OAUTH_CONSENT_SCREEN_URL;
}
const logIn = async (email, profilePic, { req, res }) => {
try {
const data = await userModel.exists({ username: email });
console.log(data)
if (!data) throw "userNotExist"
// Creating JWT cookie for user
var id = data._id;
const token = jwt.sign({ id }, 'bar', { expiresIn: 1 * 24 * 60 * 60 });
res.cookie("jwt", token, {
withCredentials: true,
httpOnly: false,
maxAge: 1 * 24 * 60 * 60 * 1000,
});
res.status(200).json({
userId: data._id,
message: "User is welcome!",
})
// res.redirect('http://localhost:5173/homepage');
} catch (err) {
if (err == 'userNotExist') {
userModel.create({ username: email }).then((data) => {
console.log("User doesn't exist")
var id = data._id;
const token = jwt.sign({ id }, 'bar', { expiresIn: 1 * 24 * 60 * 60 });
res.cookie("jwt", token, {
withCredentials: true,
httpOnly: false,
maxAge: 1 * 24 * 60 * 60 * 1000,
});
res.status(200).json({
userId: id,
message: "User is welcome!",
})
})
}
}
}
const oAuthCallback = async (req, res) => {
// Getting authentication code
var { code } = req.query;
var data = {
code,
client_id: GOOGLE_CLIENT_ID,
client_secret: GOOGLE_CLIENT_SECRET,
redirect_uri: "http://localhost:3000/google/auth",
grant_type: "authorization_code",
}
// Getting access token
const response = await fetch(GOOGLE_ACCESS_TOKEN_URL, {
method: "POST",
body: JSON.stringify(data),
});
try {
const access_token_data = await response.json();
if (access_token_data.error) {
throw access_token_data.error
}
var accessToken = access_token_data.access_token;
if (access_token_data.refresh_token) var refreshToken = access_token_data.refresh_token
var idToken = access_token_data.id_token
console.log("Access token: " + accessToken + "\n" + "refreshToken: " + (refreshToken ? refreshToken : '\n') + "Id token: " + idToken);
// Getting token information
var tokenInfoResponse = await fetch(GOOGLE_TOKEN_INFO_URL + "?id_token=" + idToken);
tokenInfoResponse = await tokenInfoResponse.json();
var email = tokenInfoResponse.email;
var profilePic = tokenInfoResponse.picture;
logIn(email, profilePic, { req: req, res: res });
} catch (error) {
console.log(error + "This is an error");
}
}
// Go handling social button click
const handleSocialLogin = async (e, socialLoginType) => {
console.log(socialLoginType);
socialLoginMediator();
}
const socialLoginMediator = async () =>{
try {
// Getting auth url for social loginj
const {data} = await axios.get("http://localhost:3000/oauth")
const authUrl = data;
// Showing consent page
window.location.href=authUrl
} catch (err) {
console.log(err)
}
}
同意页面: 这是从我设置为 http://localhost:3000/google/auth 的 callback url 被调用的地方。
我需要知道当从google页面发出请求时,cookie是如何设置为localhost:5173
另外,我可以使用任何指示来了解如何更好地理解这些概念以及幕后的所有内容如何工作。
谢谢!
设置 Cookie 域 -> 在后端代码中,在响应中设置 JWT cookie 时,将 cookie 的域属性显式设置为 localhost:5173。
res.cookie("jwt", token, {
domain: "localhost:5173",
httpOnly: false,
maxAge: 1 * 24 * 60 * 60 * 1000,
});
通过将域指定为 localhost:5173,您可以确保 cookie 与该域关联,从而允许您的前端 React 应用程序访问它。
进行此更改后,彻底测试您的身份验证流程,以确保 JWT cookie 设置正确并且您的 React 应用程序可以访问它。
通过显式设置 cookie 域,您可以绕过与请求来源相关的任何潜在问题,并确保为前端 React 应用程序运行的正确域设置 cookie。
设置 Cookie 时,请务必考虑安全影响,例如根据应用程序的要求设置适当的标志,如 httpOnly 和 secure。