I want to use OAuth login for discord (https://discord.com/developers/docs/topics/oauth2#oauth2) for my website in previouse version I was using blade instead of Vue so I was using socialite and it was easy but now that I’m suing Vue I have no idea how can I generate and redirect user to discord login page and then get data in callback.
I tried socialite like this:
web.php
Route::get('/auth/discord', function () {
return Socialite::driver('discord')->redirect();
});
Route::get('/auth/discord/callback', function () {
$user = Socialite::driver('discord')->user();
dd($user);
});
Home.vue
<template>
<button @click="loginWithDiscord">Login with Discord</button>
</template>
<script>
import axios from 'axios';
export default {
methods: {
loginWithDiscord() {
axios.get('/auth/discord').then(response => {
window.location.href = response.data.redirect;
});
}
}
}
</script>
But I’m getting this error in console:
Acess to XMLHttpRequest at 'https://discord.com/api/oauth2/authorize?client_id=34234&redirect_uri=http%3A%2F%2Flocalhost%3A8000%2Foauth%2Fcallback&scope=identify+email&response_type=code&state=Sadasdaa21=none' (redirected from 'http://localhost:8000/auth') from origin 'http://localhost:8000' has been blocked by CORS policy: Request header field x-xsrf-token is not allowed by Access-Control-Allow-Headers in preflight response.
2
Answers
I managed to fix the problem by changing the "auth/discord" function to this:
the reason of the problem was without "getTargetUrl()" it was returing html codes instead of actual url
When dealing with OAuth, you need to add an exception to the
VerifyCsrfToken
middleware.This is done because whenever you hit your
auth/discord
endpoint, you will get redirected todiscord.com
and thendiscord.com
will redirect back toauth/discord/callback
without a valid CSRF token.There is no way for an external site like
discord.com
to know a valid CSRF token for your application (that is the whole point), so you add an exception for that one endpoint.The error also seems to indicate discord does not want you to send a
x-xsrf-token
header in the request. Perhaps you have configured axios to globally add this header? If so, you should delete it from this request.Use your browser dev tools (or something like postman) to inspect the request you make to discord.com and make sure it does not have the x-xsrf-token header.