How to use refresh_token in #nuxtjs/auth-next? - jwt

I'm sorry if there are any mistakes because my native language is not English.
I'm using this module with the configuration below, but when I run auth/rerfresh it's requesting using the access_token.
I get the Authorization header on the server side, and when I decode the JWT, the content is access_token.
I am assuming that with this module, when the access_token expires, it will set the refresh_token in the Authorization header and run api/auth/refresh.
Please let me know if there are any mistakes...
auth: {
redirect: {
login: '/login',
logout: '/login',
callback: '/login',
home: '/'
},
strategies: {
local: {
scheme: 'refresh',
autoLogout: true,
token: {
property: 'access_token',
maxAge: 1800,
global: true,
// type: 'Bearer'
},
refreshToken: {
property: 'refresh_token',
data: 'refresh_token',
maxAge: 60 * 60 * 24 * 30
},
user: {
property: false,
autoFetch: true
},
endpoints: {
login: {
url: '/auth/login',
method: 'post',
propertyName: 'access_token',
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"grant_type": "password"
},
},
refresh: { url: '/auth/refresh', method: 'get' },
logout: { url: '/auth/logout', method: 'post', },
user: { url: '/auth/me', method: 'get', propertyName: false }
}
},
[/auth/login response]
{
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzX3Rva2VuIiwiZXhwIjoxNjc0NTI1OTA3LCJzdGFmZl9pZCI6ImFiY2RlMTIzIn0.68BPtgr93lwHgSfSQxieEJUJtGPe9bafQMpnbdHEqy0",
"refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaF90b2tlbiIsImV4cCI6MTY3NzExNzg0Nywic3RhZmZfaWQiOiJhYmNkZTEyMyJ9.71B1iofZIsoaduUOH7ahuTi2gc2NCp5fpsRrsZaGPMg",
"token_type": "bearer"
}
[Cookies]
Name
Value
Expires/Max-Age
Priority
auth._token_expiration.local
1674525907000
Session
Medium
auth._refresh_token.local
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaF90b2tlbiIsImV4cCI6MTY3NzExNzg0Nywic3RhZmZfaWQiOiJhYmNkZTEyMyJ9.71B1iofZIsoaduUOH7ahuTi2gc2NCp5fpsRrsZaGPMg
Session
Medium
auth._token.local
Bearer%20eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzX3Rva2VuIiwiZXhwIjoxNjc0NTI1OTA3LCJzdGFmZl9pZCI6ImFiY2RlMTIzIn0.68BPtgr93lwHgSfSQxieEJUJtGPe9bafQMpnbdHEqy0
Session
Medium
auth._refresh_token_expiration.local
1677117847000
Session
Medium
auth.strategy
local
Session
Medium
I have tried various auth settings in nuxt.config.js but could not solve the problem.
(For example, autoLogout: false, etc.)
I tried running this.$auth.refreshTokens() but , Authorization header seems to be set to access_token.
As you can see in the image above, the token was received and seems to be stored in the cookie.

refresh: { url: '/auth/refresh', method: 'post' },
Changed as above.
I expected refresh_token to be included in the Authorization header, but it seems to be included in the request body.
Changed to refer to the request body in server-side processing.

Related

how to use axios request to exchange google authorization code for access and refresh tokens

I am working on a expo react native app, I tried to implement the google login function.
I am following this expo-auth-session docs https://docs.expo.dev/guides/authentication/#google,
I've successfully gotten the authorization code using the code below:
const [request, response, promptAsync] = Google.useAuthRequest({
expoClientId: google_client_id,
scopes: [
"https://www.googleapis.com/auth/drive",
],
responseType: "code",
shouldAutoExchangeCode: false,
redirectUri: REDIRECT_URI,
extraParams: {
access_type: "offline"
},
})
useEffect(() => {
if (response?.type === 'success'){
console.log(response.params.code)
}
},
[response]);
response.params.code
is the authorization code that returns to me.
I am now trying to use this authorization code to send a post request to the google token endpoint to exchange for a token. I am following this document here: https://developers.google.com/identity/protocols/oauth2/native-app
I tried the following 2 methods, but both of them gives me an axios error code of 400. I am not sure what's wrong with my code. Can someone please help me with it please, thanks!
axios.request({
method: 'POST',
url: 'https://oauth2.googleapis.com/token',
headers: {
'content-type': 'application/x-www-form-urlencoded',
//Authorization: `Basic ${new Buffer.from(`${google_client_id}:${google_client_secret}`).toString('base64')}`,
},
data: {
grant_type: 'authorization_code',
code: response.params.code,
redirect_uri: REDIRECT_URI,
client_id: google_client_id,
client_secret: google_client_secret
}
}).then((res) => {
console.log(res.data)
}).catch(err => {console.log(err)})
and
axios.request({
method: 'POST',
url: 'https://oauth2.googleapis.com/token',
headers: {
'content-type': 'application/x-www-form-urlencoded',
Authorization: `Basic ${new Buffer.from(`${google_client_id}:${google_client_secret}`).toString('base64')}`,
},
data: {
grant_type: 'authorization_code',
code: response.params.code,
redirect_uri: REDIRECT_URI,
}
}).then((res) => {
console.log(res.data)
}).catch(err => {console.log(err)})

How to implement Facebook OIDC login on Next.js with NextAuth?

I have implemented a regular (Auth2) Facebook login with NextAuth that works fine, but now, I have to switch to OIDC login and can't seem to implement it properly. I'm getting the following error message:
[token_endpoint must be configured on the issuer](https://next-auth.js.org/errors#callback_oauth_error token_endpoint must be configured on the issuer TypeError: token_endpoint must be configured on the issuer)
And this is my configuration on the Facebook Provider:
export default NextAuth({
providers: [
FacebookProvider({
idToken: true,
clientId: process.env.FBID,
clientSecret: process.env.FBSECRET,
wellKnown: "https://www.facebook.com/.well-known/openid-configuration",
token: {
url: "https://www.facebook.com/v11.0/dialog/oauth",
params: { scope: "openid email public_profile" },
},
}),
],
secret: "sunSAd2RkCajg2DLR3+5MfsinFwws8ZuzfPm2C+FXkc=",
});
Try this code
providers: [
FacebookProvider({
idToken: true,
clientId: process.env.FACEBOOK_CLIENT_ID,
clientSecret: process.env.FACEBOOK_CLIENT_SECRET,
authorization: {
url: "https://www.facebook.com/v11.0/dialog/oauth",
params: {
client_id: process.env.FACEBOOK_CLIENT_ID,
scope: "openid email",
response_type: "code",
},
},
// wellKnown: "https://www.facebook.com/.well-known/openid-configuration/",
token: {
url: "https://graph.facebook.com/oauth/access_token",
async request(context) {
try {
// request to https://graph.facebook.com/oauth/access_token?code=""&client_id=""&redirect_uri=""&client_secret=""
const response = await axios.get(this.url, {
params: {
code: context.params.code,
client_id: context.provider.clientId,
redirect_uri: context.provider.callbackUrl,
client_secret: context.provider.clientSecret,
},
});
const tokens = response.data;
return { tokens };
} catch (error) {
throw error;
}
},
},
}),
]

Nuxt Auth uses access token instead of refresh token

My issue is as follows:
After logging in my acces token and refresh token are stored and I can access them with this.$auth.strategy.token.get()
When my access token is expired, my app calls the /token/refresh endpoint that I created in my backend. However, instead of sending the refresh_token, nuxt auth uses the expired access token. How do I tell Nuxt auth to use the refresh token by default?
My nuxt.config.js:
auth: {
localStorage: false,
redirect: {
login: "/login/",
logout: "/",
home: "/search/",
},
watchLoggedIn: true,
strategies: {
local: {
scheme: 'refresh',
token: {
property: 'access_token',
global: true
},
refreshToken: {
property: 'refresh_token',
data: 'refresh_token',
tokenRequired: true,
maxAge: 60 * 60 * 24 * 30,
grantType: 'refresh_token'
},
user:{
property: false,
// autoFetch: false
},
endpoints: {
login: { url: '/login', method: 'post' },
refresh: { url: '/token/refresh', method: 'get', grant_type:'refresh_token'},
logout: false,
user: { url: '/currentuser', method: 'get', propertyName: false }
},
tokenRequired: true,
tokenType: 'Bearer',
}
}
}

Nuxt proxy target not taken into account

When calling an api like below with Axios in Nuxt:
async test() {
await this.$axios
.post(
'https://webservice.foo.com/api-entreprise/enroler/?id=1234',
{ cle_authentification: '1qaz#WSX' }
// {
// headers: { 'Access-Control-Allow-Origin': '*' },
// withCredentials: false,
// }
)
.then((res) => {
console.log(res)
})
.catch((error) => {
console.log(error)
})
},
I'm getting the CORS error below in my browser:
Access to XMLHttpRequest at 'https://webservice.foo.com/api-entreprise/enroler/?id=1234' from origin 'http://mywebsite.test:3001' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
So, I retried with proxy settings:
nuxt.config.js:
axios: {
proxy: true,
},
proxy: {
'/api123/': {
target:
'https://webservice.foo.com/api-entreprise/enroler/?id=1234',
pathRewrite: { '^/api123/': '' },
changeOrigin: true,
},
},
and the call below:
async test() {
await this.$axios
.post(
'/api123/',
{ cle_authentification: '1qaz#WSX' }
// {
// headers: { 'Access-Control-Allow-Origin': '*' },
// withCredentials: false,
// }
)
.then((res) => {
console.log(res)
})
.catch((error) => {
console.log(error)
})
},
But the proxy target doesn't seem to be used, and I get an error 400 showing http://mywebsite.test:3001/api123/ instead.
Request URL: http://mywebsite.test:3001/api123/
Request Method: POST
Status Code: 400 Bad Request
Remote Address: 127.0.0.1:3001
Referrer Policy: strict-origin-when-cross-origin
What's wrong in my proxy configuration ?
ref. https://axios.nuxtjs.org/options/#proxy

make request in axios with credentials and data

I need to make this request but in axios
$.ajax({
type: "POST",
url: url,
data: {'HTTP_CONTENT_LANGUAGE': 'en'},
xhrFields: {
withCredentials: true
},
I tried
params = {
data: {
'HTTP_CONTENT_LANGUAGE': 'en',
},
withCredentials: true
};
axios.post(url, params)
But didn't work what do I do?