Using Nuxt-Auth with Cookie - vue.js

I am attempting to get Nuxt.js to work with cookie authentication. I am using nuxt-auth with cookie setting. Laravel Backend with Passport.
The reason I need to use Cookies is because I plan on having the nuxt project be on my main domain name (with login) and then having app.mydomainname.com for the actual application. The main website has public facing pages that use authentication as well.
Here is my config for nuxt.js for nuxt-auth:
auth: {
local: false,
redirect: {
login: "/login",
logout: "/login",
callback: "/login",
home: false,
},
strategies: {
cookie: {
token: {
property: "data.access_token",
},
user: {
property: "data",
},
endpoints: {
login: {
url: "v1/auth/login",
method: "post",
propertyName: "access_token",
},
logout: { url: "/v1/auth/logout", method: "delete" },
user: { url: "/v1/settings", method: "get" },
},
},
},
},
Login works fine, but then the cookie does not set when I look in my editthiscookie chrome plugin, thus the call to /settings does not work:
As you see the cookie is just being set to true and not the access token.
Any help with the configuration would be helpful.
Thanks

Figured it out. I had to set set required: true and type: "Bearer" in the token config.
So it looks like this now:
auth: {
redirect: {
login: "/login",
logout: "/login",
callback: "/login",
home: false,
},
strategies: {
local: false,
cookie: {
token: {
property: "data.access_token",
required: true,
type: "Bearer",
},
user: {
property: "data",
},
endpoints: {
login: {
url: "v1/auth/login",
method: "post",
},
logout: { url: "/v1/auth/logout", method: "delete" },
user: { url: "/v1/settings", method: "get" },
},
},
},
},

Related

#nuxt/auth send me to /login page when I reload the page or access URLs manually

I'm trying to implement a login system in my app (Nuxt 2) using #nuxt/auth. The backend is a Node.js + Express + Passport, using sessions and cookies.
I think it's important to say I'm using http-proxy-middleware in my front end, so my back end can be accessible in the same domain with localhost:3000/api/... or localhost:3000/uploads for uploaded files.
The backend seems to be working as expected, creating the sessions, returning an User object if logged in and 401 if not. I did some research and didn't find much advantages to use JWT so I opted for sessions and cookies instead (but any recommendations are valid). Cookies expiration time is set in the backend as 24 hours.
In my front end I don't have any custom middlewares.
In the front end, I can log in and it redirects me to home ('/'), and I can access protected pages, I have set auth globally but excluded from the login layout with auth: false.
But when I refresh the page or try to access some URL manually (e.g. /timeline) it goes back to the login page. I tried to show $auth.user in the login page and it's showing me the user's information as it was logged in. $auth.loggedIn is true.
One important thing to note is that it takes a while to show the information in $auth.user and $auth.loggedIn shows as false at the first second, maybe something to do with this? I checked the cookies and it seems to be all right, I will post more information below. (this in the login page)
When I tried to access my back end endpoint /api/user I get the user's information so I'm sure in my backend I'm logged in.
Also when I try to log out, at the first moment it logs me out but doesn't redirect to me to the login page. When I try to access some protected page it does redirect me as expected.
But I was expecting to not being redirected to login page when refreshing or accessing URLs manually, how can I fix this please?
This is my nuxt.config.js:
const { createProxyMiddleware } = require('http-proxy-middleware')
export default {
head: {
// ...
},
serverMiddleware: [
createProxyMiddleware('/api', {
target: 'http://localhost:3300/api',
changeOrigin: true,
pathRewrite: {
'^/api': '/'
}
}),
createProxyMiddleware('/uploads', {
target: 'http://localhost:3300',
changeOrigin: true,
pathRewrite: {
'^/uploads': '/uploads'
}
}),
],
router: {
middleware: ['auth']
},
// css: [],
css: [
'~assets/scss/main.scss',
],
// loading bar
loading: {
color: '#ef443b',
},
plugins: [
'~/plugins/vuelidate'
],
components: true,
buildModules: [
'#nuxtjs/eslint-module',
'#nuxtjs/style-resources',
'#nuxtjs/fontawesome',
],
modules: [
'bootstrap-vue/nuxt',
'#nuxtjs/axios',
'#nuxtjs/auth',
'nuxt-precompress',
],
auth: {
cookie: {
options: {
maxAge: 24 * 60 * 60 * 1000, // 24 hrs
secure: process.env.NODE_ENV && process.env.NODE_ENV === 'production', // HTTP if local, HTTPS if production
},
},
strategies: {
local: {
token: {
required: false,
type: false
},
endpoints: {
login: {
url: '/api/login',
method: 'POST',
propertyName: false
},
logout: {
url: '/api/logout',
method: 'GET'
},
user: {
url: '/api/user',
method: 'GET',
propertyName: false
},
},
tokenRequired: false,
// tokenType: 'Bearer',
},
},
},
bootstrapVue: {
bootstrapCSS: false, // Or `css: false`
bootstrapVueCSS: false // Or `bvCSS: false`
},
fontawesome: {
component: 'fa',
suffix: false,
icons: {
regular: true,
solid: true,
brands: true,
},
},
styleResources: {
scss: [
'./assets/scss/_variables.scss',
'./assets/scss/_mixins.scss',
],
hoistUseStatements: true,
},
axios: {
baseURL: '/',
withCredentials: true,
credentials: true,
},
env: {
apiUrl: process.env.API_URL,
},
publicRuntimeConfig: {
axios: {
browserBaseURL: process.env.BROWSER_BASE_URL
}
},
privateRuntimeConfig: {
axios: {
baseURL: process.env.BASE_URL
}
},
build: {
transpile: [
'audiomotion-analyzer'
]
},
}
My logout code is as simple as this:
methods: {
logout(e) {
this.$auth.logout()
},
},
These are the cookies when:
I log out and try to log in for the first time (maybe this cookie is from past sessions):
enter image description here
When I'm logged in and redirected to home:
enter image description here
When I access another protected page using a link:
enter image description here
When I try to access an URL manually and gets redirected to /login:
enter image description here
If necessary I can share some code from my backend too, but I think the problem is in my front-end...
EDIT
I just realized I was using this.$router.push('/') after logging in and had no config whatsoever for redirections, so I updated my nuxt.config.js and now it is redirecting without $router.push, and also when I log out. The refresh / manually access problem persists tho.
auth: {
cookie: {
options: {
maxAge: 24 * 60 * 60 * 1000, // 24 hrs
secure: process.env.NODE_ENV && process.env.NODE_ENV === 'production', // HTTP if local, HTTPS if production
},
},
strategies: {
local: {
token: {
required: false,
type: false
},
endpoints: {
login: {
url: '/api/login',
method: 'POST',
propertyName: false
},
logout: {
url: '/api/logout',
method: 'GET'
},
user: {
url: '/api/user',
method: 'GET',
propertyName: 'user'
},
},
tokenRequired: false,
// tokenType: 'Bearer',
},
},
redirect: {
login: '/login',
logout: '/login',
home: '/',
},
},

