Nuxtjs and Scatum duplicate requests and no cookie stored - laravel

I am facing a weird problem. I have a Laravel API server setup and a Nuxtjs frontend. I am using LaravelSanctum Provider in Nuxtjs. I am able to send request and the authentication and data retrival is fine. However, the cookies doesn't seem to get stored in my local storage.
login.vue
<script>
export default {
async login() {
this.$auth.loginWith('laravelSanctum', {
data: {
email: 'test#gmail.com',
password: 'test',
},
})
},
}
</script>
nuxt.config.js
axios: {
baseURL: 'http://local.api.test/api/v1/',
proxy: true,
credentials: true,
},
proxy: {
'/laravel': {
target: 'http://local.api.test/api/v1/',
pathRewrite: { '^/laravel': '/' },
},
},
auth: {
strategies: {
laravelSanctum: {
provider: 'laravel/sanctum',
url: 'http://local.api.test',
endpoints: {
login: {
url: '/api/v1/login/admin',
},
user: {
url: '/api/v1/admin',
},
},
},
},
},

Related

Getting Unathenticated Error NuxtJs Get request

Am trying to do a simple GET request in NuxtJs using Axios. l have configured my nuxt.config.js like this
axios: {
proxy: true,
credentials: true,
baseURL: 'http://localhost:8000/api/'
},
proxy: {
'/api': { target: 'http://localhost:8000', pathRewrite: {'^/api/v1/': ''} }
},
auth: {
strategies: {
laravelSanctum: {
provider: 'laravel/sanctum',
url: 'http://localhost:8000',
token: {
property: 'token',
global: true,
required: true,
type: 'Bearer',
name: 'Authorization'
},
refreshToken: {
property: 'token',
data: 'token',
maxAge: 60 * 60 * 24 * 30
},
user: {
property: 'user',
},
endpoints: {
login: { url: '/api/auth/login', method: 'post' },
user: { url: '/api/user', method: 'get' },
logout: { url: '/api/auth/logout', method: 'get' },
refresh: { url: '/api/refresh', method: 'get' },
},
tokenType: 'Bearer',
tokenRequired: true,
cookie: {
cookie: {
name: 'XSRF-TOKEN',
},
},
}
},
redirect: {
login: '/',
logout: '/',
callback: false,
home: '/'
},
},
router: {
middleware: 'auth'
},
l have tried alot of methods that were posted here before but no avail. Same issues. l also noticed that when l reload the page. Vuex shows user object empty.
Am using Laravel Sactum, any help will be greatly appreciated. Thanks in advance

in nuxt.js SSR i was created authentication system using laravel sactum im facing redirecting error

