Git Product home page Git Product logo

auth's Introduction

@adonisjs/auth


gh-workflow-image npm-image license-image

Introduction

Official Documentation

The documentation is available on the AdonisJS website

Contributing

One of the primary goals of AdonisJS is to have a vibrant community of users and contributors who believes in the principles of the framework.

We encourage you to read the contribution guide before contributing to the framework.

Code of Conduct

In order to ensure that the AdonisJS community is welcoming to all, please review and abide by the Code of Conduct.

License

AdonisJS auth is open-sourced software licensed under the MIT license.

auth's People

Contributors

allanmaral avatar bjornarhagen avatar cannap avatar consoletvs avatar dependabot[bot] avatar draftproducts avatar ericmp33 avatar greenkeeper[bot] avatar jotaajunior avatar julien-r44 avatar lecoupa avatar liam-p-idhl avatar lookingit avatar orcuntuna avatar parker-codes avatar radmen avatar romainlanz avatar rubenmoya avatar starr0stealer avatar targos avatar techlab23 avatar temasm avatar thetutlage avatar xstoudi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

auth's Issues

An in-range update of semver is breaking the build 🚨

Version 5.4.0 of semver just got published.

Branch Build failing 🚨
Dependency semver
Current Version 5.3.0
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

As semver is β€œonly” a devDependency of this project it might not break production or downstream projects, but β€œonly” your build or test tools – preventing new deploys or publishes.

I recommend you give this issue a high priority. I’m sure you can resolve this πŸ’ͺ

Status Details
  • ❌ continuous-integration/travis-ci/push The Travis CI build is in progress Details
  • ❌ continuous-integration/appveyor/branch AppVeyor build failed Details
  • ❌ coverage/coveralls Coverage pending from Coveralls.io Details

Commits

The new version differs by 16 commits.

  • e1c49c8 v5.4.0
  • 3ebc11d more test coverage
  • 5b30513 speed up tests a lot, add coverage
  • e1668ce add top level intersects function
  • 6cb2bcb intersection: use semver.version, not semver.raw
  • 4bacbfa Make exposed apis more clear
  • 8b86a26 Reduce line length and remove unused platform parameter
  • 99f133e Add range and comparator intersection docs to README
  • afbe8ca Move methods to comparator and range
  • 67c9ed7 Add support for range and comparators comparison
  • caeeac4 remove 0.x from Travis, cache npm stuff, use containers
  • bdda1a4 Add Node.js 8 to .travis.yml
  • 8fff305 Add node 6 to travis
  • aaba710 Added syntax highlighting to readme example
  • 32802c5 minimize heap allocations for maxSatisfying/minSatisfying

There are 16 commits in total.

See the full diff

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

Multiple Auth like in laravel 5.3

Does adonisjs have multiple auth like in laravel 5.3 ?
multiple auth its mean can use not only user table / model

for example:
use for employee table and customer table

Thanks

revokeAll(user) revoking all tokens of all users

Hello folks.

Basically the title explains everything. I'm using it that way:

const user = yield User.query().where({ username }).first()
yield request.auth.revokeAll(user)

And when I check in sqlite, all tokens, of all users, have been revoked, not only the tokens of the current queried user.

I'm using the code below instead of revokeAll:
yield Token.query().where({ 'user_id': user.id }).update({ 'is_revoked': true })

Am I using revokeAll wrong or it's a bug?

Context.onReady is not a function

With the newest release, there seems to be a problem on startup. When I try to run the server it throws me the following error TypeError: Context.onReady is not a function. This even occurs when I don't define a Middleware on any routes.
at AuthProvider.boot (M:\Dev\Server\node_modules@adonisjs\auth\providers\AuthProvider.js:140:13)

Auth/Model example.

Hi,

