Git Product home page Git Product logo

wn-jwtauth-plugin's Introduction

Introduction

This plugin provides a JSON Web Tokens authentication mechanism for Winter CMS integrated with Winter.User. It's essential for your web application built with Angular, Vue.js, React or other modern Javascript frameworks.

Requirements

Theme

Tutorials

Installation

$ composer require rluders/jwtauth

Configuration

You must set a secret token for your application. Do do it, on Winter's Backend access: Settings > Users > JWTAuth

Usage

Here's the list of available endpoints for this plugin.

If you are using Postman, you can click here to import the collection with all the calls that you need to test it.

Login

POST /api/auth/login

Route name

api.auth.login

Parameters

Name Type Required Description
login string Yes Account login attribute
password string Yes Account password

The field login value can be the account email or username. You can select it on Winter.User configuration what field should be used for login.

Responses

SUCCESS

Code: 200

{
  "token": string,
  "user": object
}

ERROR

Code: 401

{
  "error":
    invalid_credentials |
    could_not_create_token |
    user_inactive |
    user_is_banned
}

Register

POST /api/auth/register

Route name

api.auth.register

Parameters

Name Type Required Description
username string No Account username
email string Yes Account email
password string Yes Account password
password_confirmation string No Confirm the new password

The field username can be required. It depends of your Winter.User configuration.

Responses

SUCCESS

Code: 201

[]

ERROR

Code: 401

{
  "error": object | registration_disabled
}

Supported events

  • Winter.User.beforeRegister
  • Winter.User.register

Account Activation

POST /api/auth/account-activation

Route name

api.auth.account-activation

Parameters

Name Type Required Description
activation_code string Yes Account activation code

Responses

SUCCESS

Code: 200

[]

ERROR

Code: 422

{
  "error": invalid_activation_code | invalid_user | user_not_found
}

Forgot Password

POST /api/auth/forgot-password

Route name

api.auth.forgot-password

Parameters

Name Type Required Description
email string Yes Account email

Responses

SUCCESS

Code: 200

[]

ERROR

Code: 404

{
  "error": user_not_found
}

Reset Password

POST /api/auth/reset-password

Route name

api.auth.reset-password

Parameters

Name Type Required Description
reset_password_code string Yes Reset password code
password string Yes Account new password
password_confirmation string No Confirm the new password

Responses

SUCCESS

Code: 200

[]

ERROR

Code: 422

{
  "error":
    invalid_reset_password_code | invalid_user | invalid_reset_password_code
}

Refresh Token

POST /api/auth/refresh-token

Route name

auth.api.refresh-token

Parameters

Name Type Required Description
token string Yes Valid user JWToken

Responses

SUCCESS

Code: 200

{
  "token": string
}

ERROR

Code: 403

{
  "error": could_not_refresh_token | given_token_was_blacklisted
}

Get User

GET /api/auth/me

Middleware

jwt.auth

Route name

api.auth.me

Parameters

Name Type Required Description
token string Yes Valid token

Responses

SUCCESS

Code: 200

{
  "user": object
}

ERROR

Code: 404

{
  "error": user_not_found
}

Known issues

Beside the fact that I'm always trying to solve the possible issues, bad things could happen. Here, an list of possible issues and how to fix it.

Note to Apache users

In order to use the authorization Bearer Token you must add the following code to your .httaccess

RewriteEngine On
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]

License

GPLv3

wn-jwtauth-plugin's People

Contributors

anotterdev avatar athov avatar bernardotavares avatar bkrajendra avatar boxybird avatar bugzbrown avatar cch504 avatar dinver avatar incremental92 avatar josephcrowell avatar khorashadi666 avatar omidmm16 avatar rluders avatar su5ed avatar vittoboa 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

Watchers

 avatar  avatar  avatar  avatar  avatar

wn-jwtauth-plugin's Issues

Registration Endpoint 422 Unprocessable Entity

HTML is being return when there is a validation error. The JSON error is there as well, but the presents of the HTML creates a parsing issue. Any thoughts to what I can be doing wrong?