nuxt.js I'm implemented an SSR authentication system using Laravel sanctum but I'm facing Redirecting issue.
When I have entered login credentials after summited my LOGIN button it Was not redirected to Dashboard it still on the login page if I need to visit Dashboard I need to manually enter the dashboard URL same thing on logout.
nuxt.config.js
export default {
// Global page headers: https://go.nuxtjs.dev/config-head
head: {
title: 'hello',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: '' }
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
]
},
// Global CSS: https://go.nuxtjs.dev/config-css
css: [
],
router: {
middleware: ['auth'],
},
// Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
plugins: [
],
// Auto import components: https://go.nuxtjs.dev/config-components
components: true,
// Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules
buildModules: [
],
// Modules: https://go.nuxtjs.dev/config-modules
modules: [
// https://go.nuxtjs.dev/bootstrap
'bootstrap-vue/nuxt',
// https://go.nuxtjs.dev/axios
'#nuxtjs/axios',
// https://go.nuxtjs.dev/pwa
'#nuxtjs/pwa',
'#nuxtjs/auth-next',
],
// Axios module configuration: https://go.nuxtjs.dev/config-axios
axios: {},
auth: {
strategies: {
'laravelSanctum': {
provider: 'laravel/sanctum',
url: 'http://localhost:8000',
endpoints: {
login: {
url: "/api/login"
},
logout: {
url: "/api/logout"
},
user: {
url: "/api/user"
}
},
user: {
property: false
}
}
},
redirect: {
login: "/login",
logout: "/",
home: "/dashboard"
}
},
// PWA module configuration: https://go.nuxtjs.dev/pwa
pwa: {
manifest: {
lang: 'en'
}
},
// Build Configuration: https://go.nuxtjs.dev/config-build
build: {
babel: {
plugins: [
['#babel/plugin-proposal-private-methods', { loose: true }]
]
}
}
}
middleware
export default ({ app, redirect }) => {
if (app.$auth.loggedIn) {
return redirect("/");
}
};
Login Page
<template>
<b-container>
<b-row>
<b-col cols="6" class="mx-auto">
<b-card title="Login">
<b-button variant="primary" #click="login()">Login</b-button>
</b-card>
</b-col>
</b-row>
</b-container>
</template>
<script>
export default {
middleware: ["guest"],
data() {
return {
form: {
email : "john#email.com",
password : "123321"
}
};
},
methods: {
login() {
this.$auth
.loginWith("laravelSanctum", {
data: this.form
})
.then(response => console.log(response))
.catch(error => console.log(error));
}
}
};
</script>
Layout default
<template>
<div>
<div>
<b-navbar type="dark" variant="dark">
<b-navbar-brand href="/">NavBar</b-navbar-brand>
<b-navbar-nav class="ml-auto">
<template v-if="$auth.loggedIn">
<b-nav-item to="/dashboard">Dashboard</b-nav-item>
<b-nav-item href="#" #click.prevent="logout()">Logout</b-nav-item>
</template>
<template v-else>
<b-nav-item to="/login">Login</b-nav-item>
</template>
</b-navbar-nav>
</b-navbar>
</div>
<Nuxt />
</div>
</template>
<script>
export default {
methods: {
async logout() {
try {
await this.$auth.logout();
} catch (error) {
console.log(error);
}
}
}
};
</script>
#nuxt/auth do have a middleware for the auth already, you don't need to do it yourself.
To benefit of it, you can add this to your nuxt.config.js file
router: {
middleware: ['auth'],
},
In any .vue file that you want to whitelist (aka if you do not want to check if loggedIn is true), you can use the auth key
<script>
export default {
auth: false, // will bypass the middleware's verification
}
</script>
Everywhere else, it will double check that you're logged in before proceeding. Otherwise, it will bring you to the login page that you've specified.

CSRF token mismatch when using nuxt/auth + Laravel Sanctum

CSRF token mismatch. error on register page when I try to login it was working good.
my register page
<template>
<b-container>
<b-row>
<b-col cols="6" class="mx-auto">
<b-card title="Register">
<b-button variant="primary" #click="register()">Register</b-button>
</b-card>
</b-col>
</b-row>
</b-container>
</template>
<script>
export default {
auth: 'guest',
data() {
return {
name: "john",
email: "john#email.com",
password: "123321"
};
},
methods: {
async register() {
const data = {
'name': this.name,
'email': this.email,
'password': this.password
}
console.log(data);
try {
const res = await this.$axios.post('/register', data)
console.log(res)
}
catch(e) {
console.log(e.message)
}
}
}
};
</script>
nuxt.config.js
export default {
// Global page headers: https://go.nuxtjs.dev/config-head
head: {
title: 'hello',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: '' }
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
]
},
// Global CSS: https://go.nuxtjs.dev/config-css
css: [
],
router: {
middleware: ['auth'],
},
// Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
plugins: [
],
// Auto import components: https://go.nuxtjs.dev/config-components
components: true,
// Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules
buildModules: [
],
// Modules: https://go.nuxtjs.dev/config-modules
modules: [
// https://go.nuxtjs.dev/bootstrap
'bootstrap-vue/nuxt',
// https://go.nuxtjs.dev/axios
'#nuxtjs/axios',
// https://go.nuxtjs.dev/pwa
'#nuxtjs/pwa',
'#nuxtjs/auth-next',
],
axios: {
baseURL: "http://localhost:8000/api"
},
auth: {
strategies: {
'laravelSanctum': {
provider: 'laravel/sanctum',
url: 'http://localhost:8000',
endpoints: {
login: {
url: "/api/login"
},
logout: {
url: "/api/logout"
},
user: {
url: "/api/user"
}
},
user: {
property: false
}
}
},
redirect: {
login: "/login",
logout: "/",
home: "/dashboard"
}
},
// PWA module configuration: https://go.nuxtjs.dev/pwa
pwa: {
manifest: {
lang: 'en'
}
},
// Build Configuration: https://go.nuxtjs.dev/config-build
build: {
babel: {
plugins: [
['#babel/plugin-proposal-private-methods', { loose: true }]
]
}
}
}
Login Page
<template>
<b-container>
<b-row>
<b-col cols="6" class="mx-auto">
<b-card title="Login">
<b-button variant="primary" #click="login()">Login</b-button>
</b-card>
</b-col>
</b-row>
</b-container>
</template>
<script>
export default {
middleware: ["guest"],
data() {
return {
form: {
email : "john#email.com",
password : "123321"
}
};
},
methods: {
login() {
this.$auth
.loginWith("laravelSanctum", {
data: this.form
})
.then(response => console.log(response))
.catch(error => console.log(error));
}
}
};
</script>
EDIT: I do have the following error in my network tab devtools.
network tab error xhr.js?b50d:177 POST localhost:8000/api/register 419 (unknown status) "message": "CSRF token mismatch.", "exception": "Symfony\Component\HttpKernel\Exception\HttpException",