How can I log in as a user with nuxt.auth?

I currently have the following nuxt.auth configuration.
auth: {
strategies: {
cookie: {
endpoints: {
login: { url: '/api/login', method: 'post' },
},
},
},
},
When login is ok, the response is in json format with the following data
{'user': 'Tlaloc-Es'}
On the login page I have the following code:
this.$auth
.loginWith('cookie', {
data: {
email: this.user_email,
password: this.user_password,
remember: this.remember,
},
})
.then((data) => {
const response = data.data.data;
this.$auth.setUser(response.user);
console.log(response.user);
console.log(this.$auth.loggedIn);
});
The problem is this.$auth.loggedIn always returns false.
I guess that auth doesn't set the user as logged, but I don't know any other steps I need part of:
this.$auth.setUser(response.user);
After a call, logging in browser stores the following cookies:
auth._token.cookie -> true
session -> session token
auth.strategy -> 'cookie'
auth._token_expiration.cookie -> false
How can I set the user as logged?
EDIT
If I execute the logout this value
auth._token.cookie
turn to false, but the session still is stored and anyway
this.$auth.loggedIn
return false.
EDIT
Another try:
auth: {
redirect: {
login: '/login',
logout: '/login',
home: '/',
},
strategies: {
cookie: {
cookie: {
name: 'session',
},
user: {
property: false,
autoFetch: false,
},
endpoints: {
login: { url: '/api/login', method: 'post' },
logout: { url: '/api/logout', method: 'post' },
},
},
},
},
async signIn() {
const succesfulLogin = await this.$auth.loginWith('cookie', {
data: {
email: this.user_email,
password: this.user_password,
remember: this.remember,
},
});
if (succesfulLogin) {
const response = succesfulLogin.data.data;
await this.$auth.setUser({ user: response.user });
console.log(this.$auth.loggedIn);
//await this.$auth.logout();
}
},
This is after login:
reponse cookie
Thanks.
you should try setting set this.$auth.loggedIn = true to true after receiving the data
this.$auth
.loginWith('cookie', {
data: {
email: this.user_email,
password: this.user_password,
remember: this.remember,
},
})
.then((data) => {
const response = data.data.data;
this.$auth.setUser(response.user);
this.$auth.loggedIn = true
console.log(response.user);
console.log(this.$auth.loggedIn);
});
Finally works with the following configuration:
auth: {
redirect: {
login: '/login',
logout: '/login',
home: '/',
},
strategies: {
cookie: {
options: {
httpOnly: true,
path: '/',
},
user: {
property: false,
autoFetch: false,
},
endpoints: {
login: { url: '/api/login', method: 'post' },
logout: { url: '/api/logout', method: 'post' },
},
},
},
},