422

Support to Winter CMS 1.2 with Laravel 9

Now that Winter CMS 1.2 now supports Laravel 9, and tymon/jwt-auth seems to be totally abandoned, we need to replace it with php-open-source-saver/jwt-auth that is a fork from the tymon's librabry but with support to Laravel 9.

If you are using Winter CMS 1.2 and having issues with the plugin let me know on this issue, 'cause this could be the main reason.

Check package dependencies and upgrade if necessary

The package is using the tymon/jwt-auth version 1.0.0-rc.1 maybe we could update it to 1.0.0-rc.4.1.

Is it compatible with OctoberCMS?
Why we don't have a stable version for 1.0.0? But, we already have a 2.0.0 in development.

error 401 for route api/auth/me

The login part seems to be working, my vuejs app receives a token then try to access the route api/auth/me but receives a 401 No token provided

When I look at the API response, I can see that the header is containing the token as such:
this is the javascript log of the 401 error returned by the API:

config:
...
  data: undefined
  headers:
    Accept: "application/json, text/plain, */*"
    Authorization: "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9vYy1kcm9uZXQubG9jYWxcL2FwaVwvYXV0aFwvbG9naW4iLCJpYXQiOjE1ODg5MTkwMDEsImV4cCI6MTU4ODkyMjYwMSwibmJmIjoxNTg4OTE5MDAxLCJqdGkiOiJreFRQMVhSQkNwWEtITDdSIiwic3ViIjoxLCJwcnYiOiI0MTFjOTE3YTBmYjUxZTBhNDI3YTdlM2RlYWE1YTQ5ZTI5MmRkYjliIn0.vSWvZbrntyRNl-3Zy3XzBk-yZhCswpNFGW3Jwjjcdbs"
    X-Requested-With: "XMLHttpRequest"
    __proto__: Object
    maxContentLength: -1
    method: "get"
    timeout: 0
...
    url: "api/auth/me"
...
  data: ""Token not provided" on line 52 of /Users/christ/Sites/oc-dronet/plugins/rluders/jwtauth/vendor/tymon/jwt-auth/src/Http/Middleware/BaseMiddleware.php"
...
  status: 401
  statusText: "Unauthorized"

Overwrite activation url with custom plugin

Hi,
I'm trying to overwrite the activation and password reset urls so I can customize these per installation in an .env file for example.

So far I have a custom plugin in which I have this in the Plugin.php file.

use RLuders\JWTAuth\Models\Settings as UserSettings; 

 public function boot(){
   UserSettings::set('activation_url', 'http://localhost:8080/account-activation?code={code}');
 }

This works, the problem is that it clears all the fields in the settings section for the plugin in the backend.
The values still exist, they just don't display anymore in their corresponding fields in the settings area.

Any hint what I'm doing wrong?

Thanks,
A.

Class '\RLuders\JWTAuth\Providers\AuthServiceProvider' not found

Hi!

Help me please. I'm currently learning winter cms(Watch and Learn) and there using your plugin. I tried to install it from cms backend, but failed. Then install by composer and it gives out such a mistake... 2 days I have been trying to understand what he wants from me

How to create a custom login request?

Sorry, this is not an issue, but a question.

I would like to create a custom login for jwt. The custom login would be using an unique uuid code of device which belongs to an user. No password, just an uuid login request, if exists then dispatch a token. Is there any best practice for this idea?

Thanks.

Install error "Method subMinutes does not exist."

Hi,

I'm trying to install the plugin from the October CMS Marketplace and get this error:

"Method subMinutes does not exist." on line 96 of .../vendor/laravel/framework/src/Illuminate/Support/Traits/Macroable.php

  • OctoberCMS Build: 471
  • PHP Version: 7.4.12

Best way to bind the Requests

It must have a better way to bind the Requests. For now, it's all in AuthServiceProvider.php, so one code block is created for every single Requests.

Can I bind using the interface?