How to set up email provider in Strapi 3.0.1v?

I use Strapi 3.0.1 version and I try to adjust the reset password for admin. If I understand correctly I need to set up only an email provider. I had read the doc for setting up email provider here
I had installed the strapi-provider-email-nodemailer and created a file ./config/plugins.js with
module.exports = ({ env }) => ({
email: {
provider: 'nodemailer',
providerOptions: {
host: "smtp.***.***",
port: 465,
secure: true,
auth: {
user: "***",
pass: "***",
}
},
settings: {
defaultFrom: '***',
defaultReplyTo: '***',
},
},
});
After that, I navigate to ****/admin/auth/forgot-password* and input admin email and get an error This email is invalid.
{
"statusCode": 400,
"error": "Bad Request",
"message": [{"messages": [{"id": "Auth.form.error.email.invalid"}]}],
"data": [{"messages": [{"id": "Auth.form.error.email.invalid"}]}]
}
Could you please help me to set up an email provider or find a mistake?
It works with settings:
module.exports = ({ env }) => ({
email: {
provider: "nodemailer",
providerOptions: {
nodemailer_default_from: "XXX",
nodemailer_default_replyto: "XXX",
host: env('EMAIL_HOST'),
port: env('EMAIL_PORT', 25),
password: env('EMAIL_PASSWORD'),
username: env('EMAIL_USERNAME'),
authMethod: "SMTP",
}
},
});

DataSource transport.destroy called +1 times for each successive delete (recalled for previously deleted items)

I have a DataSource in my code that support destroy. In order to delete object from the it, i directly call remove, i.e.
myDataSource.remove(discardedData);
I get a behavior similar to this. However, unlike the linked thread, my destroy is not set to a function, so the solution does not help me.
My DataSource (i included all of it in case some of my configuration is to blame):
var QueueMessages = {
type: "aspnetmvc-ajax",
transport: {
read: {
url: BASE_URL + "api/QueueMessages/GetMessagesHeaders",
dataType: "json",
type: "GET",
beforeSend: function (req) {
req.setRequestHeader('Authorization', authService.getAuth());
}
},
destroy: {
url: BASE_URL + "api/QueueMessages/deleteMessage",
dataType: "json",
type: "DELETE",
beforeSend: function (req) {
req.setRequestHeader('Authorization', authService.getAuth());
}
}
},
schema: {
model: {
id: "id",
fields: {
profileName: { type: "string" },
queueType: { type: "string" },
acceptedAt: { type: "date" },
processedAt: { type: "date" },
BodyExcerpt: { type: "string" }
}
},
total: "total",
data: "data",
},
error: function (e) {
//throw user back to login page
if (e.errorThrown === "Unauthorized")
$rootScope.$apply($location.path('/'));
},
requestStart: function () {
},
requestEnd: function () {
},
pageSize: 50,
serverPaging: true,
serverFiltering: true,
serverSorting: true,
serverGrouping: true,
serverAggregates: true
};
I cant find any clues as to why this is happening.
thanks to OnaBai I found the problem.
consulting RFC 7231, i my changed the http DELETE response from 200 OK to 204 no content.

Resources