Git Product home page Git Product logo

oc-jwtauth's Introduction

JWT Auth API

JSON Web Token Authentication for your OctoberCMS API integrated with RainLab.User

This plugin provides token based authentication to your application. Is based on the awesome package JSON Web Token Authentication for Laravel & Lumen by Sean Tymon.

Requirements

RainLab.User plugin

Installation

  1. [NOT REQUIRED ANY MORE] After plugin installation you need to copy /plugins/vdomah/jwtauth/config/auth.php to {root}/config/auth.php. If you want to change parameters values of auth.php you can use environment variables in .env (see "Environment options" section). {root}/config/auth.php is still supported and got priority highest then /plugins/vdomah/jwtauth/config/auth.php.

  2. Generate JWT Authentication Secret. It will be used to sign your tokens. You got 2 options:

    • generate using command line:
      php artisan jwt:generate
      
      You need to assign the generated value to JWT_SECRET in your .env.
    • go to Backend > Settings > JWTauth settings and click Generate Secret Key and save. This value has the highest priority and will override JWT_SECRET value from .env.

Endpoints

The plugin provides 4 endpoints:

  • /api/login

    Makes attempt to authenticate and returns token if succeeded. Also the basic user info is included in the response. By defult expects 2 parameters to receive: email and password.

  • /api/signup

    Tries to create a user and returns token if succeeded. The user info is included in the response. By default expects 3 parameters to receive: email, password and password_confirmation.

  • /api/refresh

    Tries to refresh the token and return the new token. By default expects 1 parameter: token.

  • /api/invalidate

    Tries to invalidate the given token - this can be used as an extra precaution to log the user out. By default expects 1 parameter: token.

Environment options

You're free to define any of this option in your project root .env.

JWT config

Variable Default
JWT_SECRET
JWT_TTL 60
JWT_REFRESH_TTL 20160
JWT_ALGO HS256
JWT_USER_CLASS RainLab\User\Models\User
JWT_IDENTIFIER id
JWT_BLACKLIST_ENABLED true
JWT_PROVIDERS_USER Tymon\JWTAuth\Providers\User\EloquentUserAdapter
JWT_PROVIDERS_JWT Tymon\JWTAuth\Providers\JWT\NamshiAdapter
JWT_PROVIDERS_AUTH Tymon\JWTAuth\Providers\Auth\IlluminateAuthAdapter
JWT_PROVIDERS_STORAGE Tymon\JWTAuth\Providers\Storage\IlluminateCacheAdapter

Laravel auth config

Variable Default
AUTH_DEFAULT_GUARD web
AUTH_DEFAULT_PASSWORDS users
AUTH_GUARDS_WEB_DRIVER session
AUTH_GUARDS_WEB_PROVIDER users
AUTH_GUARDS_API_DRIVER token
AUTH_GUARDS_API_PROVIDER users
AUTH_PROVIDERS_USERS_DRIVER eloquent
AUTH_PROVIDERS_USERS_MODEL \RainLab\User\Models\User
AUTH_PASSWORDS_USERS_PROVIDER users
AUTH_PASSWORDS_USERS_EMAIL auth.emails.password
AUTH_PASSWORDS_USERS_TABLE password_resets
AUTH_PASSWORDS_USERS_EXPIRE 60

Extending

How to use this in another plugin?

Simply add ->middleware('\Tymon\JWTAuth\Middleware\GetUserFromToken') to the end of the route in the plugin's routes.php

eg:

Route::post('test', function (\Request $request) {
   return response()->json(('The test was successful'));
})->middleware('\Tymon\JWTAuth\Middleware\GetUserFromToken');

Then when making the request set the header "Authorization" to "Bearer {yourToken}"

How to define own set of user attributes in response?

For sign up and sign in add corresponding methods getAuthApiSignupAttributes or/and getAuthApiSigninAttributes to User model by extending it in your plugin's boot method:

    User::extend(function($model) {
        $model->addDynamicMethod('getAuthApiSignupAttributes', function () use ($model) {
            return [
                'my-attr' => $model->my_attr,
            ];
        });
    });

oc-jwtauth's People

Contributors

bogandix avatar dleee avatar feber avatar jonoirwinrsa avatar vdomah 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

Watchers

 avatar  avatar  avatar

oc-jwtauth's Issues

Auth guard is not defined.

I have a fresh install octobercms with Octobro/Api and was looking for a good oAuth plugin.
Unfortanetly I am getting the error Auth guard is not defined when I'm trying to login.
I am creating a login request with Postman POST request and have submitted my fields in the form-data body.

Also, can I create a user for the API only? Right now it is mixing with my customers users but I would like to restrict the API user(s) or group to the API only.

Class jwt.auth does not exist

  1. I have installed jwtauth plugin from october cms
  2. Copied auth.php to root /config
  3. In my own plugin, I have added routes.php with:
    Route::post('api/test', function (\Request $request) {})->middleware('jwt.auth');

I am getting error:
Class jwt.auth does not exist
\vendor\laravel\framework\src\Illuminate\Container\Container.php

It works fine when I replace it with the value from jwtauth/plugin.php boot():
// $this->app['router']->middleware('jwt.auth', '\Tymon\JWTAuth\Middleware\GetUserFromToken');
...->middleware('\Tymon\JWTAuth\Middleware\GetUserFromToken');

Any ideas?

{ "error": "token_not_provided" } with OC v2

I managed to login and get a token but can't do anything else,

with this from the readme in my routes.php

