vuejs 2 - vue-auth JWT token not possible to safe - authentication

here is my Vue Object:
Vue.use(require('#websanova/vue-auth'), {
auth: require('#websanova/vue-auth/drivers/auth/bearer.js'),
http: require('#websanova/vue-auth/drivers/http/axios.1.x'),
router: require('#websanova/vue-auth/drivers/router/vue-router.2.x'),
fetchData: {url: 'http://localhost:5000/auth/user', method: 'GET',
enabled: true},
tokenDefaultName: 'access_token',
parseUserData: function (response) {
console.log('found user')
return response.data.user
},
tokenStore: ['localStorage']
})
Here is my login:
this.$auth.login({
data: {
username: this.model.email,
password: this.model.password
},
success: function (response) {
alert(response)
console.log(response)
this.$auth.user = response.data
},
error: function (res) {
console.log(res.data)
console.log(res)
this.$notify({
component: {
template: `<span><strong>Oops, something went wrong... </strong><br>Not possible to login because of an internal server error</span>`
},
icon: 'fa fa-exclamation',
horizontalAlign: 'right', // right | center | left
verticalAlign: 'top', // top | bottom
type: 'danger' // info | success | warning | danger
})
this.model.error_msg = 'Not possible to login'
},
rememberMe: true,
url: 'http://localhost:5000/auth/login',
redirect: '/dashboard',
fetchUser: true
})
The workflow should be
POST to /login the API returns the token (this works)
Store the token (this doesnt work)
Use the Token for the fetch user route (this doesnt work)
If vue posts to the /login route the API returns the following:
{
"access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1MjA5Mzg2MTcsIm5iZiI6MTUyMDkzODYxNywianRpIjoiZTZiNmViNTItMTI4NC00NzA5LWEwYTMtOTk5YTM4YmIyMTcwIiwiZXhwIjoxNTIwOTM5NTE3LCJpZGVudGl0eSI6eyJmaXJzdG5hbWUiOiJHZW9yZyIsImxhc3RuYW1lIjoiU2F0dGxlciIsImVtYWlsIjoiZ2VvcmdAc2F0dGxlci5pbyIsInV1aWQiOiI2ZTU1OGZjM2ExYjg0MTQ0YWQ1ODU1N2JlYWMxMjFkOCJ9LCJmcmVzaCI6dHJ1ZSwidHlwZSI6ImFjY2VzcyJ9.0EhkUXZpG4WTxhnDvQQp8i97GaNXoNyp24P7qLMRUPM",
"message": "successfully logged in - welcome",
"refresh_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1MjA5Mzg2MTcsIm5iZiI6MTUyMDkzODYxNywianRpIjoiNzAxNTAxYWYtODJjMC00YmQ5LTg1YjAtZjQ0ZTNjNzgzYmY1IiwiZXhwIjoxNTIzNTMwNjE3LCJpZGVudGl0eSI6eyJmaXJzdG5hbWUiOiJHZW9yZyIsImxhc3RuYW1lIjoiU2F0dGxlciIsImVtYWlsIjoiZ2VvcmdAc2F0dGxlci5pbyIsInV1aWQiOiI2ZTU1OGZjM2ExYjg0MTQ0YWQ1ODU1N2JlYWMxMjFkOCJ9LCJ0eXBlIjoicmVmcmVzaCJ9.gRH3nJQEaBc2_0iZ9E9fhGg-9i-fil8c5SOvh8Tvsbg",
"request_id": "037dd993-1c19-4c68-8e5a-e060e11d3ce8",
"status": "OK"
}
If i check the local storage in the dev tool it seems to be empty
How can I tell vue-auth to store the access token?
Thanks

