Activities

binoysarker

binoysarker posted a new question

auth-module •

UnauthorizedError: jwt malformed

i am trying to use this auth-module in my nuxt js application. i followed all the standard process to install nuxt app, auth-module. I also copy most of the code from the code in the example given here.

my code in nuxt config file
serverMiddleware: ['~/api/auth'], auth: { strategies: { local: { endpoints: { login: { url: '/api/auth/login', method: 'post', propertyName: 'token.accessToken' }, logout: { url: '/api/auth/logout', method: 'post' }, user: { url: '/api/auth/user', method: 'get', propertyName: 'user' } } // tokenRequired: true, // tokenType: 'bearer' }, auth0: { domain: 'nuxt-auth.auth0.com', client_id: 'q8lDHfBLJ-Fsziu7bf351OcYQAIe3UJv' } } }, eslint: { fix: true }, /* ** Axios module configuration ** See https://axios.nuxtjs.org/options */ axios: { proxy: true }, proxy: { '/api': 'http://localhost:3000' },
my code in api/auth.js file
`const express = require('express')
const bodyParser = require('body-parser')
const cookieParser = require('cookie-parser')
const jwt = require('express-jwt')
const jsonwebtoken = require('jsonwebtoken')

// Create app
const app = express()

// Install middleware
app.use(cookieParser())
app.use(bodyParser.json())

// JWT middleware
app.use(
jwt({
secret: 'dummy'
}).unless({
path: '/api/auth/login'
})
)

// -- Routes --

// [POST] /login
app.post('/login', (req, res, next) => {
const { username, password } = req.body
const valid = username.length && password === '123'

if (!valid) {
throw new Error('Invalid username or password')
}

const accessToken = jsonwebtoken.sign(
{
username,
picture: 'https://github.com/nuxt.png',
name: 'User ' + username,
scope: ['test', 'user']
},
'dummy'
)

res.json({
token: {
accessToken
}
})
})

// [GET] /user
app.get('/user', (req, res, next) => {
res.json({
user: req.user
})
})

// [POST] /logout
app.post('/logout', (req, res, next) => {
res.json({
status: 'OK'
})
})

// Error handler
app.use((err, req, res, next) => {
console.error(err) // eslint-disable-line no-console
res.status(401).send(err + '')
})

// -- export app --
module.exports = {
path: '/api/auth',
handler: app
}
`
and this error is showing up
image

Please tell me how can i fix this. Thanks

rossthemusicteacher

rossthemusicteacher posted a new question

auth-module •

Google Auth Redirecting Me, But Vuex State for loggedIn and user does not change.

NUXT version: ^2.4.0

auth stuff in NUXT config:
fetchUserOnLogin: true,
redirect: {
login: '/login',
logout: '/',
callback: '/login',
home: '/'
},
strategies: {
'google': {
client_id: '57605071811-9aj9lah24gka212dcotvrhlhneaflf2n.apps.googleusercontent.com'
}
}

After setting up the auth module, I am using $auth.loginWith('google). Once I am authenticated, it sends me back to my redirect. On that page, I obeserve that the key has been stored in local storage, but the vuex store has not been altered at all, and the auth strategy is 'local'.

I am a fairly new dev, so I am not sure if this is a genuine bug or if I flubbed something up. Any help is GREATLY GREATLY appreciated.

craigPeckett

craigPeckett posted a new question

auth-module •

IE does not call the user get request when logging in after logging out

Using google chrome everything in my application seems to work ok but when I use internet explorer i get the following issue.

  1. Log in as user a,
  2. logged in as user a,
  3. log out
  4. log in as user b,
  5. logged in as user a
  6. refresh web browser
  7. logged in as user b

The get user function only seems to be called once the browser is refreshed and not straight after the user has logged in. any ideas

homerjam

homerjam posted a new bug report

auth-module •

bug body-parser should be in dependencies not devDependencies

Version

v4.8.1

Reproduction link

http://url.com

Steps to reproduce

Try running a basic example without body-parser installed

Error while initializing nuxt: { /var/task/node_modules/@nuxtjs/auth/lib/providers/_utils.js:1
Error: Cannot find module 'body-parser'

What is expected ?

It should work

What is actually happening?

Nuxt can't find the body-parser module

stivenramireza

stivenramireza posted a new question

auth-module •

Cannot read property '$auth.$state' of undefined

When I use v-if="!$auth.$state.loggedIn" or whatever property of Nuxt.js auth-module, I get that error. Someone knows how can I fix it?

jskorlol

jskorlol posted a new question

auth-module •

I have a question on setToken setting.

If you enter a token with the command below, the token type is not specified.

$ nuxt. $ root. $ auth.setToken ('local', $ {response.data.token}): tokenType does not apply.

('local', Bearer $ {response.data.token})
I have to put Bearer myself.

alwindeleon

alwindeleon posted a new question

auth-module •

Improve Documentation

In my own experience, its hard to get started using this module. It seems that a lot of the community prefer to implement their own auth just because of the difficulty of trying to set this up. I was wondering if and how I can help to improve the documentation and if there already is a better set of documentation.

Currently, I've finished setting up the local strategy auth but the Facebook auth is giving me a headache. I'm trying to follow the demo repo but it seems different from the one deployed and being showed.

noobling

noobling posted a new question

auth-module •

Broken link

The providers link here is a 404 not sure where it is meant to go…

samboylett

samboylett posted a new bug report

auth-module •

bug Using both Cookie and Localstorage methods creates issues with SSR

Version

v4.8.1

Reproduction link

http://abc

Steps to reproduce

  1. Use local scheme to login
  2. Close browser
  3. Open browser back on website

What is expected ?

The login state should be persisted between server and client side

What is actually happening?

The cookie has expired, so server side is rendering as if not logged in, but client side reads the local storage so logs the user in, resulting in a different rendered DOM to server side.

Additional comments?

The logged in state is being saved in local storage and cookie. The issue is that the cookie expires after the session ends, so when the user returns the server side rendered DOM will be different to the client side, as there is no cookie but the client side can fall back onto local storage.

Setting localStorage: null will fix this

Torone

Torone posted a new bug report

auth-module •

bug Token expired

Version

v4.8.1

Reproduction link

http://sorry-no-link

Steps to reproduce

  • Wait for a API token to be expired
  • Only errors are shown…

What is expected ?

The user should be logged out, token cleared from cookies/local storage/etc. It should be reactive.

What is actually happening?

I can see the user logged in, the store contains all the user information, navigating on a page that require a user to be logged in do nothing, the page run, try to fetch data with an invalid token, it return error 401, nothing happen.
I tried to create a custom middleware but I can not logout the user manually. It is just broken/stuck.

Additional comments?

It would be nice to have an example about how to handle situations like this.

GillesWHC

GillesWHC posted a new question

auth-module •

Google Strategy Token Expiration

Due to refresh tokens not being implemented yet, my google token expires after 1 hour. Is there a way to prolong this currently?

samanthabaita

samanthabaita posted a new question

auth-module •

Why the authentication configurations are embedded during build process?

Hi, I have a question about the configuration of the module.

Context

I am building a Nuxtjs Web App with Auth0 Universal authentication containerized with Docker. At my company we have different environments (in this case, staging and production). I need to execute the application on different environment and I'm trying to build a Docker image that can be used in every environment. Usually I configure the Docker container with env variables with docker run command.

Problem

I saw that in the module/plugin.js file there is the line const options = <%= JSON.stringify(options.options) %> that substitutes the options during build. I have some problems to understand how I can change this configuration between different environments. I found a solution, I can build different images for each environment, but I think that this solution could be improved because now my images depends on environment and on current configuration, so the application is not portable.

I saw the same technique in nuxt-i18n module, but I feel that translation is more application context. The authentication configuration is more about the infrastructure so I think this kind of configuration could be outside the building process.

What do you think about that? Maybe there is a solution that I didn't thought about.

scaff

scaff posted a new question

auth-module •

How to login without being redirected ?

Hello,
I'm trying to build a login form component that behave differently according to where it's been used.

Basicly, the form emit a loggedIn event when the login has been successful so the parent will redirect if needed.
Another use case is the use of the same login form inside a modal (a multi step form that ask for login before going further.

The problem is loginWith automaticaly redirects me to /.

Here is the code of my form :

<template>
  <div>
    <form @submit.prevent="onSubmit">
      <label for="username">
        {{ $t('LoginForm.username') }} :
        <input id="username" v-model="$v.form.email.$model" type="text">
      </label>
      <br>
      <label for="password">
        {{ $t('LoginForm.password') }} :
        <input id="password" v-model="$v.form.password.$model" type="password">
      </label>
      <br>
      <input type="submit" :value="$t('LoginForm.login')">
    </form>
  </div>
</template>

<script>
import { required, email } from 'vuelidate/lib/validators'

export default {
  data () {
    return {
      form: {
        email: '',
        password: ''
      }
    }
  },
  methods: {
    onSubmit () {
      this.$v.$touch()
      if (this.$v.$invalid) {
        this.$toast.error('Veuillez compléter correctement le formulaire')
      }

      this.$auth.loginWith('local', {
        data: {
          email: this.form.email,
          password: this.form.password
        }
      })
        .then((result) => {
          this.$toast.success(this.$t('LoginForm.loginSuccess'))
          this.$emit('loggedIn')
        })
        .catch((err) => {
          this.$toast.error(this.$t('LoginForm.loginError'))
        })
    }
  },
  validations: {
    form: {
      email: {
        required,
        email
      },
      password: {
        required
      }
    }
  }
}
</script>

and the nuxt.config.js:

auth: {
    strategies: {
      local: {
        endpoints: {
          login: { url: '/sessions', method: 'post', propertyName: 'data.jwtToken' },
          user: false,
          logout: false
        }
      }
    }
  }

How to prevent that ?

Thanks in advance for your help

Geminii

Geminii posted a new question

auth-module •

Redirection from guest page to redirect.home

Hi,

I need some help about redirection when i open the browser if the user has already been authenticated. Here is my configuration to reproduce :

Configuration

auth: {
    // Options
    strategies: {
      local: {
        endpoints: {
          login: { url: process.env.BASE_URL + '/auth', method: 'post', propertyName: 'token' },
          logout: false,
          user: { url: process.env.BASE_URL + '/users/auth', method: 'get', propertyName: false }
        }
      }
    },
    redirect: {
      login: '/signin,
      logout: '/signin',
      home: '/home'
    },
    resetOnError: true,
    rewriteRedirects: true,
    fullPathRedirect: true
  },
  router: {
    middleware: ['auth']
  },

Version

"@nuxtjs/auth": "^4.8.1",
"@nuxtjs/axios": "^5.5.4",

Steps to reproduce

  • I authenticate my user on the application (url : /signin)
  • User is redirect to /home
  • I kill/close my browser
  • Reopen the default page, user is connected but not redirect (url: /).

What is expected ?

  • On the default page (guest middleware), i want to be redirect to /home page instead of current default page /.

What is actually happening?

  • When i reopen the browser, call on the endpoint.user is DONE successfully
  • User is authenticated on the header, but the middleware doesn't redirect to /home.

Comments
I try to debug the problem of redirection but i think it's a problem about watch on loggedIn.
Currently, to fix this problem, i need to add this code into the layout :

    created() {
      if (this.$store.state.auth.loggedIn) {
        this.$router.push('/home');
      }
    },

But in theory, i don't need to write this code, because on the default layout, i use auth: 'guest'.

Maybe i missing something in the configuration ? or this case isn't implemented at the moment ?

Thanks a lot for your answers.
Best regards.

edwh

edwh posted a new question

auth-module •

Blocking login modal for some pages?

I have some pages that I need to force login for, and some I don't. I can find examples about how to force a redirect when you're not logged in (e.g. https://nuxtjs.org/examples/auth-routes/), but what I'd like to do is to force a blocking modal, so that once the login has completed I remain on the correct page, which will then render correctly. My login processing is inside my default layout.

Has anyone done something like this, so they can point me at an example of how to do it correctly? I'm fairly new to Nuxt, so if I roll my own I'll probably do it in a silly way.

I'm wanting to use SSR too, which may well affect the solution.

leo91000

leo91000 posted a new bug report

auth-module •

bug Computed loggedIn property : Mismatching childNodes vs. VNodes

Version

v4.8.1

Reproduction link

https://codesandbox.io/s/codesandbox-nuxt-mcvnw?fontsize=14

Steps to reproduce

1) Install nuxt
2) Setup axios and auth (I use axios 5.5.4)
3) Install vuetify (optional)
4) Setup vuetify (optional)
5) In the layout of your application add a computed property with the following function :
isLogged() {
return this.$auth.loggedIn;
}
6) Add the following html tag : <v-btn v-if="isLogged">Login</v-btn>

What is expected ?

The code should not return any error.

What is actually happening?

I get the following error :
"[Vue warn]: The client-side rendered virtual DOM tree is not matching server-rendered content. This is likely caused by incorrect HTML markup, for example nesting block-level elements inside

, or missing . Bailing hydration and performing full client-side render."

Additional comments?

Note : If I remove the v-if directive, the error disapear

DmitriyColors

DmitriyColors posted a new question

auth-module •

how unset headers for login strategy [401, error: NotAuthenticated: No auth token]

Hello my friends!
For a long time I read open-ended issue, but I did not find an answer.
I hope you will help!

Working request: await this.$axios.$post('/api/login', { strategy, email, password })

Not a work request that I make in $auth

async login () {
        try {
          await this.$auth.loginWith('customLocal' ,{
            strategy: this.auth.strategy.local,
            email: this.auth.inputLogin,
            password: this.auth.inputPassword
          })
        } catch (e) {
          this.formError = e.message
        }
      }

As a result, I get a 401 error and a message on the server error: NotAuthenticated: No auth token

As I understand $auth set headers "Content-type" : "***", "Authorization" : "***" by default.
I get the same result by adding headers to the work request in Postman.

{
    "name": "NotAuthenticated",
    "message": "No auth token",
    "code": 401,
    "className": "not-authenticated",
    "data": {},
    "errors": {}
}

Is it possible to avoid such behavior? If so, how?

*** My settings nuxt.config.js ***

  modules: [
    '@nuxtjs/axios',
    '@nuxtjs/proxy',
    '@nuxtjs/auth'
  ],
  axios: {
    proxy: true
  },
  proxy: {
    '/api/login': { target: 'http://127.0.0.1:3030', pathRewrite: {'^/api/login': '/authentication'} },
    '/api/user' : { target: 'http://127.0.0.1:3030', pathRewrite: {'^/api/user' : '/users'} },
    '/api/registration' : { target: 'http://127.0.0.1:3030', pathRewrite: {'^/api/registration' : '/users'} },
  },
  auth: {
    strategies: {
      local: {
        endpoints: {
          login: { url: '/api/login', method: 'post', propertyName: false},
          user: false,
          logout:false,
        }
      }
    }
  },
  router: {
    middleware: ['mobile', 'auth']
  }
gotenxds

gotenxds posted a new feature request

auth-module •

idea Disable need for token

What problem does this feature solve?

Hello ^^

I would like to suggest the ability to remove the need for a token on fetchUser method.

In my use case I handle all flows with a code flow, google, Facebook and "local" I then save the access token on the server and my requests are authorized from the client via a session.

When fectuser is called my server checks for an active session and return the data or 204 if non found.
Right now to make this work I need to add this to my mounted method on default layout:

    async mounted() {
      await this.$auth.setUserToken('OK'); // Does not matter, we work with sessions.
      await this.$auth.fetchUser();
    }

I would like to disable the need for a token to call fetch user.

What does the proposed changes look like?

Expose some property that will disable the need for a token ?

mstacy

mstacy posted a new question

auth-module •

Improper check of hasRefreshTokenChanged

https://github.com/nuxt-community/auth-module/blob/226203fe33f6ee68b89fd66bfd76bc1ebb87aa20/lib/schemes/refresh.js#L94

Believe this line should be:
this.hasRefreshTokenChanged = refreshToken !== this._getRefreshToken()

Current check returns false when with different tokens:
this.hasRefreshTokenChanged = refreshToken === this._getRefreshToken()

From the check below using this.hasRefreshTokenChanged:
if (!this._getRefreshTokenExpiration() || this.hasRefreshTokenChanged) {
It would appear the current check is giving the wrong response and the functionality doesn't match with the variable name. Current naming implies we are looking for the tokens to be different from one another

razukc

razukc posted a new feature request

auth-module •

idea Different redirect routes for different strategies

What problem does this feature solve?

When using more than one strategy, different redirect option for each strategy can be configured.

What does the proposed changes look like?

HI,
have an problem with redirect routes. How can I set different redirect rout for
different auth strategies in my nuxt.config.js
This is my config file.
`auth: {
strategies: {
user: {
scheme: 'local', endpoints: { login: { url: '/user/signin', method: 'post', propertyName: 'accesstoken' },
logout: { url: '/user/logout', method: 'get' },
user: { url: '/user/details', method: 'get', propertyName: 'user' }
},
tokenType: 'Bearer',
redirect: {
login: '/user/signin',
logout: '/user/logout',
callback: '/',
home: '/user/details'
},
},
provider: {
scheme: 'local', endpoints: { login: { url: '/provider/signin', method: 'post', propertyName: 'accesstoken' },
logout: { url: '/provider/logout', method: 'get' },
user: { url: '/provider/profile', method: 'get', propertyName: 'user' }
},
tokenType: 'Bearer',
redirect: {
login: '/provider/signin',
logout: '/provider/logout',
callback: '/provider',
home: '/provider/profile'
},
},

},

},
`