Giter Site home page Giter Site logo

jwt-auth's Introduction

jwt-auth

JSON Web Token Authentication for Laravel

Build Status Scrutinizer Code Quality Coverage Status License Latest Version Total Downloads

Docs work in progress!

This package requires PHP >=5.4

lots of improvements being made on develop branch (0.4.x-dev). Hope to release soon

Installation

Install via composer - edit your composer.json to require the package.

"require": {
    "tymon/jwt-auth": "0.3.*"
}

Then run composer update in your terminal to pull it in.

Once this has finished, you will need to add the service provider to the providers array in app/config/app.php as follows:

'Tymon\JWTAuth\JWTAuthServiceProvider'

Next, also in the app/config/app.php file, under the aliases array, you may want to add the JWTAuth facade.

'JWTAuth' => 'Tymon\JWTAuth\Facades\JWTAuth'

Finally, you will want to publish the config using the following command:

$ php artisan config:publish tymon/jwt-auth
Don't forget to set a secret key in the config file!

I have included a helper command to generate a key as follows:

$ php artisan jwt:generate

this will generate a new random key, which will be used to sign your tokens.

And you're done!

Basic Usage

Creating Tokens

There are a number of ways you can generate a token. The usual flow would be to pass some credentials and the package will try to authenticate the user and return a fully formed JSON Web Token.

Authenticating a User
// simple example
Route::post('auth/login', function () {
    $credentials = Input::only('email', 'password');

    if ( ! $token = JWTAuth::attempt($credentials) )
    {
        // return 401 error response
    }

    return Response::json(compact('token'));
});
Creating a token based on a User object
$user = User::find(1);
$token = JWTAuth::fromUser($user);

Retrieving User from a token

Once a user has "logged in" (e.g. provided their credentials via a login form) to your application, then the next step would be to make a subsequent request, with the token, to retrieve the users' details, so you can show them as being logged in.

To make authenticated requests, you will need to set an authorization header:

Authorization: Bearer {yourtokenhere}

Alternatively you can include the token via a query string

http://api.mysite.com/me?token={yourtokenhere}

// simple example
Route::post('me', function () {

    try
    {
        $user = JWTAuth::parseToken()->toUser();
    }
    catch(Tymon\JWTAuth\Exceptions\TokenExpiredException $e)
    {
        // token has expired
        return Response::json(['error' => 'token_expired'], 401);
    }

    if (! $user)
    {
        // user not found
        return Response::json(['error' => 'user_not_found'], 404);
    }

    return Response::json(compact('user'));
});

Alternatively, you can use the included jwt-auth route filter. It includes some sensible default responses when, for example, the token has expired or is invalid.

Route::post('me', ['before' => 'jwt-auth', function() {

    $user = JWTAuth::getToken()->toUser();

    return Response::json(compact('user'));
}]);

These responses can be overridden, by hooking into a series of events that are fired before the response is returned. Here are the events that can be fired during the filter.

// fired when the token could not be found in the request
Event::listen('tymon.jwt.absent');

// fired when the token has expired
Event::listen('tymon.jwt.expired');

// fired when the token is found to be invalid
Event::listen('tymon.jwt.invalid');

// fired if the user could not be found (shouldn't really happen)
Event::listen('tymon.jwt.user_not_found');

// fired when the token is valid (User is passed along with event)
Event::listen('tymon.jwt.valid');

API

// accepts an array of credentials e.g. email & password
JWTAuth::attempt($credentials);

// accepts a token and returns the authenticated user on success
JWTAuth::login($token);

// retrieves the token from the request
// (checks Authorization Bearer header and query string)
JWTAuth::getToken();

// accepts a token and returns the User object
JWTAuth::toUser($token);

// accepts a User, and returns a token
JWTAuth::fromUser($user);

// sets the token for the request
// further methods that require a token can then be chained
JWTAuth::setToken($token);

// returns the subject (sub) claim from the token
// (defaults to User id)
JWTAuth::getSubject($token);

// provides access to the underlying jwt provider
// returns a token
JWTAuth::encode($subject, $customClaims);

// decodes a token and returns the payload array
JWTAuth::decode($token);

Todo

  • add more tests
  • add test coverage reporting
  • finish docs!
  • fully decouple from laravel

License

The MIT License (MIT)

Copyright (c) 2014 Sean Tymon

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

jwt-auth's People

Contributors

agentk avatar dirkgroenen avatar overtrue avatar scrutinizer-auto-fixer avatar seanclowdy avatar tymondesigns avatar

Watchers

 avatar

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.