我在使用前端的password-google进行用户身份验证时遇到了挑战。
当前,我有一个应用程序,可让您在发送令牌并在响应中传递令牌后在本地注册和登录。如果设置了令牌,则在前端对应用程序进行身份验证,如果没有用户令牌,则对前端(反应侧)进行未认证。
我如何在passport-google中使用此逻辑?
此刻,此逻辑给了我一个cors错误。并且我启用了cors和东西,并且我的react port服务器被接受为cors的来源。 Express在3000上运行,而react在3001上运行。
在以下位置访问XMLHttpRequest 'https://accounts.google.com/o/oauth2/v2/auth?response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fauth%2Fgoogle%2Fcallback&scope=profile&client_id=414221829387-squf9po9h437tjkknkc0c4foq6734fo7.apps.googleusercontent.com' (从“ http://localhost:3000/users/auth/google”重定向) 原点“ null”已被CORS政策阻止:否 请求中存在“ Access-Control-Allow-Origin”标头 资源。
Axios的基本URL设置为localhost:3000
我如何在客户端称呼护照Google。
render(){
const googleLogin = response => {
let googleData;
googleData = {
googleID: response.profileObj.googleId,
email: response.profileObj.email,
password: "",
};
this.props.googleLogin(googleData);
};
return(
........
<form onSubmit={this.handleSubmit}>
....
</form>
<div>
<GoogleLogin
clientId={'******'}
render={renderProps => (
<GoogleLoginButton
className="googleBtn"
alt="googleLogo"
onClick={renderProps.onClick}
align={"center"}
>
</GoogleLoginButton>
)}
buttonText="Login with Google"
onSuccess={googleLogin}
onFailure={googleLogin}
className="googleComponentBtn"
theme="dark"
/>
</div>
</div>
)
}
这是我的尝试,
App.js(这里正在获取令牌)
// JWT TOKEN
if (sessionStorage.jwtToken) {
// Set auth token header auth
setAuthToken(sessionStorage.jwtToken);
// Decode token and get user info and exp
const decoded = jwt_decode(sessionStorage.jwtToken);
// Set user and isAuthenticated
store.dispatch(setCurrentUser(decoded));
// Check for expired token
const currentTime = Date.now() / 1000;
if (decoded.exp < currentTime) {
// Logout user
store.dispatch(logoutUser());
// Redirect to login
window.location.href = "/login";
}
}
class App extends Component {
render(){
return (
<Provider store={store}>
<Navbar/>
</Provider>
);
}
}
export default App;
authActions.js
// how the local login works to get an idea
export const loginUser = userData => dispatch => {
Axios.post('/users/login', userData)
.then( res => {
// retrieve token from the response
const token = res.data.token;
console.log(token);
// pass the token in session
sessionStorage.setItem("jwtToken", token);
// set the auth token
setAuthToken(token);
// decode the auth token
const decoded = jwt_decode(token);
// pass the decoded token
dispatch(setCurrentUser(decoded))
})
.catch(err => {
if(err.response.data){
console.log(err.response)
dispatch({
type: GET_ERRORS,
payload: err.response.data
})
}
})
}
// attempt to login with google, and recieve a token from routes.
export const googleLogin = () => dispatch => {
Axios
.get('/users/auth/google', userData)
.then(res => {
const { token } = res.data;
// Set token to ls
sessionStorage.setItem("jwtToken", token);
// Set token to Auth header
setAuthToken(token);
// Decode token to get user data
const decoded = jwt_decode(token);
// Set current user
dispatch(setCurrentUser(decoded));
})
.catch(err => console.log(err));
};
// set logged in user
export const setCurrentUser = (decoded, dispatch) => {
return{
type:SET_CURRENT_USER,
payload:decoded
}
}
路由/用户尝试传递令牌以做出反应
router.get('/auth/google',
passport.authenticate('google', { scope: 'profile'}), (req, res, next) => {
console.log(profile);
jwt.sign(process.env.JWT_SECRET,{expiresIn: 4800}, (err, token) => {
res.json({
success:true,
token: token
})
});
});
router.get('/auth/google/callback',
passport.authenticate('google', { failureRedirect: '/login' }),
(req, res) => {
res.redirect('/');
});
passport.js
passport.use(
new GoogleStrategy(
{
clientID: process.env.clientID,
clientSecret: process.env.secret,
callbackURL: 'http://localhost:3000/auth/google/callback',
// proxy: true
}, (token, tokenSecret, profile, done) => {
// console.log(profile);
User.forge({ googleId: profile.id}).fetch()
.then( (err, user) => {
if(!user){
const googleUser = new User({
googleId: profile.id,
email:profile.emails[0].value
});
googleUser.save().then( user => done(null, user))
}else{
done(null, user)
console.log(user);
}
})
}
))
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(user, done) {
User
.forge({id: user})
.fetch()
.then((usr) => {
done(null, usr);
})
.catch((err) => {
done(err);
});
});