I am using pusher-js in react. My frontend is served at app.xxx.com and my backend is served at api.xxx.com. We have a private notification websocket channel to push notiifcations through app.xxx.com. What i'm trying to achieve is using the auth endpoint on backend. But no matter what i do, pusher will always request to the base URL of frontend plus auth endpoint. In my case it will be https://app.xxx.com/broadcasting/auth but i want it to be https://api.xxx.com/broadcasting/auth. What should i do? Here's my pusher config:
pusher = new Pusher(APP_ID, {
httpHost: process.env.REACT_APP_WS_HOST,
authEndpoint: '/broadcasting/auth',
auth: {
params: {
id: userData.id,
},
headers: {
'X-CSRF-Token': '{{ csrf_token() }}'
}
},
cluster: 'ap2',
wsHost: process.env.REACT_APP_WS_HOST,
wsPort: 6001,
wssPort: 6001,
forceTLS: true,
})
The value of process.env.REACT_APP_WS_HOST is api.xxx.com
UPDATE:
I even tried adding an authHost key but nothing changed.
You should be able to use the full URL to the endpoint:
authEndpoint: 'https://api.xxx.com/broadcasting/auth'
I have a Nuxt app setup with #nuxt/auth. The user always get redirected to login page whenever the page is refreshed. I guess the server side of the Nuxt app is not logged in while the client side is logged in. The JWT access token is gotten from an Express API. Please can someone help me to solve this?. Here is my nuxt.config.js
auth: {
redirect: {
login: '/',
logout: '/',
home: '/dashboard',
},
resetOnError: true,
rewriteRedirects: true,
strategies: {
local: {
token: {
property: 'data.accessToken',
},
user: {
property: 'data[0]',
autoFetch: false,
},
endpoints: {
login: {
url: '/api/v1/users/login',
method: 'post',
},
logout: false,
user: {
url: '/api/v1/users',
method: 'get',
propertyName: false,
},
},
},
},
},
And my dashboard.vue
export default {
middleware: ['auth'],
};
Here is my working nuxt.config.js
export default {
router: {
middleware: ['auth'],
},
modules: [
'#nuxtjs/auth-next'
],
auth: {
redirect: {
login: '/login',
home: '/',
logout: '/login',
callback: false, // not used here in our case
},
localStorage: false, // REALLY not secure, so nah
resetOnError: true, // kick the user if any error happens w/ the auth
strategies: {
local: {
scheme: 'refresh', // used for the refreshToken flow
token: {
property: 'access_token',
maxAge: 3600, // only useful if not detected on the login
},
refreshToken: {
property: 'refresh_token',
data: 'refresh_token',
maxAge: 60 * 60 * 24 * 30, // 1 month
},
clientId: process.env.IAM_CLIENT_ID, // our application's ID aka browser
user: {
property: 'employee',
autoFetch: false, // no need to fetch the user, will be done in gql
},
endpoints: {
login: { url: '/login', method: 'post' },
refresh: { url: '/oauth/refresh', method: 'post' },
user: false, // as told above, this one is not needed
logout: { url: '/logout', method: 'get' },
},
tokenRequired: true,
tokenType: 'JWT',
},
},
plugins: [
'~/plugins/nuxt-axios.js',
{ src: '~/plugins/nuxt-auth.js', mode: 'client' },
],
}
nuxt-auth.js is a basic logger in case of an error
import $toast from '~/mixins/buefy-toast'
export default function ({ $auth }) {
$auth.onError((_name, error) => {
$toast.open({ message: error })
})
}
Another important part is my login flow (triggered on a form submit)
export default {
methods: {
async authMe() {
const succesfulLogin = await this.$auth.loginWith('local', {
data: {
email: this.email,
password: this.password,
},
})
if (succesfulLogin) {
await this.$auth.setUser({
email: this.email,
password: this.password,
})
}
}
// ...
}
}
We do basically not get the user on the API while authenticating, but rather submit the credentials and validate them, then setting the flag manually with the function $auth.setUser. This is the only part that I handle to pass the loggedIn flag to true, the remaining configuration is just project configuration.
We do also have some refreshToken on our JWT but you can totally omit this one.
Axios config file is basically setting our app's needed headers.
The auth middleware is the one coming w/ the #nuxt/auth module itself, I did not wrote it myself. This is totally working (cookies + vuex state) when generated with target: 'static'.
Good day.
I've been using js-cookie to set cookies in my application, they are set in the exact same way however one of them turns into undefined whenever i use window.location or reload the page. I set 2 cookies, one for a token and one for for the user role in my application but for whatever reason the user role cookie is reset.
Here is how i set it:
login ({dispatch }, payload) {
axios.get('/login',{
auth: {
username: payload.username,
password: payload.password
}
}).then(function (response) {
let in120Minutes = 1/12;
Cookies.set('user_role', response.data['permissions'].user_role, {expires: in120Minutes})
Cookies.set('token', response.data['x-access-token'], {expires: in120Minutes})
window.location.pathname = '/myPage'
}).catch(function (error) {
dispatch('errorHandler', error, { root: true })
})
},
Why does this happen exactly? I do the exact same thing into another application and it works fine.
This is my strategy, which is defined on a server.register(). I'm basing my work off a tutorial and it is literally copied from it but it doesn't work.
server.auth.strategy('standard', 'cookie', {
password: 'somecrazycookiesecretthatcantbeguesseswouldgohere', // cookie secret
cookie: 'app-cookie', // Cookie name
isSecure: false, // required for non-https applications
redirectTo: '/login',
ttl: 24 * 60 * 60 * 1000 // Set session to 1 day
});
server.auth.default({
strategy: 'standard',
mode: 'required',
scope: ['admin']
});
This is my login route where the error occurs:
server.route({
method: 'POST',
path: '/login',
config: {
auth: false,
validate: {
payload: {
email: Joi.string().email().required(),
password: Joi.string().min(2).max(200).required()
}
},
handler: function (request, reply) {
getValidatedUser(request.payload.email, request.payload.password)
.then(function (user) {
if (user) {
//ERROR OCCURS HERE: IT SAYS SESSION IS UNDEFINED
request.auth.session.set(user);
return reply('Login Successful!');
} else {
return reply(Boom.unauthorized('Bad email or password'));
}
});
// .catch(function (err) {
// return reply(Boom.badImplementation());
// });
}
}
});
I've tried so many things but this part is crucial for this work and I can't find anyone with the same problem. Help please!
hapi-auth-cookie has changed the way cookies are set and cleared. As of version 5.0.0, use request.cookieAuth.set() and request.cookieAuth.clear(). You are probably using a more recent version of the plugin than is used in the package.json of the tutorial.
source:
https://github.com/hapijs/hapi-auth-cookie/commit/d233b2a3e4d0f03ef53b91b7929b8dbadbff624c
I'm using this library for a JQuery plugin I'm coding... I save inside a cookie a specific data created by the user in this way:
// Update cookies checks if the cookie esists.
// If cookie exists => push data {myData:[obj1[, obj2, [...], objN]]}
// If cookie doesn't exists => create cookie with {myData:[obj1]}
function _updateCookie(name, cookie, data) {
// Check if cookie exists
var cookies = {myData:[]};
// _getCookie(name) { return Cookies.get(name) }
if (_getCookie(name) != undefined) {
cookies = _getCookie(name);
}
cookies.reminders.push(cookie);
Cookies.set(name, cookies, data);
}
DATA:
var data = {
expires: 1,
path: '/',
domain: '',
secure: true
}
COOKIE:
var cookie = {
myData: [
1: myObject1,
2: myObject2,
// [...]
n: myObjectN
],
}
When I call _getCookie(name) it always returns undefined. I've also tried to list the cookies with:
console.log(Cookies.get());
// log: Object {_ga: "GA1.1.402426237.1450622600"}
But if i look at chrome://settings/cookies i see:
2 cookies on localhost [_ga], [myCookie]
Any suggestion of what am I doing wrong?
EDIT
I saw that the problem comes out when i call Cookie.set(); with this values
Cookies.set('myCookie', {[expires: ...], path: '', domain: ''});
if I call
Cookies.set('myCookie'{[expires: ...]});
I can get the cookie with no problems.