如何登录谷歌在React Native为前端和NodeJS mongodb为后端?
你可以使用这个"react-native-google-signin"库在前端。
这是
的用法import {GoogleSignin, statusCodes} from 'react-native-google-signin';
useEffect(() => {
configureGoogleSign();
}, []);
function configureGoogleSign() {
GoogleSignin.configure({
webClientId: WEB_CLIENT_ID,
offlineAccess: false,
});
}
const signIn = async () => {
try {
await GoogleSignin.hasPlayServices();
const userInfo = await GoogleSignin.signIn();
setgmail(userInfo);
//Navigate user where you want and store information
} catch (error) {
if (error.code === statusCodes.SIGN_IN_CANCELLED) {
// user cancelled the login flow
} else if (error.code === statusCodes.IN_PROGRESS) {
// operation (f.e. sign in) is in progress already
} else if (error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) {
// play services not available or outdated
} else {
// some other error happened
}
}
};
对于后端,您需要验证将由前端发送的用户访问令牌。
await axios({
method: 'get',
url: 'https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=' + access_token,
withCredentials: true
})
.then(function (response) {
console.log('response==>', response.data);
flag = true;
id = response.data.kid
})
.catch(function (response) {
console.log('error');
});
改进@Awais Ibrar的答案
不发送访问令牌,而是在请求头中从前端发送授权码,在后端使用授权码获取访问令牌。
注意-攻击者可以很容易地插入访问令牌,因为访问令牌的来源不能轻易验证。 来源:Google Developer Documentation
步骤1:从Google Cloud Console的GMAIL API获取凭证(OAuth 2.0客户端id)
步骤2:在React Native中import { GoogleSignin, statusCodes } from '@react-native-google-signin/google-signin';
function configureGSignin() {
GoogleSignin.configure({
androidClientId: 'ANDROID_CLIENT from Google Cloud Console',
scopes: ['https://www.googleapis.com/auth/gmail.readonly'],
// find more scopes here https://developers.google.com/identity/protocols/oauth2/scopes#gmail
webClientId: `WebClientId from Google Cloud Console`,
offlineAccess: true, // if you want to process data on backend
iosClientId: `IOS_CLIENT_ID from Google Cloud Console`,
});
}
const signIn = async () => {
try {
await GoogleSignin.hasPlayServices();
const userInfo = await GoogleSignin.signIn();
//save details of userInfo in the frontend and request backend using userinfo.serverAuthCode
//Navigate user where you want and store information
} catch (error) {
if (error.code === statusCodes.SIGN_IN_CANCELLED) {
// user cancelled the login flow
} else if (error.code === statusCodes.IN_PROGRESS) {
// operation (f.e. sign in) is in progress already
} else if (error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) {
// play services not available or outdated
} else {
// some other error happened
}
}
};
function backendRequest() {
const url = 'YOUR_BACKEND_URL';
const serverAuthCode = the_same_code_you_get_in_userinfo
axios.post(url,{body data},{ headers: {
Authorization: `Basic ${serverAuthCode}`,
'Content-Type': 'application/json',
},
},
)
.then(function (response) {
//on successful request
})
.catch(function (error) {
//on error
})
.finally(function () {
// always executed
});
}
后端步骤2
router.post("/", async (req, res) => {
try {
const token = req.headers.authorization.split(" ")[1];
getAccessToken(token);
res.status(200).send("OK");
} catch (error) {
res.status(401).send("Unauthorized");
}});
async function getAccessToken(code) {
try {
const { tokens } = await oAuth2Client.getToken(code);
logger.info("Tokens : ", tokens);
saveCredentials(tokens);
} catch (err) {
logger.info("Error :", err);
}
}