Route::get('test', function (\Request $request) {
                    return response()->json(('The test was successful'));
                 })->middleware('\Tymon\JWTAuth\Middleware\GetUserFromToken');

sending the Bearer token with postman and receiving this

{
    "error": "token_not_provided"
}

any idea what I am missing?

Missing argument for AuthManager::createDriver(),

Hi, I updated October to Build 431 and tried to install the plugin.
I copied the auth.php file into config/ but it doesn't seems to work.

Missing argument 1 for Illuminate\Auth\AuthManager::createDriver(), 
called in {root}/vendor/laravel/framework/src/Illuminate/Support/Manager.php on line 87 
and defined

{root}/vendor/laravel/framework/src/Illuminate/Auth/AuthManager.php line 16

Auth crashing because of different declarations of $rememberTokenName

Actually, I don't know if this is the right place to post this error (I'll put it to the october core repo as well).

Anyhow, trying to do the authentication with the current OctoberCMS version through JWT will result into the following error:

[Fri May 17 16:51:35.315766 2019] [fcgid:warn] [pid 18049] [client 24.134.39.209:60808] mod_fcgid: stderr: PHP Fatal error: October\\Rain\\Auth\\Models\\User and Illuminate\\Auth\\Authenticatable define the same property ($rememberTokenName) in the composition of Vdomah\\JWTAuth\\Models\\User. However, the definition differs and is considered incompatible. Class was composed in /var/www/vhosts/test/htdocs/test/plugins/vdomah/jwtauth/models/User.php on line 5

What I found out was that the concurrent declarations will be found here, in the vendor directory of the OctoberCMS root folder:

vendor/october/rain/src/Auth/Models/User.php: protected $rememberTokenName = 'persist_code'; vendor/october/rain/src/Auth/Models/User.php: return $this->rememberTokenName; vendor/laravel/framework/src/Illuminate/Auth/Authenticatable.php: protected $rememberTokenName = 'remember_token'; vendor/laravel/framework/src/Illuminate/Auth/Authenticatable.php: return $this->rememberTokenName;

After changing it to "persist_code" there is no problem with authenticating anymore.

Does anyone else have that problem as well here? Or found a solution without modifying the vendor files?

php artisan jwt:generate not working

Hy I am having this error when i run php artisan jwt:generate

In BoundMethod.php line 147:

Method Tymon\JWTAuth\Commands\JWTGenerateCommand::handle() does not exist

Thanks

$isHidden causing an error

When I try and use the CMS tab in October, I get this error.

Undefined property: Tymon\JWTAuth\Middleware\GetUserFromToken::$isHidden
/$my_path/modules/cms/widgets/ComponentList.php line 101

How do I change the error key and value?

Is there a possibility of changing the error key and message from the controller because I have to follow some certain format when returning a response body from the client?

Login other than email

Hi is there a way to login using username and password , when i did it
it threw this error
{
"errors": {
"root": "Could not sign you in with those details."
}
}

add others data in the reponse

Hello,

there is a way to add other data like user role in the header response , i know that i can modify directly the file route.php and add to
$user = [ 'id' => $userModel->id, 'name' => $userModel->name, 'surname' => $userModel->surname, 'username' => $userModel->username, 'email' => $userModel->email, 'is_activated' => $userModel->is_activated, ];

there is a way to extend this file , thans

500 error on /api/login

October build - 427
User plugin version - 1.4.3

from october event log
Illuminate\Contracts\Container\BindingResolutionException: Unresolvable dependency resolving [Parameter #0 [ <required> $app ]] in class Illuminate\Auth\AuthManager in /Users/andrew/work/ocblog/vendor/laravel/framework/src/Illuminate/Container/Container.php:933

Can we use Backend user and Rainlab user both?

Hi,

Thank you for this wonderful plugin.

My application required a rest API for frontend and backend users. This plugin provides functionality for frontend user but the same thing can be used for Backend user?

Thanks.

Middleware \Tymon\JWTAuth\Middleware\GetUserFromToken not working

I use the following code on my own plugin:

Route::post('test', function (\Request $request) {
   return response()->json(('The test was successful'));
})->middleware('\Tymon\JWTAuth\Middleware\GetUserFromToken');

But when I post something to this route, it always return the status 503 Service Unavailable, and I tested \Tymon\JWTAuth\Middleware\GetUserFromToken::handle() that is never called

but when I change Route::post to Route::get, \Tymon\JWTAuth\Middleware\GetUserFromToken::handle() will call successful.

Any idea for this situation? Thanks

change secret

Did I miss something or should we change the 'secret' in jwthauth/config/config.php?
If yes, that would be important to write into the installation file. Or ideally be done by the plugin registration method.

JWTAuth not found

just fresh install octobercms 2.2.22 and php artisan plugin:install Rainlab.User, php artisan plugin:install Vdomah.Jwtauth got and error like: Class 'Tymon\JWTAuth\JWTAuth' not found

How to retrieve the User session after login

Hi,
How to retrieve the User session after login?
I am building API using this plugin to handle the authentication.
How do I get the logged user session?
I tried the usual

$user = Auth::getUser();

but it does not work

thanks

Always get invalid_credentials

I've followed the plugin instructions and configured the settings.

Schermata 2020-08-17 alle 11 44 52

When i try to login using cURL i always get invalid_credentials, even if's all double checked:

curl --request POST --header "Content-Type: application/json" --data '{email:"my_email_address",password:"my_password"}' https://my_server_url/api/login
{"error":"invalid_credentials"}

Is there something i'm missing?
Thanks in advance.

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.