Core: I have a problem with authentication

Created on 12 Mar 2017  路  7Comments  路  Source: adonisjs/core

I'm making chat project phone, I'm using adonis for web services, I tried to use Jwt and Api for authentication, but I always have some issues.

1- doesn't work with POST method and gives me this message, I'm suing Postman for testing.

```{
"error": {
"message": "host and origin mis-match",
"name": "Error",
"status": 403,
"frames": [
{
"file": "node_modules\adonis-middleware\src\Shield\index.js",
"method": "Shield._validateCsrf",
"line": 182,
"column": 23,
"context": {
"start": 177,
"pre": " if (this.shieldConfig.csrf.compareHostAndOrigin) {n const host = request.hostname()n const requestOrigin = request.header('origin') || request.header('referer')n const originHost = requestOrigin ? url.parse(requestOrigin).hostname : nulln if (!originHost || host !== originHost) {",
"line": " const error = new Error('host and origin mis-match')",
"post": " error.status = 403n error.code = 'EBADCSRFTOKEN'n throw errorn }n }"
}
},
{
"file": "node_modules\adonis-middleware\src\Shield\index.js",
"method": "Shield.handle",
"line": 253,
"column": 12,
"context": {
"start": 248,
"pre": " returnn }nn const csrfSecret = yield request.session.get(this.sessionKey)n if (methods.indexOf(requestMethod) > -1 && !this._isFiltered(request, filterUris)) {",
"line": " this._validateCsrf(request, csrfSecret)",
"post": " }n yield this._setupCsrf(request, response, csrfSecret)n yield nextn }n"
}
},
{
"file": "node_modules\co\index.js",
"method": "onFulfilled",
"line": 65,
"column": 19,
"context": {
"start": 60,
"pre": " */nn function onFulfilled(res) {n var ret;n try {",
"line": " ret = gen.next(res);",
"post": " } catch (e) {n return reject(e);n }n next(ret);n }"
}
},
{
"file": "internal/process/next_tick.js",
"method": "process._tickCallback",
"line": 103,
"column": 7,
"context": {}
}
]
}
}

2- `request.authUser` doesn't work with jwt to get user information, Gives me the empty array.

3- How to use _csrf with web services and how to fix jwt and api problems with POST PUT DELETE

Please help me, I have to finish this project as soon as possible.


This is my my AuthController 

```js
'use strict'
const Hash   = use('Hash')
const User   = use('App/Model/User')

class AuthController {

  * login(request, response) {

    const mobile   = request.input('mobile')
    const password = request.input('password')
    const login    = yield request.auth.attempt(mobile, password)

    try {
      yield request.auth.validate(mobile, password)
    } catch (e) {
      response.unauthorized({error: e.message})
    }

    if (login) {

      const user = request.currentUser

      response.status(201).json({'login': login,'user': request.authUser})

    } else {
      response.unauthorized('Invalid credentails')
    }

  }

  * store(request, response) {
    //
  }

  * show(request, response) {
    //
  }

  * edit(request, response) {
    //
  }

  * update(request, response) {
    //
  }

  * destroy(request, response) {
    //
  }

}

module.exports = AuthController

And this my route

'use strict'

/*
|--------------------------------------------------------------------------
| Router
|--------------------------------------------------------------------------
|
| AdonisJs Router helps you in defining urls and their actions. It supports
| all major HTTP conventions to keep your routes file descriptive and
| clean.
|
| @example
| Route.get('/user', 'UserController.index')
| Route.post('/user', 'UserController.store')
| Route.resource('user', 'UserController')
*/

const Route = use('Route')

const Config = use('Config')
Config.set('auth.authenticator', 'jwt')

Route.post('/api/login', 'AuthController.login')

//// Api Routes Group
Route.group('api', () => {

    Route.post('/get', 'AuthController.postLogin')

}).prefix('api')/*\\.middleware(['auth:jwt'])*/

//// Admin Login
Route.on('/').render('admin.login')
Route.on('/login').render('admin.login')
Route.post('/admin/login', 'AdminController.postLogin')



