I want to use JWT authentication in my nuxtjs app but it's not refreshing the token. For testing purposes, I set the access token expire time 5 seconds and refresh token for 30 minutes.
Access token expire after 5 seconds but the token is not refreshing after 5 second its logged-out
I'm using the Django rest framework and in nuxt I'm using nuxt auth v5
settings.py
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
),
}
SIMPLE_JWT = {
'AUTH_HEADER_TYPES': ('JWT',),
'ACCESS_TOKEN_LIFETIME': timedelta(seconds=5),
'REFRESH_TOKEN_LIFETIME': timedelta(minutes=30),
}
nuxt.config.js
auth: {
localStorage: false,
strategies: {
local: {
scheme: 'refresh',
token: {
property: 'access',
type: 'JWT',
required: true
},
refreshToken: {
property: 'refresh',
},
user: {
property: false,
autoFetch: true
},
endpoints: {
login: { url: '/jwt/create/', method: 'post',},
refresh: { url: '/jwt/refresh/', method: 'post',},
user: {url: '/users/me/', method: 'get' },
logout: false
},
}
}
}
}
I'm little new in JWT and nuxt. Correct me if I'm wrong.
My main goal is just to refresh the token automatically when access toke is expired.
Related
I was implementing a role based authentication using next-auth v4 using CognitoProvider which I modified to add a role but the role attribute is not passed in the final session json
import NextAuth from "next-auth/next";
function CognitoProvider(options) {
return {
id: "cognito",
name: "Cognito",
type: "oauth",
wellKnown: `${options.issuer}/.well-known/openid-configuration`,
idToken: true,
profile(profile) {
console.log(profile);
return {
id: profile.sub,
name: profile.name,
email: profile.email,
image: profile.picture,
role: profile["cognito:groups"],
};
},
options,
};
}
export default NextAuth({
providers: [
CognitoProvider({
clientId: process.env.COGNITO_CLIENT_ID,
clientSecret: process.env.COGNITO_CLIENT_SECRET,
issuer: process.env.COGNITO_DOAMIN,
}),
],
callbacks: {
session: (props) => {
console.log(props);
return props.session;
},
},
});
Below is the console log of profile object
role: profile["cognito:groups"]
Actual Object
I have added a user to admin group and wanted him to access a specific route in my NextJS app.
Any help would be appreciated.
You need to configure the jwt and session callbacks to include more data in the session.
From Next-Auth docs:
If you want to make something available you added to the token [...] via the jwt() callback, you have to explicitly forward it here [the session() callback] to make it available to the client.
To add the user's role:
export default NextAuth({
// ...
callbacks: {
jwt({ token, account, profile }) {
if (account) {
// modify token
token.role = profile.role;
}
return token;
},
session({ session, token }) {
// Send properties to the client
if (session.user) {
// modify session
session.user.roles = token.role;
}
return session;
},
},
});
Then in your route, you would get the user's role from the session session.user.role
I am trying to establish a pre-request script in postman but I get error "Full authentication is required" because when I send the authorization in the header it is not being taken into account (As I see in the console).
This is strange because when I use that same header in a separate request it works fine and generates the desired token.
This is my pre-request code:
var username = pm.environment.get("username");
var password = pm.environment.get("password");
const echoPostRequest = {
url: myURL(I deleted due the security reasons),
method: 'POST',
timeout: 0,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Basic xxxxxxxxxxxxx"
},
body: {
mode: 'urlencoded',
urlencoded: [
{key: "grant_type", value: "password", disabled: false},
{key: "username", value: username, disabled: false},
{key: "password", value: password, disabled: false}
]
}
}
pm.sendRequest(echoPostRequest, function (err, response) {
console.log(response.json())
//console.log('Saving the token ')
//var responseJson = response.json();
// pm.environment.set('access_token', responseJson.access_token)
});
thank you very much for helping me with this!
lately i'm trying to implement a login api for a website.
I'm using Nuxt for the FE, Django REST Framework for the BE and Nuxt Auth Module for the JWT.
Now I tryed to use the normal option for implement my api:
https://auth.nuxtjs.org/schemes/local.html#options
auth: {
localStorage: false,
redirect: {
logout: '/login'
},
cookie: { options: { expires: 7} },//7 minuti
strategies: {
local: {
endpoints: {
login: { url: 'http://127.0.0.1:7777/api/users/login/', method: 'post', propertyName: false},
user: { url: 'http://127.0.0.1:7777/api/users/infoUser/', method: 'get', propertyName: false},
logout: { url: 'http://127.0.0.1:7777/api/users/logout/', method: 'post'},
},
tokenRequired: false,
tokenType: false
}
}
},
but in Django I don't see the token on vscode debug mode.
I need the token for retrieve the user infos.
Can someone help me?
Thank you.
I got it working with the standard Django Restframework endpoint: link
This returns the token which will be set automatically by NuxtJS. In <app>/urls.py I have:
urlpatterns = [
path('login', views.obtain_auth_token, name='login'),
path('user', Views.CurrentUser.as_view()),
path('logout', Views.Logout.as_view()),
]
With the user and logout endpoint being endpoints I created myself.
If this doesn't work can you spicify your way of working on the BE?
I have an app with react and Django rest framework. I use Django allauth for login and registration. when I want to log in, everything is ok, and the response is 201 but the data is empty and I don't get token. I send this request with the postman and I get the token. what should i do?
React Request:
axios({
method: 'post',
url: 'http://localhost:8000/rest-auth/login/',
data: {
username: 'admin',
email: '',
password: 'admin123456'
},
headers: { 'content-type': 'application/json' }
})
.then(response => {
console.log(response.data.key);
})
.catch(error => {
console.log(error);
});
the response is:
{data: "", status: 200, statusText: "OK", headers: {…}, config: {…}, …}
postman request: http://localhost:8000/rest-auth/login/
{
"username": "mahtab",
"email": "",
"password": "mahtab23"
}
postman response:
{
"key": "f75b9f54848a94ac04f455321118aff5d5a7e6f8"
}
The below code works fine for the single endpoint, how to set it for multi endpoints. Please help me.
My requirement is to upload the same file into multiple AWS Buckets.
var uploader = new qq.s3.FineUploader({
//debug: true,
element: document.getElementById('fine-uploader-s3'),
template: 'qq-template-s3',
request: {
endpoint: 'https://s3.amazonaws.com/amazon-bucket',
accessKey: '123456789'
},
signature: {
endpoint: 's3Upload.php'
},
uploadSuccess: {
endpoint: 's3Upload.php?success'
},
iframeSupport: {
localBlankPagePath: '/success.html'
},
retry: {
enableAuto: false // defaults to false
},
cors: {
//all requests are expected to be cross-domain requests
expected: true,
//if you want cookies to be sent along with the request
sendCredentials: true
}
});