I'm new to Adonis and looking for an example of how to use JWT auth with Adonis 4x. I can see in the docs that I need to define a User model when using Lucid. I'm not sure how to represent the User model as the password hash function is implemented within the database, therefore I need to execute a raw query to call this function rather than just selecting from the table. In addition, passwords have expiry dates - how would I represent to the auth middleware that as well as checking that the email and hashed password match against a User, the password must also have not expired.

Thanks a lot.

Api Token Scheme

Should be the Personal Api Token Scheme be referring to the one said on the API Docs:

The personal API tokens become popular by Github (https://github.com/blog/1509-personal-api-tokens), to use a token for automated scripts, where it is not possible to manually type the email and password every time.

config/auth.js

authenticator: 'api',
api: {
  serializer: 'lucid',
  scheme: 'api',
  model: 'App/Models/User'
},

Then I created the api_token for my test user which is in tokens

{ user_id: user.id, type: 'api_token', token: '123456', is_revoked: false }

But when I tried to access it using Postman;

GET /test HTTP/1.1
Host: 127.0.0.1:3333
Authorization: Bearer 123456
Cache-Control: no-cache
Postman-Token: c82707aa-6a50-1b50-44b5-2ff30059e8ed

It returns 401 Unauthorized

E_INVALID_API_TOKEN: The api token is missing or invalid

I am not using JWT or such so, something wrong in the docs or I miss-understood it completely? or can someone tell me how to extend @adonisjs/auth so we can create something like a Token scheme? or a simple config like encrypted: false at config/auth.js:api just to have a flag disable the Encryption.decrypt

Provider should expose the currentUser in every request ( stateful authentication only )

@RomainLanz commented on Fri May 20 2016

Hi there !

I have a weird problem with a condition in my view to display different content when I user is logged in or not.

So I'm using the authUser variable which is send by default to any views.
I have got in my navbar partials a condition to display the Login / Register button or user information.

<div id="nav-bar-right">
  {% if authUser %}
    <div class="nav-bar-user">
      <!-- ... -->
    </div>

    <div class="nav-bar-separator"></div>

    <div class="nav-bar-actions">
      <!-- -->
    </div>
  {% else %}
    <div class="nav-bar-login">
      <p><a href="#" @click.prevent="showLoginModal">Connexion</a> / <a href="#" @click.prevent="showRegisterModal">Inscription</a></p>
    </div>
  {% endif %}
</div>

This is working perfectly (I have only tested it when I'm not logged in).

I also have a condition to display modal when you're not logged in. You can find the code below.

{% if not authUser %}
  {% include 'frontend.modals.login' %}
  {% include 'frontend.modals.register' %}
{% endif %}

This doesn't work. I have also try some "hacks" to make it works but nothing happens.

{% if authUser %}
  {% include 'frontend.modals.login' %}
  {% include 'frontend.modals.register' %}
{% endif %}

{% if not authUser %}
  {% include 'frontend.modals.login' %}
  {% include 'frontend.modals.register' %}
{% else %}
  {% include 'frontend.modals.login' %}
  {% include 'frontend.modals.register' %}
{% endif %}

Both example under display nothing. I have tried to display the variable authUser in my view to see his content. So I have put {{ authUser | json }} before the two conditions. Nothing is display.


@RomainLanz commented on Sun May 22 2016

I come back to give you updates.

So I have finish my login/register function and the if / else in the navbar doesn't work either (it always display the else content.

authUser seems always empty (not null).

The code to auth my user that you can see below works perfectly:

* store(request, response) {
  const username = request.input('username')
  const password = request.input('password')

  try {
    const user = yield request.auth.attempt(username, password)
  } catch(e) {
    if (request.ajax) {
      return response.status(400).send({ error: true })
    }

    yield request.withOut('password').andWith({ error: true }).flash()
  }

  return response.redirect('back')
}

@thetutlage commented on Sun May 22 2016

@RomainLanz authUser is only to the views by the named auth middleware.

Route.get('/profile', 'UserController.profile').middleware('auth')

Also make sure to update the adonis-auth package from github, coz I added this global around a week ago and may be your app has the old version


@thetutlage commented on Sun May 22 2016

Reference from the conversation on Gitter

Stateless and stateful authentication will have a little difference in how you access the user from your controllers and views.

Stateful Authentication will have the access to a variable called currentUser on each request and view after the user has loggedIn

Whereas Stateless authentication like JWT and API will have access to the variable called auth on the request object. There will be no view's global for stateless auth, since creating a view with JWT in place is not expected.


@niallobrien commented on Wed May 25 2016

When can we expect this to be implemented? Thanks.

Cannot switch between authenticator Adonis 4(dawn)

Hi,
I'm using Adonis 4 (dawn).

In config/auth.js i set

authenticator: 'session'

but, if i set an api route like that:

Route.get('/api/foo', 'APIController.foo').middleware(['auth:jwt'])

The auth is anyway set to session: indeed, if i login in "session mode", i can use that api even not set Authorization: Bearer header.

Instead, if i switch in config/auth.js

authenticator: 'jwt'

Even after setting middleware('auth:session'), auth always use jwt token to authenticate.

Thank you

capitalize jwt token type

Is there a reason the generated token type is lowercase? I'm trying to set the header as jwt.type + jwt.token (jwt representing the generated token from auth.generate), but the approach doesn't work since jwt.type is bearer rather than Bearer.

plans to add CAS or LDAP auth?

I was wondering if you have plans to add CAS (2.0, 3.0 and SAML) and possibly LDAP auth to adonis-auth.

Awesome work on Adonis!

How login user with Relations?

My User model has id, name and permissions as Relations

const user = yield User
  .query()
  .with('permissions') 
  .fetch()
{
  "id": 1,
  "name": "Alex"
  "permissions": [/* ... */]
}

But after login request.currentUser has no permissions property. How create currentUser object with Relations? For example:

request.auth.loginViaId(id).with('permissions') 

An in-range update of mocha is breaking the build 🚨

Version 3.5.0 of mocha just got published.

Branch Build failing 🚨
Dependency mocha
Current Version 3.4.2
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

As mocha is β€œonly” a devDependency of this project it might not break production or downstream projects, but β€œonly” your build or test tools – preventing new deploys or publishes.

I recommend you give this issue a high priority. I’m sure you can resolve this πŸ’ͺ

Status Details
  • ❌ continuous-integration/appveyor/branch AppVeyor build failed Details
  • βœ… continuous-integration/travis-ci/push The Travis CI build passed Details
  • βœ… coverage/coveralls First build on greenkeeper/mocha-3.5.0 at 97.697% Details

Release Notes free-as-in-freezing

3.5.0 / 2017-07-31

πŸ“° News

  • Mocha now has a code of conduct (thanks @kungapal!).
  • Old issues and PRs are now being marked "stale" by Probot's "Stale" plugin. If an issue is marked as such, and you would like to see it remain open, simply add a new comment to the ticket or PR.
  • WARNING: Support for non-ES5-compliant environments will be dropped starting with version 4.0.0 of Mocha!

πŸ”’ Security Fixes

πŸŽ‰ Enhancements

  • #2696: Add --forbid-only and --forbid-pending flags. Use these in CI or hooks to ensure tests aren't accidentally being skipped! (@charlierudolph)
  • #2813: Support Node.js 8's --napi-modules flag (@jupp0r)

πŸ”© Other

Commits

The new version differs by 34 commits.

  • 82d879f Release v3.5.0
  • bf687ce update mocha.js for v3.5.0
  • ec73c9a update date for release of v3.5.0 in CHANGELOG [ci skip]
  • 1ba2cfc update CHANGELOG.md for v3.5.0 [ci skip]
  • 065e14e remove custom install script from travis (no longer needed)
  • 4e87046 update karma-sauce-launcher URL for npm@5
  • 6886ccc increase timeout for slow-grepping test
  • 2408d90 Make dependencies use older version of readable-stream to work around incompatibilities introduced by 2.3.0 on June 19th
  • 68a1466 Try not clearing the env for debug in the integration test and see if that fixes Node 0.10 on AppVeyor; if need be, some other fix/workaround can be applied to handle whatever was up with debug without causing this issue
  • 958fbb4 Update new tests to work in browser per test hierarchy reorganization
  • 1df7c94 Merge pull request #2704 from seppevs/increase_test_coverage_of_mocha_js
  • 1f270cd Stop timing out (#2889)
  • 27c7496 upgrade to [email protected]; closes #2859 (#2860)
  • 50fc47d fix CI; closes #2867 (#2868)
  • 1b1377c Add test for ignoreLeaks and fix descriptions

There are 34 commits in total.

See the full diff

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

Tutorial about adding Oauth?

I would like to build apps with Adonis.js that feature "Login with Linkedin" or "Login with Spotify".

Is there a tutorial out there to help developers build oauth applications with Adonis? What are the steps involved?

Thank you!

PS
I followed the Auth0 tutorial by @unicodeveloper and it was very helpful with adding email/password auth. Now wondering about social login

Multiple Auth for same Authentication Scheme

Is it possible to use same authentication scheme like session and have separate auth with multiple tables, for example for admin section and customer section. Or could it be session for admin and jwt for customer section?

Authentication

@dubcanada commented on Wed Feb 24 2016

Hello,

I am in need of the Authentication provider, so I figured rather then just build one for myself I would build it and contribute it back. I was reading the Trello card for the Authentication https://trello.com/c/wns5DzT3/28-authentication-provider

Are you wanting to separate it out into it's own repo like you did with the mail provider https://github.com/adonisjs/adonis-mail ? I plan on copying that to start with as that has your driver structure done.

I'm going to start tomorrow, so I'll probably send a pr before the end of this week. At least for basic/session, JWT may take a bit more as I don't need that atm.

Thanks!


@thetutlage commented on Wed Feb 24 2016

@dubcanada Nice, it will be great to have initial authentication system for Adonis. I am not sure if i would be able to make it the official Auth provider, because the actual one i have in my mind is quite complex. Here is a brief.

  1. Authentication system will have UserProviders, whose job will be to validate credentials. Now these can be username,password or can be a token. UserProvider has no idea where the credentials will come from.
  2. There will be multiple schemes like session, basic-auth. Now these scheme knows where to look for credentials.
  3. Finally there will a driver which will read credentials from schemes and will validate them with the UserProviders.

Also there will be mechanism for guest logins, which means you can dummy login visitors and once they signup, you can simply join their guest tokens with their user profile. It will be helpful to know what a visitor did before becoming a user.

Obviously you are not bound to implement all these things. But it will be great if you can come up with a normal authentication provider to help others until i come up with the fully fledged one.


@dubcanada commented on Tue Mar 01 2016

I'll do a basic one for session and basic-auth drivers and leave it at that. I'll try and copy how you do things currently along with the Laravel auth provider and see how it turns out. Hopefully it will work until you do the larger version with JWT and such.


@thetutlage commented on Tue Mar 01 2016

πŸ‘

request.auth.attempt() returning error too soon

In the Authentication docs there is an example something like this:

    * login (request, response) {
        const email = request.input('email')
        const password = request.input('password')
        const login = yield request.auth.attempt(email, password)

        if (login) {
            response.route('profile')
            return
        }

        response.unauthorized('Invalid credentails')
    }

If the email or password is invalid an error comes back something like this:
PasswordMisMatchException: Password does not match

The attempt() method doesn't allow the rest of the code to continue once it fails / throws error. So response.unauthorized('Invalid credentails') never fires. Any ideas?

Pass Extra Payload to JWT attempt()?

After the work done in #13, should there not be an additional parameter added to JWT.attempt() to pass an optional user payload object since it uses generate() inside?

I can send a PR over for this, but just want to make sure I'm not missing/misunderstanding about attempt() before I do.

auth:setup doesn't provides user hook

Hello, just played with auth and noticed a lack of User Hook, for encripting password.
If it's not there passwords are saved without hasing.. and when trying to validate it gives an error.
I havent found how to disable these, so i think it would be better to provide user hook with user model on auth:setup

JWT auth with attempt method

I need to validate the user email and password, and if they are valid I want to send the JWT token, but the method "request.auth.attempt(email, password)" not working with JWT schema, there is a built way to do this, or I need to implement the logic myself?

InvalidLoginException (401) Login Failure

Hi,

I try to implement basic auth.

config/auth.js :

  authenticator: 'basic',
  basic: {
    serializer: 'Lucid',
    model: 'App/Model/User',
    scheme: 'basic',
    uid: 'tel',
    password: 'code'
  },

routes.js :

Route.get('/profile', 'UserController.profile').middleware('auth:basic')

I have a "InvalidLoginException (401) Login Failure". I use Postman with "Basic Auth" option.

Any ideas ?

Thanks for your help.

Refresh tokens issue in scheme jwt with custom foreign keys

So, when I try to refresh an user token show a query exception:
error: column tokens.userid does not exist
Method try to access userid (all in lowercase) in tokens table, but the correct is userId.
This error show only in generateForRefreshToken.

Code example bellow.

//Model definition
class User extends Model {
  static boot () {
    super.boot()
    this.addHook('beforeCreate', 'User.hashPassword')
 }
  tokens () {
    return this.hasMany('App/Models/Token', 'id', 'userId')
  }
}

//controller
async refreshToken ({ request, auth }) {
    const refreshToken = request.header('x-refresh-token')
    return await auth.generateForRefreshToken(refreshToken) 
}

Get user without request object

I need the user in multiple models. In Laraval I can do this with

$user = Auth::user();

Is there something similar in AdonisJS or exists a way to get the authenticated user without access to the request object.

An in-range update of jsonwebtoken is breaking the build 🚨

Version 7.4.2 of jsonwebtoken just got published.

Branch Build failing 🚨
Dependency jsonwebtoken
Current Version 7.4.1
Type dependency

This version is covered by your current version range and after updating it in your project the build failed.

jsonwebtoken is a direct dependency of this project this is very likely breaking your project right now. If other packages depend on you it’s very likely also breaking them.
I recommend you give this issue a very high priority. I’m sure you can resolve this πŸ’ͺ

Status Details
  • ❌ continuous-integration/travis-ci/push The Travis CI build is in progress Details
  • ❌ continuous-integration/appveyor/branch AppVeyor build failed Details

Commits

The new version differs by 12 commits.

  • e56f904 update changelog
  • 480bb9b 7.4.2
  • c6a7026 Merge pull request #374 from ziluvatar/add-check-for-empty-secrets
  • c584d1c sign: add check to be sure secret has a value
  • 43739dc Merge pull request #371 from ziluvatar/docs-about-refreshing-tokens
  • 016fc10 docs: about refreshing tokens
  • 5f44a86 Merge pull request #365 from ziluvatar/information-regarding-base64-secrets
  • c25e990 docs: verifying with base64 encoded secrets
  • 2f36063 Merge pull request #360 from ziluvatar/add-ecdsa-tests
  • 00086c2 document keyid as option (#361)
  • 89900ea Add tests for ES256
  • 27a7f1d readme: Using private key with passpharase (#353)

See the full diff

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

JWT Auth Token Never Expired

I have added the expiresIn parameter to jwt but the generated token never expired.

auth.js:

jwt: {
    serializer: 'Lucid',
    model: 'App/Model/User',
    scheme: 'jwt',
    uid: 'email',
    password: 'password',
    expiresIn: '1',
    secret: Config.get('app.appKey')
	
  },

Authorization header:

Authorization=Bearer JWT_TOKEN

Is there any parameter I need to set to make it works?

Authetication required to access files?

Hi!

I was wondering if there is a simple way to protect the files on the server (e.g PDF).

By "protect" I mean that the user must be logged in order to access the file.

At the moment I've a simple Article model which contains a Title, Description and the PDF name. Then there is a controller which simply show these information with the embedded PDF, so the user can access view the PDF with foo.com/article/{id} and here I have the Auth middleware.

But it could also access it by foo.com/PDF_Name.pdf without authentication, and it's what I want to avoid.

Feature Request: Ability to serialize object into JWT Token Payload

I wanted to start this conversation here before offering a pull request. I want to see what the community thinks as well as project maintainers.

When using Adonis Auth with JWT, the sample code below only serializes the Entities Primary Key into the Payload.

const user = yield User.find(1)
const token = yield request.auth.generate(user)

Code: https://github.com/adonisjs/adonis-auth/blob/master/src/Schemes/Jwt/index.js#L93-L103

JWT Spec and the jsonwebtoken library support providing object literals into the payload. It would be very useful if Adonis Auth also supported this use-case. An example of practical use of this feature would be such as if you want to add the Users Profile object into the payload, so you don't need to make another API call for that information (or and it to the response itself).

Without this feature you have to work around it by adding the object into the response body (to avoid another Web I/O).

const profile = yield user.profile().fetch();
const token = yield request.auth.generate(user);
response.send({ token: token, profile: profile });

Many client side frameworks have built in support for JWT payloads, example Aurelia Auth, which has an API to get the JWT payload. If the payload had an object expected you wouldn't need to do any further processing to get the details of the Users Identity, or any special logic to store and maintain that information through the life of the session, which is something the framework is already doing with the payload.

Offering this feature is trivial, there are a few different ways I see how it could be done, but first would like to here others thoughts. If anyone wants to see sample change-sets in how this could be achieved I would be glad to provide and discuss further

Attempt method throws exception

Whenever auth.attempt is called for invalid state i.e. user not found or wrong password, the method will throw an exception. If the result of the method should return a boolean to represent whether or not the login attempt was successful, shouldn't the auth.attempt swallow the user not found and password mismatch errors thrown by the validate method?

Extending Auth Provider in Adonis 4

Hi,
i'm trying to extend auth provider to support mongoDB for authentication.
There is nothing about in the docs, but in 3.x docs yes.
In particular, 3.x docs says that i have to extend auth provider adding a Ioc.extend function in bootstrap/extend.js, but in 4.x there is no more bootstrap folder.
Where do i have to add the extend code?

Thank you

Auth type api, not found column

I'm catch error when try use auth type api.

select * from "users" where exists (select * from "tokens" where "token" is null and "type" = $1 and "is_revoked" = $2 and users.id = tokens.user_id) limit $3 - column "type" does not exist

My config/auth.js.

'use strict'

module.exports = {
  authenticator: 'api',

  api: {
    serializer: 'lucid',
    model: 'App/Models/System/User',
    scheme: 'api',
    uid: 'email',
    password: 'password',
    expiry: '30d',
    options: {
      secret: 'self::app.appKey'
    }
  }
}

Delete remember_me token on logout

The session scheme is just creating redundant remember_me tokens inside the table and set them to revoked on logout. Ideally these tokens are of no-use and must be deleted

two JWT schemes: Exception doesnt parse needed auth config

I have 2 types of users and auth systems respectfully: client lgged in by phone number and unique device id, and operator, who work on orders, received from clients. Operators should log in with email/password or maybe username/password. More classical. How can I define two JWT schemes? Or I should write my own implementation for one of schemes? (or copy from adonis auth middleware?

Cannot find module '../Middleware/AuthInit'

Error (500)
Cannot find module '../Middleware/AuthInit'

In node_modules/adonis-auth/providers/AuthManagerProvider.js on line 17:

const AuthInit = require('../Middleware/AuthInit') should be

const AuthInit = require('../middleware/AuthInit') and then it works ...

I am on linux Ubuntu, so files are case sensitive ...

Also on line 23 Middleware is upper cased ..

Password Does Not Match error

Hi,

I tried to do JWT, when running the validate command I get the above result.

In the DB, email is [email protected], password is 123456789 (unhashed)

Is the password supposed to be hashed in the database? If so, what is the hashing. The docs could improve on this as I spent a few hours trying to get this simple thing to work... but still failed...

Check for jwt in cookies

In certain circumstances it's easier to include a jwt as a cookie instead of a header.

What do you think?

Need possibility to switch hash algorithm in authorization

I connect authorization to my existing database with different hash logic of bcrypt (for example sha256 or md5... etc), but in adonis-auth use only Hash object with bcrypt algorithm. Can you make possibility to switch Hashes in authorization (Or some config in Hash object...)

https://github.com/adonisjs/adonis-auth/blob/8aa688685b7a3de35994a1c54b89fbb964cb3a72/src/Serializers/Lucid.js#L38-L40

https://github.com/adonisjs/adonis-auth/blob/8aa688685b7a3de35994a1c54b89fbb964cb3a72/src/Serializers/Lucid.js#L141-L146

Is it possible to have multiple authentication methods at once?

I've been reading the documentation on authentication methods. Is it possible to allow both session based authentication and API token authentication? It doesn't seem clear from the docs.

My idea is to have a webUI that uses session based authentication and a mobile app that uses token based authentication.

If I've missed some piece of documentation somewhere, please let me know. It seems like you can currently only select one however. Cheers!

Session not saved on redirect

I'm using a custom SAML login but it just wraps around the session auth driver. I am manually logging in the user with auth.login(user) in the SAML response, which appears to be working. However, when I attempt to redirect the user back to the home page, the session appears to be cleared out and immediately throws an InvalidSessionException (which I have configured with hooks to redirect back to the SAML login route). I have tried both cookie and redis session drivers with the same result.

Can you tell if I'm missing something?

app/Controllers/Http/AuthController.js

  async postLogin({ request, response, auth, session }) {
    let result = await Saml.parseLoginResponse(request)

    if (result.success) // look up or insert user
    {
      let user = await User.findBy('email', result.attributes.email)

      if (!user) // no record
      {
        Logger.info('Creating new user with email: ' + result.attributes.email)
        user = await User.create(Object.assign(result.attributes, { name_id: result.nameID }))
      }

      await auth.login(user)
      Logger.info(user.toJSON())
      Logger.info(session.all()) // this outputs { adonis-auth: 1 }
      Logger.info('Login success, redirecting to home page.')
    }
    else
      Logger.info('Login failed, redirecting to home page.')

    return response.redirect('/')
  }

start/hooks.js

hooks.after.providersBooted(() => {
  const Exception = use('Exception')
  const Logger = use('Logger')

  Exception.handle('InvalidSessionException', async (error, { request, response, session }) => {
    Logger.error(error)
    Logger.info(session.all()) // this is now missing { adonis-auth: 1 }

    // redirect to login
    return response.redirect('/sso/login', 301)
  })
})

Policy based authorization

I'm going to be starting on a project in 3 weeks, hopeing to use adonisjs. I was wondering if it is achievable to have policy based authorization on routes, controllers etc similar to Laravel.
https://laravel.com/docs/5.2/authorization

From looking at the docs I haven't seen anything to do with authorization. Im also new to node, so maybe if you could please point me to the right direction so I can try to implement it :)

Btw I love the framework!!

Characters in the token id generated is not equal to the varchar character limit in token table

@webreinvent commented on Fri Sep 23 2016

Here's what I did:

  1. ace auth:setup to setup authentication, it created migration as well which includes tokens table.
  2. Changed authenticator from authenticator: 'session', to authenticator: 'api',
  3. Used following code to generate token:
const user = yield User.find(1)
const token = yield request.auth.generate(user)

if I print this token it contains 121 characters while in tokens table, column token has only varchar(40) 40 characters.

Routes with middleware "auth:api" failed

When I try to visit the link http://127.0.0.1/v1/user/list it returns error. I suspect this is because the whereHas or somewhere returns the object .first() instead of the token value.

Below is my code.

config/auth

...
authentication: 'api',
api: {
  serializer: 'lucid',
  scheme: 'api',
  model: 'App/Models/User',
  uid: 'email',
  password: 'password'
},
...

start/routes.js

Route.get('list', 'UserController.list')
    .prefix('v1/user')
    .middleware('auth')

Postman

GET /v1/user/list HTTP/1.1
Host: 127.0.0.1:3333
Authorization: Bearer 23195646bc77407758817c9b9e9781ddccdd8d7289c23e32f0bddb4077e84c03cb2a90b188da244c8d2e63f03c63c0b5m2S1rNiGO98DdCEm804MzkLoWv2a1zIk0MGR599qrWc6kbGByE6tMyyFkVM+ubz3s06x3T0LRhip6zRSM5nNa59/bu3Bdr3MvK+8HM6YthpeRQ8DS1ki8Ik/kIWw/p1j8oEdNrgHb5bmpSPtqPZr2VjWRcdgwjtezOSNFvYTR05sGWs68wI+52NAa7uhkMM/MUXH7HpSOj/gRiSCemF1rHP5lRIik06h8ryHmp6choc=
Cache-Control: no-cache
Postman-Token: d78ccac9-b87d-2c22-c7b0-7a4dbe84bac9

Error

select * from `users` where exists (select * from `tokens` where `token` = {"id":49,"user_id":557,"token":"c84a46630f7243f78dee51e53eb00719","type":"api_token","is_revoked":0,"created_at":"2017-12-10 18:17:41","updated_at":"2017-12-10 18:17:41"} and `type` = 'api_token' and `is_revoked` = false and users.id = tokens.user_id) limit 1 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' `user_id` = 557, `token` = 'c84a46630f7243f78dee51e53eb00719', `type` = 'api_to' at line 1

Generate Token, in traits

async generateToken(type = 'api_token') {
    const token = uuid.v4().replace(/-/g, '')
    return await this.tokens().create({
      type: 'api_token',
      token: token,
      is_revoked: false
    })
  }

async getToken(type = 'api_token', encrypted = true, generate = false) {
    let token = await this.tokens()
      .where({ type, is_revoked: false })
      .first()

    if (token && generate === true) {
      token = await this.renewToken(type)
    }
    if (!token) {
      token = await this.generateToken(type)
    }

    if (encrypted) {
      return { type: 'bearer', token: Encryption.encrypt(token.token) }
    } else {
      return token
    }
  }

Update

I debug it a little more, i am not sure, but it is working again. first I tried auth.user = await user.getToken() to set the user, then it worked, then I removed it, its working, no mysql error. Do you have any ideas?

I will close this issue, but when it comes back, ill re-open and should point or submit PR on it.

Mongo serializer?

Hello! Does it possible to create a Mongo Serializer to use with Auth package? Or Does it possible to use Auth module without Serializer?

Thank you!

Enable client side hashing for any authentication

I would like a way to verify the user's password which was hashed on the client-side with the same hashing library (bcryptjs).

The BaseScheme's * validate (uid, password, returnUser) method may check if the provided password is the same as the uid related user's before hashing it.

Custom API for authentication

Hey,
how would i use my existing api for logging in? I'm currently using an API based on nodejs and mongodb.
The API works but I don't know how to integrate it the best way

Example for creating auth in Adonis 4?

One of the reasons I was initially attracted to adonis was that generating authentication was as easy as one command. Now that seems to be broken! Is there an example of an Adonis 4 app with authentication?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.