You should save the access_token in the success case.
this.$auth.login({
data: {
username: this.model.email,
password: this.model.password
},
success: function (response) {
alert(response)
console.log(response)
this.$auth.token('access_token', response.data.access_token)
}

Related

Calling the auth function will call the wrong url

I'm using the Nuxt/Auth library in a NuxtJs project. I'm trying to make a login request to my backend. So I don't use any of the existing schemes that the library has prepared by default.
This is what my configuration looks like in nuxt.config.js
axios: {
baseUrl: 'https://api.release.my-custom-domain.com',
credentials: true,
proxy: true
},
proxy: {
'/api/': {
target: 'https://api.release.my-custom-domain.com',
pathRewrite: {'^/api/': ''}
}
},
auth: {
strategies: {
local: {
token: {
property: 'token',
global: true,
},
user: {
property: 'user'
},
endpoint: {
login: {url: '/api/v1/auth', method: 'post', propertyName: false}
}
}
}
},
I use a proxy because of a problem with cors.
This is what my code looks like in vue.
methods: {
async loginFormSubmit () {
try {
let response = await this.$auth.loginWith('local', { data: this.login })
console.log(response);
} catch (err) {
console.log(err);
}
}
}
After I call the function, the XRH request runs, but it always adds /login to the url request.
This is what the url should look like - http://localhost:3000/api/auth
But the request looks like this - http://localhost:3000/api/auth/login
Didn't someone already solve this problem?
Thank you for your answers.

Nuxt - pusher : refresh a plugin when i log in

For my nuxt app, i need to use pusher for handling websocket.
I use pusher-js, and i created a nuxt plugin to enable pusher throughtout my app.
The problem is that i need to be auth to use pusher.
That my plugin :
import Pusher from 'pusher-js'
export default ({ $axios, env, $auth }, inject) => {
if (!$auth.loggedIn) {
return
}
const pusher = new Pusher(process.env.PUSHER_APP_KEY, {
cluster: 'eu',
authEndpoint: `${$axios.defaults.baseURL}/broadcasting/auth`,
auth: {
headers: {
Authorization: $auth.strategy.token.get()
}
}
})
inject('pusher', pusher)
}
Here is where i register my plugin in the nuxt-config
auth: {
redirect: {
login: '/auth/login',
logout: '/auth/login',
callback: '/auth/login',
home: '/'
},
strategies: {
laravelJWT: {
provider: 'laravel/jwt',
url: process.env.BASE_BACK_URL + '/platform',
endpoints: {
login: { url: '/auth/login', method: 'post' },
user: { url: '/auth/me' },
logout: { url: '/auth/logout', method: 'post' },
refresh: { url: '/auth/refresh' }
},
user: {
property: 'data'
},
token: {
property: 'access_token',
maxAge: 60 * 60
},
refreshToken: {
maxAge: 20160 * 60
}
}
},
plugins: [
{ src: 'plugins/pusher.js', ssr: false }
]
},
When I'm logged and I refresh the page it's fine. But when I log in via login page, the pusher object is not instantiated (because I was not logged in) and when I want to go to my chat page, the website has not refreshed (cause spa) and I obvioulsy get an error cause I want to access pusher but it does not exist.
So is there a way to refresh the plugin when i login, or to enable it only when i'm logged ?
Thx :)

How to implement Nuxt Server Middleware Google authorization?

I've got the following auth configuration in my nuxt.config.js
auth: {
strategies: {
google: {
client_id: process.env.GOOGLE_KEY,
codeChallengeMethod: '',
scope: ['profile', 'email'],
responseType: 'token id_token'
}
},
redirect: {
login: '/login',
logout: '/logout',
home: '/',
callback: '/welcome'
},
rewriteRedirects: false
},
router: {
middleware: ['auth']
},
serverMiddleware: [
{ path: '/db', handler: '~/api/db.js' },
],
This setups frontend authentication, so all my .vue pages are protected. Besides that, I've got some serverMiddleware, like in my api/db.js
const app = require('express')()
app.get('/fields/:schema', async (req, res) => {
var result = []
// some logics here
return result;
})
Request to this resource is not protected by any auth, but I've noticed in Network tab in browser, that all request made by $axios.$get('db/fields/some_schema') from my .vue pages set some Google cookie, like
auth.strategy=google; auth._token.google=Bearer...
which is not used in my serverMiddleware api/db.js
Does Nuxt.js has some out of box way to setup Google authentication for server middleware? What is the right way to setup it?
I had to use this nuxt config
auth: {
strategies: {
google: {
clientId: 'to be added',
clientId: '<your cliendID here>',
codeChallengeMethod: '',
responseType: 'code',
endpoints: {
token: 'http://localhost:8000/social-login/google/',
userInfo: 'http://localhost:8000/auth/user/'
},
},
}
},
and implement backend token and userInfo endpoints

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?