Nuxt auth without the user endpoint

I'm using Nuxt auth, but I don't have an endpoint for the user, in nuxt.config is set the endpoint to be false and after loginWith I'm jest setting the user manually.
The issue is that after refresh I'm logged in but I don't have any user info (name, email...) what I'm I missing here?
nuxt.config file:
auth: {
strategies: {
local: {
endpoints: {
login: {
url: '/api/users/login/',
method: 'post',
propertyName: 'token',
},
logout: { url: '/api/users/logout/', method: 'post' },
user: { url: '/api/users/auth/', method: 'post' },
// user: false,
},
autoFetchUser: false,
tokenName: 'Authorization',
tokenType: 'Token',
// tokenRequired: true,
// globalToken: true,
},
},
},
login form file
const { data } = await this.$auth.loginWith('local', {
data: { username: this.email, password: this.password },
});
this.$auth.setUser(data);
When you logged in, user info will return from login data, when you refresh there is no endpoint for user, then auth plugin cant retrieve your user info, so you must do it manually and setUser yourself

How can I solve problem logout on safari browser? (auth nuxt)

When I log out in Chrome and Firefox browser it works fine. But when I logged out on safari, it didn't go well. When I click logout, it goes to the login page then returns to the home page. After I click logout one more time. It made it to the login page. So I have to click logout twice on safari browser
My code like this :
async logout () {
await this.$auth.logout()
this.SET_IS_AUTH(false)
// this.$router.push('/')
window.location.href = '/'
}
My auth in nuxt.config.js like this :
auth: {
redirect: {
login: '/',
home: '/home',
logout: '/'
},
strategies: {
local: {
scheme: 'refresh',
token: {
property: 'response.token',
// maxAge: 3600,
// type: 'Bearer'
},
refreshToken: {
property: 'response.token',
// data: 'refresh_token',
// maxAge: 60 * 60
},
endpoints: {
login: {
url: '/auth/token',
method: 'post',
propertyName: 'response.token'
},
user: false,
logout: false
},
tokenRequired: true,
tokenType: 'Bearer '
}
},
token: {
name: 'token'
},
cookie: {
name: 'token'
}
},
How can I solve this problem?

Nuxtjs Google Auth

After calling $auth.loginWith('google'), I am getting
http://localhost:3000/ru/user-registration#state=D7xooLsNNxNGfbvcQMU5g&access_token=ya29.a0Ae4lvC2z0XERgeRUipmu7c205WWCCSVgRZ-s_mYWg6ZoMgCGzVZ-U69arfpn-ybm5kthqtvqQrD7lGYmNDqiLtkW1aIecP6Wp-bwINMok3ztNcW5KwmlohLmtnbk4IZVkciKfb8T_JUtf89xpJcjpt2dSx_09FPGSKc&token_type=Bearer&expires_in=3599&scope=email%20profile%20openid%20https://www.googleapis.com/auth/userinfo.email%20https://www.googleapis.com/auth/userinfo.profile&authuser=0&prompt=consent as a callback. What should I do next in order to get the info of the registered gmail. Any help or ideas are welcome
auth part in my nuxt.config.js
auth: {
strategies: {
local: {
endpoints: {
login: { url: "token/", method: "post", propertyName: "access" },
user: { url: "user/me/", method: "get", propertyName: false },
logout: false,
}
},
google: {
client_id: 'my_client_id',
redirect_uri: 'http://localhost:3000',
}
},
},
In your nuxt.config.js file you declare two differents strategies: local and google. If you would like to use Google as an identity provider you don't need to precise the endpoints.
Here is my actual config for one of my project:
auth: {
redirect: {
login: '/login',
logout: '/login',
home: '/',
callback: '/callback'
},
strategies: {
google: {
client_id: 'XXXXXxxxx.apps.googleusercontent.com'
}
}
}
And I have specified on Google API Console the following authorized URI: localhost:3000/callback for my dev environment and mydomain.com/callback for the prod.