Calling the auth function will call the wrong url - vue.js

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.

Related

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 :)

Nuxt.js auth user is set but loggedIn is still false

js app with Nuxt Auth and when I want to log in. User is not set and loggedIn is false
const response = await this.$auth.loginWith('local', { data: {
email: this.form.email.value,
password: this.form.password.value,
} });
this.$auth.setUser(response.data.user);
this.$auth.strategy.token.set(response.data.jwt.access_token)
this.$auth.strategy.refreshToken.set(response.data.jwt.refresh_token)
so I wrote this and after that user is set but loggedIn is still false. Here my nuxt.config.js.
auth: {
strategies: {
local: {
scheme: 'refresh',
token: {
property: 'access_token',
maxAge: 1800,
required: true,
type: 'Bearer',
},
refreshToken: {
property: 'refresh_token',
data: 'refresh_token',
maxAge: 60 * 60 * 24 * 30,
},
user: {
property: 'user',
autoFetch: true,
},
endpoints: {
login: { url: '/login', method: 'post' },
refresh: { url: '/refresh', method: 'post', propertyName: false },
logout: { url: '/logout', method: 'post' },
user: { url: '/refresh', method: 'post', propertyName: false },
},
},
},
},
Can you help me with it please?
I found solution to my answer. I wrote my own scheme
import { RefreshScheme } from '~auth/runtime'
export default class CustomScheme extends RefreshScheme {
// Override `fetchUser` method of `local` scheme
async fetchUser (endpoint) {
this.options.endpoints.user = {
...this.options.endpoints.user,
data: {
token: this.$auth.strategy.refreshToken.get()
}
}
// Token is required but not available
if (!this.check().valid) {
return
}
// User endpoint is disabled.
if (!this.options.endpoints.user) {
this.$auth.setUser({})
return
}
// Try to fetch user and then set
return this.$auth.requestWith(
this.name,
endpoint,
this.options.endpoints.user
).then((response) => {
const user = response.data.user
// Transform the user object
const customUser = {
...user,
fullName: user.name,
roles: ['user']
}
// Set the custom user
// The `customUser` object will be accessible through `this.$auth.user`
// Like `this.$auth.user.fullName` or `this.$auth.user.roles`
this.$auth.setUser(customUser)
return response
}).catch((error) => {
this.$auth.callOnError(error, { method: 'fetchUser' })
})
}
}
Apparently was the problem by getting user from propertyName. I replace code with my own response const user = response.data.user and now it seems working :)

How to retrieve token property in Nuxt Auth

I am developing my first NuxtJs application with the following technologies.
For Backend APIs Laravel 7.3 (Passport)
Nuxt v2.15.2
Rendering mode: Universal (SSR / SSG)
NuxtAxios v5.13.1
NuxtAuth v5
My login API response is as follows:
{
"status": true,
"code": 200,
"data": [
{
"id": 3,
"nick_name": "johndoe",
"full_name": "John Doe",
"email": "johndoe#mail.com",
"access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiIxIiwianRpIjoiNWE5MjFmMGMyMDBlZjkxYWQxY2QyNGI3NDEyYmI1OWY4ZGEyZjg2Yzc0Y2M1ZDAwOTRhOWIyZTU4MGY3MmZmODRmNGI5N2QwYjJmYjA5NjMiLCJpYXQiOjE2MTQwMzE1MDMsIm5iZiI6MTYxNDAzMTUwMywiZXhwIjoxNjQ1NTY3NTAzLCJzdWIiOiIzIiwic2NvcGVzIjpbXX0.clQslt3CdTLoVDHzQFwQyrRLjzjTOSeipCyQAl07gzmwXFKr542hR3MUCRr8CTjueWDTNbwd-iKkQztvB7Z-0N1zaptq67UEwj3iPEEtnbV2gMOSlVdAUu0q4OPJKYI9RwJKHnK-q1bTCOUOitfLrnYOq3Lb1T8B-3en5_S7xb9ln-iOtwVc3vW1OnEbEIsn3ELeTro1zQ9IKdlHhQ50CnGU45LipzKeadtVGkm9qm467XOqlVPZdulMJTCkvunETo23hQsTsn_Fxy0IYLUA0v-_C-ARB0N672fAuHF2a8MIYHv066Omm-6WsPrCNtfOkoIgyuMLl0gaua04IJfHrDbh7CJSEUqootKTsIVvFG4OjqR3yDN2PdhjJkPYWNTMeLbKV3ewSsjCS1aMOtXYvhrVFjrunn5M74pDBzn3kW9VMFIh2BbIfUDO_ziDrsn7KAVyOm-p7gdBN_gVKcl_Hx9x4EagixWRL7GGUqEZ2AbxRkpIO4HKwqMm7WxKatSt5hkmPZ6Zt-jfMTfrj7KuF6WhhjCh1TOFJSy9BTqp9_a2eKP-YL2M6JIJXFDHwovToC96JBptbumPvB2i2KDU_XoXF2WFx_I4iNJpZVFN0u12MeyMbXlnpf4X2t79_I7QklxSfZ5LgsOdsnt9dAm9QBbSvf8AdZZNOS4p59DuQls",
}
],
"error": null,
"errors": null
}
nuxt.config.js
auth: {
strategies: {
local: {
token: {
// property: 'access_token'
// property: 'data[0].access_token'
// property: 'data.data[0].access_token'
property: false
},
user: {
property: 'data',
autoFetch: true
},
endpoints: {
login: { url: '/en/signin', method: 'post' },
logout: { url: '/user/logout', method: 'get' },
user: { url: '/en/user/profile', method: 'get' },
}
}
}
},
Login.vue
export default {
data() {
return {
login: {
email: 'johndoe#mail.com',
password: 'welcome'
}
}
},
methods: {
async userLogin() {
try {
let response = await this.$auth.loginWith('local', { data: this.login })
console.log(response)
} catch (err) {
console.log(err)
}
}
}
}
When I am setting local.property: false, auth._token.local is being set as complete json object instead of "access_token" and then the second hit goes to '/en/user/profile' with Unauthenticated Request result.
I think an alternate way would be to set local.token.required:false , and then set the user token after your login attempt was successful. Something like this:
nuxt.config.js
auth: {
strategies: {
local: {
token: {
required: false
},
user: {
property: 'data',
autoFetch: true
},
endpoints: {
login: { url: '/en/signin', method: 'post' },
logout: { url: '/user/logout', method: 'get' },
user: { url: '/en/user/profile', method: 'get' },
}
}
}
},
Login.vue
methods: {
async userLogin() {
try {
let response = await this.$auth.loginWith('local', { data: this.login })
.then((response)=>{
this.$auth.setUserToken(response.data[0].access_token,'refreshToken');
});
console.log(response);
} catch (err) {
console.log(err)
}
}
}

