I am using NuxtJs auth module to handle my authorization in the state. For the auth I wrote an express api which works.
I have following configuration in my nuxt.config.js:
axios: {
baseURL: 'http://localhost:4000/api'
},
auth: {
strategies: {
local: {
endpoints: {
login: { url: '/users/login', method: 'post', propertyName: 'data.token' },
user: { url: '/users/me', method: 'get', propertyName: 'data' },
},
}
}
},
And in my login component I call the login route like this:
const { data } = await this.$auth.loginWith('local', {
data: this.login
})
This call the /api/users/login route successfully (200) and after that calls the /api/users/me with an error saying
xhr.js:178 GET http://localhost:4000/api/users/me 401 (Unauthorized)
In postman I am calling the api route which returns the user like this*
> Get - localhost:4000/api/users/me
>
> Authorization:
>
> Type: Bearer Token Token: xxxx
Which returns the users data.
I read that nuxt auth module default the type to 'Bearer' but in my case it does not work.
The user login work but the second route which returns the user data does not work due to authorization. The Api is not inside the nuxtjs it is a different project written in Express.
You can try this:
axios: {
baseURL: 'http://localhost:4000/api' },
auth: {
strategies: {
local: {
endpoints: {
login: { url: '/users/login', method: 'post', propertyName: 'data.token' },
user: { url: '/users/me', method: 'get', propertyName: 'data' },
},
tokenType: ''
}
}
},
Setting tokenType to an empty string overrides the default "Bearer". Some server configurations may throw a 401.
Related
So, I'm having a SPA which has Okta implemented for authentication. According to the Okta policy that is set up in place, the user(s) log in with credentials (email and password) and then are prompted to validate with a magic link or code (both sent to their primary email address). I'm trying to get around this and programmatically login through API
What I've tried so far:
a POST Request to the /api/v1/authn with the username and password (which returns a session token)
then a GET request to /oauth2/default/v1/authorize with the clientID,sessionToken,redirectUri,scope which should return the access and id tokens from my understanding...
This last request just redirect back to the login page.
Cypress.Commands.add('oktaLogin', () => {
const optionsSessionToken = {
method: 'POST',
url: `https://${Cypress.env('okta_domain')}/api/v1/authn`,
body: {
username: Cypress.env('okta_username'),
password: Cypress.env('okta_password'),
options: {
warnBeforePasswordExpired: 'true'
}
}
}
cy.request(optionsSessionToken).then(response => {
const sessionToken = response.body.sessionToken;
const qs = {
client_id: Cypress.env('okta_clientid'),
redirect_uri: `https://${Cypress.env('baseURL')}/callback`,
code_challenge_method: 'S256',
responseType: ['id_token','token'],
scope: ['openid', 'profile', 'email'],
sessionToken: sessionToken,
}
cy.request({
method: 'GET',
url: `https://${Cypress.env('okta_domain')}/oauth2/default/v1/authorize`,
form: true,
followRedirect: true,
qs: qs
}).then(response2 => {
//tokens should be available here?
cy.log(response2.body)}) //returns HTML back to login.
});
})
I started learning RTK Query few days ago and I have been enjoying it cool features and simplicity, so I decided to switch from useContext to RTK Query in the project I'm building with Next.js and a custom server using Node.js and express. In this project, I made an api route for login and signup which would be hit by using RTK Query and Axios with the help of custom axios base query RTK Query provided. The login and signup api endpoints already had a logic to store token inside the cookies storage. I use RTK Query with axios to post user request so they can get a response of their token store in cookies storage. This logic of storing user token in the cookies works well with useContext and axios.
But the logic didnot work as expected while using RTK Query, and these are results:
The token was set in the cookies storage but I get a response status of 401.
When user submit their credentials in the login or signup page, they are supposed to be redirected to profile page with their details being display since I made use of useQuery to fetch user profile. But the data did not display. Which means the token stored is not effective.
I'm unable to get the user information even though the token had been stored in the cookies.
Whenever I click on a link to redirect me to a particular route, useQuery didnot fetch anything and when I go back to profile, the user details will be fetched and display but when I refresh the page again, no data will be dsiplay
Whenever a get request was successful at the first time, I alway lose the data whenever I refresh the page.
All these issues only happens to routes that are protected with middleware in the backend and the middleware is to verify the token. But I have no issue with reloading a page which data that is not protected in the backend.
I also have a middleware in my backend for verifying and checking if token is true in the cookie to check if user is authenticated, if it is false, user should be directed to the login page in the frontend. The logic for fetching and check if data is true is inside HOC component which was wrapped with protected route, but whenever the data value is false, am still able to go to any route in the frontend instead of redirecting me to login page. And when I log the data to the console I recieve the correct data.
Removing token from cookie works successfully.
export const fetcherApi = createApi({
reducerPath: "fetcherApi",
baseQuery: axiosBaseQuery({
baseUrl: "http://localhost:5000/",
}),
tagTypes: ["User"],
endpoints(build) {
return {
//________Authentication
registerUser: build.mutation({
query: (form) => ({
url: "register",
method: "post",
data: form,
}),
invalidatesTags: ["User"],
}),
loginUser: build.mutation({
query: (form) => ({
url: "login",
method: "post",
data: form,
}),
invalidatesTags: ["User"],
}),
getAuth: build.query({
query: () => ({ url: "auth", method: "get" }),
}),
//__________User
updateUserName: build.mutation({
query: (...rest) => ({
url: "update-user",
method: "put",
data: rest,
}),
invalidatesTags: ["User"],
}),
getUser: build.query({
query: () => ({ url: "user", method: "get" }),
providesTags: ["User"],
}),
//__________Profile
postProfile: build.mutation({
query: (form) => ({
url: "login",
method: "post",
data: form,
}),
}),
getAllProfiles: build.query({
query: () => ({ url: "all-profiles", method: "get" }),
}),
getUserProfile: build.query({
query: () => ({ url: "profile/me", method: "get" }),
}),
//___________Car
postCar: build.mutation({
query: (form) => ({
url: "new-car",
method: "post",
data: form,
}),
}),
putCar: build.mutation({
query: ({ id, ...rest }) => ({
url: `update-car/{id}`,
method: "put",
data: { rest },
}),
}),
getAllCars: build.query({
query: () => ({ url: "all-cars", method: "get" }),
}),
getCarById: build.query({
query: (id) => ({ url: `onecar/${id}`, method: "get" }),
}),
getAllUserCars: build.query({
query: () => ({ url: "my-car", method: "get" }),
}),
};
},
});
export const {
// ______Authentication______
useGetAuthQuery,
useRegisterUserMutation,
useLoginUserMutation,
//_______User_________
useUpdateUserNameMutation,
useGetUserQuery,
//_____Profile_________
useGetUserProfileQuery,
useGetAllProfilesQuery,
usePostProfileMutation,
//_____Car____________
usePostCarMutation,
usePutCarMutation,
useGetAllCarsQuery,
useGetCarByIdQuery,
useGetAllUserCarsQuery,
} = fetcherApi;
I solve this issue by adding credentials: include as baseQuery parameter and I added async and await in my functions
baseQuery: fetchBaseQuery({
baseUrl: "https://my-app.herokuapp.com/",
credentials: "include",
}),
I am using nuxt.js (frontend) and laravel6 (backend) API. Laravel app is running http://172.16.10.86:8000 port and nuxt.js app is running http://localhost:3000. I want to send data in my MySQL database using nuxt.js app. When I send POST request from my nuxt.js app it redirects properly but does not insert any data in database. Inside network tab, I found a 404 error.
methods:{
async register(){
try {
await this.$axios.post('/auth/register',this.form);
} catch(e) {
return;
}
this.$auth.login({data: this.form});
this.$router.push({name:'index'});
}
nuxt.config.js
auth: {
strategies: {
local: {
endpoints:{
login:{
url: '/auth/login',method: 'post', propertyName: 'token'
},
user:{
url:'me', method: 'get', propertyName: 'data'
},
logout:{
url:'logout', method: 'get'
}
}
}
},
axios:{
baseUrl:'http://172.16.10.86:8000/api'
},
I believe you just typo in your axios config.
It's should be baseURL not baseUrl. Please take a look at the docs.
You need to add full URL for the API server.
methods:{
async register() {
try {
await this.$axios.post('http://172.16.10.86:8000/api/auth/register', this.form);
} catch(e) {
return;
}
this.$auth.login({data: this.form});
this.$router.push({name:'index'});
}
I am having an issue in setting the authorization token to the request header. I always get a 401 Unathuroized issue after setting my header using a bearer driver. Below is my code:
bearer.js
module.exports = {
request: function (req, token) {
this.options.http._setHeaders.call(this, req, {Authorization: 'Bearer ' + token})
},
response: function (res) {
if (res.data.token) {
return res.data.token
}
}
}
main.js
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)
import VueAuth from '#websanova/vue-auth'
Vue.use(VueAuth, {
auth: require('#websanova/vue-auth/drivers/auth/bearer.js'),
http: require('#websanova/vue-auth/drivers/http/axios.1.x.js'),
router: require('#websanova/vue-auth/drivers/router/vue-router.2.x.js'),
refreshData: {url: 'auth/refresh', method: 'GET', enabled: false, interval: 30},
fetchData: {url: 'auth/user', method: 'GET', enabled: false},
notFoundRedirect: {path: '/admin'},
rolesVar: 'roles',
})
and the code in login.vue
this.$auth.login({
data: credentials,
url: process.env.VUE_APP_URL + '/api/v1/login',
fetchUser: false,
success: function (response) {
if(response.data){
localStorage.setItem('user',(JSON.stringify(response.data.data)));
this.$auth.user(response.data.data);
this.$auth.watch.authenticated = true;
this.$auth.watch.loaded = true;
this.$router.push('/dashboard');
axios.defaults.headers.common["Authorization"] = "Bearer " + response.data.data.token;
debugger;
}
},
error: function () {
this.$notify({
type: 'warn',
title: 'Login',
text: 'Login failed'
});
},
})
I tried to add a debugger inside the request method of a bearer.js driver, that doesn't seem to execute.
I am using the contentful (CMS platform) api to get the user details by userId by using request module. Here, the access-token is passed as query param which the system recognizes as invalid. But I am not sure if there is any wrong in the way I am passin the query param.I am pretty sure the token passed is valid as I can get the proper result using rest-client. Code is given below:
request.get(
{
url:
"https://api.contentful.com/organizations/organizationId/users/userId",
qs: {
access_token:
" CFPAT-xxxxxxxxxxxxxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx "
},
headers: {
Authorization:
"CFPAT-xxxxxxxxxxxxxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"x-contentful-enable-alpha-feature": "organization-user-management-api",
"Content-Type": "application/json"
},
method: "GET",
json: true
},
function(error, response, body) {
console.log(body);
}
);
Error:
{ requestId: 'e102c744950f39fdabad9ae942ac16ba',
message:
'The access token you sent could not be found or is invalid.',
sys: { type: 'Error', id: 'AccessTokenInvalid' } }