Token expiration ?

Ahoj,
it seems that after a Login, the token is expiring after some time.
For me it's OK for the security side.

  1. What is the proper way to reconnect ? Login again ?

  2. When modifying profile or password after an authentication, how could I test if the token is still valid (user not deactivated or token not expired) ?
    Should I perform my profile modification and then manage errors, or could I test if the token is still valid before and how ?
    Is it the purpose of Refresh Token endpoint ?
    Thanks

How to refresh token ?

Ahoj Ricardo,
I'm trying to refresh the token in Vue.js with the following script
refreshToken ({ commit }) { const authorization = { headers: { 'Authorization': 'Bearer ' + state.token } } this.$axios .patch(SERVER_URL + "/api/auth/refresh-token", authorization) .then(response => { }
I get first an HTTP 200, then an HTTP 404 and finally a CORS error "Network Error"

Could it be the same as issue #49 ?

image

Refresh Token

The endpoint /refresh-token is returning this error.

A token is required
/var/www/public/plugins/rluders/jwtauth/vendor/tymon/jwt-auth/src/JWT.php line 331

Carbon Error on Plugin Installation

Iam getting the following Error on a fresh October Installation with Apache and PHP 7.1 and 7.2:

Declaration of Jenssegers\Date\Date::add($interval) must be compatible with Carbon\CarbonInterface::add($unit, $value = 1, $overflow = NULL)

get user object and check the user without middleware

Hi Recardo ,
thank you for useful plugin, but I have some question about this plugin. I want to check the user is login Or return the user object by static method without using middleware, I can use Auth::check but I want find by token ,

ex:
class Post extends Controller
public function review(){
if(JwtAuth::check){ return [ 'user'=>JwtAuth::user()];
}else{
return ['message'=> "you must register Or login to site']; }
}

Thanks

Improve error handling

Based on #40 it seems that it is necessary to improve the error handling to avoid non-treated 500 errors to be sent by the API. What I do expect here is that, when it fails, it should fail gracefully, giving back some meaningful response in JSON format.

API get user

Hi
I am doing some testing using the Postman collection.
I managed to login.
When I am trying to get the user with /api/auth/me in postman I got an exception, even if I set the header as documented (Authorization and Bearer token)

<p class="lead">We're sorry, but an unhandled error occurred. Please see the details below.</p>
            <div class="exception-name-block">
                <div>Token not provided</div>
                <p>/Users/christophevidal/Sites/oc-vodka/plugins/rluders/jwtauth/vendor/tymon/jwt-auth/src/Http/Middleware/BaseMiddleware.php 
                    <span>line</span> 52
                </p>

Fork for Winter CMS

I have created a fork where I have gotten this plugin working with the native Winter (formerly RainLab) plugins and core modules instead of their compatibility aliases.

https://github.com/josephcrowell/wn-jwtauth-plugin

I am good to maintain if you don't want to maintain a fork for Winter, but if you were going over to Winter any way, you can pull this in (probably as a new repo since the name is changed) where I've done the work for you.

How to change password ?

Dobry den Ricardo,
I'm using October and a frontend app on Vue.js (Quasar framework).
I'm wondering if the way to modify a password for a registered user in my app is to do it through the reset password process (with email key), or if it's possible directly when the user is registered, in a profile vue and how ?
Thanks for your help.

image

How to deal with Axios async ?

I'd like to refresh the token to check it's validity, before changing the user profile or password.
The problem is that the refresh response arrives after the profile update axios call.
What could you advice to wait the new token and insure the user access is still valid ?
Thanks for your help.

Class 'Tymon\JWTAuth\Providers\AbstractServiceProvider' not found

Hi,

I'm t install the plugin from the October CMS Marketplace and get this error:

(1/1) FatalThrowableErrorClass 'Tymon\JWTAuth\Providers\AbstractServiceProvider' not found

in AuthServiceProvider.php line 12
at require_once()in ClassLoader.php line 130
at ClassLoader->includeClass('RLuders\JWTAuth\Providers\AuthServiceProvider', 'plugins/rluders/jwtauth/providers/AuthServiceProvider.php')in ClassLoader.php line 99
at ClassLoader->load('RLuders\JWTAuth\Providers\AuthServiceProvider')
at spl_autoload_call('RLuders\JWTAuth\Providers\AuthServiceProvider')in Application.php line 635
at Application->resolveProvider('RLuders\JWTAuth\Providers\AuthServiceProvider')in Application.php line 582
at Application->register('RLuders\JWTAuth\Providers\AuthServiceProvider')in Plugin.php line 79
at Plugin->register()in PluginManager.php line 251
at PluginManager->registerPlugin(object(Plugin), 'RLuders.JWTAuth')in PluginManager.php line 185
at PluginManager->registerAll()in ServiceProvider.php line 51
at ServiceProvider->register()in Application.php line 586
at Application->register(object(ServiceProvider))in ProviderRepository.php line 75

Invalid response Content-Type when username has already been taken.

I am facing a very strange issue where when a username has already been taken the response I get is in html instead of text/json. If the email has been taken then the response is in text/json.

Also I have found out that this depends on the primary login method of the 'Users Plugin'; if set to username then username taken returns text/json and email returns text/html.

image

image

User register in vue.js + October

Thanks for this fine plugin, but I'm getting a strange pb when registering a user with my Vue.js app.
With this app developped with MDB framework, all is fine. Switching to Quasar with same code, I get the following error from October (nothing change from server side)

HTTP/1.1 500 Internal Server Error
Undefined index: password
C:\Dev\WinNMP\WWW\Meteo\plugins\rluders\jwtauth\http\requests\RegisterRequest.php line 21

public function data()  {
          $data = $this->all();
          // Password confirmation is optional
          if (!array_key_exists('password_confirmation', $data)) {
               $data['password_confirmation'] = $data['password'];
          }
          return $data;
}

Based on : https://watch-learn.com/creating-rent-car-app-vue-and-october/login-and-register-with-jwt
from the Vue.js side the data collected from my form is prepared for Axios this way :

const user = new URLSearchParams(); // Déclaration pour éviter pbs avec AXIOS
user.append("name", this.name);
user.append("surname", this.surname);
user.append("email", this.email);
user.append("password", this.password);
user.append("password_confirmation", this.password_confirmation);

The URLSearchParams() user has the form :
name=toto&surname=toto&email=toto%40toto.com&password=totototo&password_confirmation=totototo

Why with a Vue framework it's working and with the other, passed data seems to be wrong ?
It seems that the string is not exactly sent the same way and disturb JWT which misunderstand the parameters...
Could it be a control on reception which wrongly parse the received parameters ?

In addition, with a password length error, I get also a HTTP/1.1 500 Internal Server Error.

We're sorry, but an unhandled error occurred. Please see the details below.
The password must be between 8 and 255 characters.
C:\Dev\WinNMP\WWW\Meteo\vendor\october\rain\src\Database\Traits\Validation.php line 340

Thanks

Extend response

Hi All,

Could you please help me how could I extend response to get custom User (model) attributes and/or data that come from user model relationships (such as permissions, etc.)? Current response contains only fields of User model.

Thanks in advance!

Not getting error response on login and register

Hi,

So I have the following problem. When trying to login the user, if I send correct data everything works fine. I get the response, get the token, I get the user data. All good.

But if the user inputs wrong information, like instead of email he enters username. Then I just get CORS error.

http://api.localhost/api/auth/login 422 (Unprocessable Entity)

and

Access to XMLHttpRequest at 'http://api.localhost/api/auth/register' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Which is weird. Now I did more testing and for the login if I enter wrong email and password. I actually get the response of invalid_credentials, which is good, but I don't get a response if using username instead of email. At least not when contacting the API through my app, which is on another domain.

But if I do it through Postman, then I get:

{
    "error": {
        "login": [
            "The login must be a valid email address."
        ]
    }
}

Which is great, and I want to get the same thing through my app. But I keep getting CORS error.

Now for CORS I have this plugin installed: https://octobercms.com/plugin/offline-cors

I tried installing yours, and allowing everything, but it just didn't work at all, none of the requests passed. So I had to use the above mentioned plugin.

Also the same thing is happening with registration, when all the data is correct everything is fine and works well. But if for example you try to register user with existing email, you just get the CORS error.

Any help would be appreciated.

Autologin

Would be nice to have an autologin option after the user confirms the account creation, you can find where to do it here.

If the account creation confirmation is disabled, we probably also want to be able to enable the autologin.

How to install it from github?

OK! Since now I put it back as a paid plug-in at the OctoberCMS Marketplace maybe would be a good idea to improve the documentation that explains how to install it directly from the GitHub repository.

In this case, I guess that would be nice to explore 3 ways to get the source code and install the plug-in:

  • Clone
  • Download
  • Composer

The token could not be parsed from the request

I got an error like this. The RewriteRule is added in the .htaccess.

<div>The token could not be parsed from the request</div> <p><....>/plugins/rluders/jwtauth/vendor/tymon/jwt-auth/src/JWT.php <span>line</span> 185 </p>

Any idea?

Get user from token in my middleware

Hi to all,
I want to create my middleware which allow user to access api based on the group they belong to.

Is it possible to get user from token without provide user_id in the params call?

With JWT Auth API Plugin i can get current user with JWTAuth::parseToken()->authenticate();
But in this plugin is not possible.

Can you help me?
Thanks.

Error when trying to install plugin from October Cms

Hi, I am trying to use this plugin in October CMS and I was wondering if it is still available at OctoberCMS.

I get this error when I try to install the plugin:

Authority to provide product "rluders/jwtauth-plugin" could not be found

How can I implement editing of user information?

Hi!

Such a question is - is it possible to implement editing of user data through queries? For example, change your first name, last name, email, password, and so on

Maybe it's already there and I didn't notice..

Logout?

I realize at documentation there's no way to log out, once we log in there's no route from logout (e.g. auth/logout.

I saw there are extensions from tymonsdesign jwt token, I use it on a separate project mine and there's a logout possibility.

Might is missing something in the documentation?

Paid but still open-source and free

Hello!

I know that some of you will be mad with me, but I spend a lot of time thinking about it, and I decided on it. It is being a lot of fun to create and maintain this plugin over the last few years. Its first release was on Mar 3, 2017, and since then it is getting improved and receiving a lot of contribution from the community, and I do appreciate it.

In the beginning, the plugin used to be closed and paid, then, after some time I decided to make it free and opensource. But, it wasn't being enough, I was needing to spending some time replying to issues, fixing some bugs, in general, maintaining the project, and TBH I'm not using OctoberCMS anymore - wait, I still thinking that it is great. I'm just saying it, 'cause my working focus changed during the last 3 years.

But I felt that I still want to give back something to the community, mainly 'cause I think that OctoberCMS provide such a great environment, and I would like to help it somehow.

So, I'm making this plugin paid again. But, ONLY if you install it from the OctoberCMS marketplace. The plugin's license still the same and it still allows you to use it on commercial projects, or fork and create your version of it. It only means that, if you want to use the easy way to install it, by the OctoberCMS marketplace, you should buy it - in this case, you will be contributing with both, OctoberCMS and also my jobs.

If you want to use its free version, the only way to do it is to install it from this GitHub repository. And It is an easy, very easy thing to do.

Also, it costs only $5, which is the lowest value accepted by the OctoberCMS market place. It is pretty acceptable, and keep in mind that it will help me to keep updating this plugin, and also other plugins that I'm planning to develop. As well, 30% of every sale is "by default" sent to OctoberCMS, and it will help them.

I have no idea how it will work, and I can change it in the future. But, please, let me know in the comments what to do you think about my decision.

Of course, you also can support me on Patreon - and it is really helpful.

Thank you all.

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.