//// Admin Routes Group
Route.group('admin-routes', () => {

  Route.get('/', 'DashboardController.index')
  Route.get('admin', 'DashboardController.index')
  // Users
  Route.resource('users', 'UsersController')
  Route.get('users/page/:page', 'UsersController.index')
  // Settings
  Route.resource('settings', 'SettingsController')
  // complaints
  Route.resource('complaints', 'ComplaintsController')
  Route.get('complaints/page/:page', 'ComplaintsController.index')
  // rates
  Route.resource('rates', 'RatesController')
  Route.get('rates/page/:page', 'RatesController.index')
  // payments
  Route.resource('payments', 'PaymentsController')
  Route.get('payments/page/:page', 'PaymentsController.index')

}).middleware('auth').prefix('admin')



//// Users Routes Group
Route.group('auth-routes', () => {



  Route.get('logout', 'AdminController.logout')

}).middleware('auth')



// Route.get('/got', function * (request, response) {
//     response.status(200).json({ user: 'prosper' })
// }).middleware('auth')

Route.post('/login', 'AuthController.postLogin')

And this is my Config auth

'use strict'

const Config = use('Config')

module.exports = {

  /*
  |--------------------------------------------------------------------------
  | Authenticator
  |--------------------------------------------------------------------------
  |
  | Authenticator is a combination of HTTP Authentication scheme and the
  | serializer to be used for retrieving users. Below is the default
  | authenticator to be used for every request.
  |
  | Available Schemes - basic, session, jwt, api
  | Available Serializers - Lucid, Database
  |
  */
  authenticator: 'jwt',

  /*
  |--------------------------------------------------------------------------
  | Session Authenticator
  |--------------------------------------------------------------------------
  |
  | Session authenticator will make use of sessions to maintain the login
  | state for a given user.
  |
  */
  session: {
    serializer: 'Lucid',
    model: 'App/Model/User',
    scheme: 'session',
    uid: 'email',
    password: 'password'
  },

  /*
  |--------------------------------------------------------------------------
  | Basic Auth Authenticator
  |--------------------------------------------------------------------------
  |
  | Basic Authentication works on Http Basic auth header.
  |
  */
  basic: {
    serializer: 'Lucid',
    model: 'App/Model/User',
    scheme: 'basic',
    uid: 'email',
    password: 'password'
  },

  /*
  |--------------------------------------------------------------------------
  | JWT Authenticator
  |--------------------------------------------------------------------------
  |
  | Jwt authentication works with a payload sent with every request under
  | Http Authorization header.
  |
  */
  jwt: {
    serializer: 'Lucid',
    model: 'App/Model/User',
    scheme: 'jwt',
    uid: 'mobile',
    password: 'password',
    secret: Config.get('app.appKey'),
    options: {
      // algorithm: 'HS256'
    }
  },

  /*
  |--------------------------------------------------------------------------
  | API Authenticator
  |--------------------------------------------------------------------------
  |
  | Api authenticator authenticates are requests based on Authorization
  | header.
  |
  | Make sure to define relationships on User and Token model as defined
  | in documentation
  |
  */
  api: {
    serializer: 'Lucid',
    model: 'App/Model/Token',
    scheme: 'api'
  }

}

All 7 comments

I hope you would have formatted the issue properly. All I understand is that you are having CSRF token exception. Simply disable the csrf inside config/shield.js file

Also please create separate issue for each problem. It is hard for me to help you with everytime within a single issue.

Just my login at your controller code, there are more than single problem, take time to read the documentation first.

For example, in the below code, there is no need of calling auth.attempt and auth.validate. Since attempt method will validate the credentials.

const login    = yield request.auth.attempt(mobile, password)

    try {
      yield request.auth.validate(mobile, password)
    } catch (e) {
      response.unauthorized({error: e.message})
    }

@thetutlage Is right to disable csrf inside config/shield.js file. Cause I'm use it for backend also
and yes you right about auth.attempt, I just was trying and testing sorry about that :)
Thank you so much for answering.
I'm so happy with your framework, Thank so much.

CSRF tokens are not meant for API servers. Since you are writing API it is fine to disable it.

But if I disable it how I can check the token for backend website. and what about request.authUser.

and sorry to ask something about that, but i know that token is made for wb services also so how i can use it to protect my web services.

And so sorry for my bad English :)

As I said, please created separate issues for each concern. Also you can discuss common problems or hurdles inside the gitter channel. https://gitter.im/adonisjs/adonis-framework

Closing the issue, since it's not constructive

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

umaams picture umaams  路  3Comments

themodernpk picture themodernpk  路  3Comments

douglaszaltron picture douglaszaltron  路  3Comments

devcaststudio picture devcaststudio  路  3Comments

dezashibi picture dezashibi  路  4Comments