NuxtJS Auth Proxy

Then using nuxtjs/auth and nuxtjs/axios nuxt is ignoring my proxy configuration.
In past I have used just axios for auth.
Now I am trying to use the #nuxtjs/auth module. Because I use a seperate backend and CORS I need to use axios proxy for auth.
But the auth stragegy local doesnt use the proxy and I dont get why. It always tries to use the nuxt URL. Seems like auth is absolutely ignoring my proxy. Can anyone help?
// nuxt.config
// ...
axios: {
proxy: true
},
proxy: {
'/api/': {
target: 'http://localhost:4000',
pathRewrite: { '^/api/': '' }
}
},
/*
** Auth Module Configuration
** See https://auth.nuxtjs.org/schemes/local.html
*/
auth: {
strategies: {
local: {
endpoints: {
login: { url: '/api/auth/login', method: 'post', propertyName: 'token' },
logout: { url: '/api/auth/logout', method: 'post' },
user: { url: '/api/auth/user', method: 'get', propertyName: 'user' }
}
}
}
},
// ..
// Component
async userLogin() {
try {
let response = await this.$auth.loginWith('local', { data: this.login })
console.log(response)
} catch (err) {
console.log(err)
}
}
My Nuxt is running on http://localhost:3000
My client always tries to connect to http://localhost:3000/api/auth/login
But I need http://localhost:4000/auth/login
I use all modules up to date
I have same problem. But I use #nuxtjs/auth-next because nuxtjs/auth is outdated and use #nuxtjs/proxy to replace nuxtjs/axios proxy.
Here is my pacakge dependencies.
// pacakge.json
"dependencies": {
"#nuxtjs/auth-next": "^5.0.0-1648802546.c9880dc",
"#nuxtjs/axios": "^5.13.6",
"#nuxtjs/proxy": "^2.1.0",
"nuxt": "^2.15.8",
// ...
}
Fixed nuxt.config.
// nuxt.config.ts
import type { NuxtConfig } from '#nuxt/types';
const config: NuxtConfig = {
ssr: false,
// ...ignore
modules: [
'#nuxtjs/axios',
'#nuxtjs/proxy',
'#nuxtjs/auth-next',
],
auth: {
strategies: {
local: {
name: 'local',
endpoints: {
login: { url: '/api/auth/login', method: 'post', propertyName: 'token' },
logout: { url: '/api/auth/logout', method: 'post' },
user: { url: '/api/auth/user', method: 'get', propertyName: 'user' }
}
// ...ignore
},
},
},
proxy: {
'/api': {
target: 'http://localhost:4000/',
secure: false,
// CORS problem need to set true,
changeOrigin: true,
pathRewrite: {
'^/api' : '/'
}
},
}
};
export default config;
If you set correct, when you run npm run dev the console should show below info.
[HPM] Proxy created: /api -> http://localhost:4000/
[HPM] Proxy rewrite rule created: "^/api" ~> "/"
[HPM] server close signal received: closing proxy server
The proxy object should be outside of the axios object, ie
axios: {
proxy: true,
// Your other configurations
}
proxy: {
'/api/': {
target: 'http://localhost:4000',
pathRewrite: { '^/api/': '' }
}
}

Nuxt JS Login route is still accessible after successful login

I am trying to resolve this issue past few weeks. I followed couple of series. One on youtube, and one on codecourse. Both of them showed the right way to authenticate user, but once the user is logged in. Login route is still accessible. I will try to give as much information i can.
This is my nuxt.config.js
auth: {
plugins: ["~plugins/auth.js"],
strategies: {
local: {
endpoints: {
login: {
url: "auth/login",
method: "post",
propertyName: "meta.token"
},
user: {
url: "auth/me",
method: "get",
propertyName: "data"
},
logout: {
url: "auth/logout",
method: "post"
},
redirect: {
login: "/auth/login",
logout: "/",
home: "/",
callback: "/"
},
watchLoggedIn: true,
rewriteRedirects: true
}
}
}
},
Here is my login.vue
export default {
middleware: ["guest"],
auth: "guest",
name: "login",
data() {
return {
form: {
email: "",
password: ""
}
};
},
methods: {
async login() {
await this.$auth.loginWith("local", {
data: this.form
});
this.$router.push({
path: this.$route.query.redirect || "/dashboard"
});
}
}
};
It's still accessible after login.
Your configured it wrong. Its all described in the docs. For example middleware
There is no such thing as
middleware: ["guest"],
as in your code. Middleware called auth as you can see in docs. So you need to set it either
Setting per route:
export default {
middleware: 'auth'
}
Globally setting in nuxt.config.js:
router: {
middleware: ['auth']
}