Laravel implementation of DINGO+JWT API interface in combat

Source: Internet
Author: User
Tags auth compact constructor json php file

The previous article explained how to configure the installation package (click here) and then explain how to use


Here my needs are very special, the model used is not app/user, so you need to specify---"Reference article click here


① New database and its model

1. New Migrate:

PHP Artisan make:migration create_clients_table--create=clients
2. New Model:

PHP Artisan Make:model Client

Then modify the model client's inheritance class as follows:

Use Illuminate\foundation\auth\user as authenticatable;
Use Illuminate\database\eloquent\model;

/**
 * @property mixed user_pwd */
class Client extends authenticatable
{
.....


3. Modify the Up method in the data/migrations/201x_xx_xx_xxxxxx_create_clients_table.php file as follows:

    Public function up ()
    {
        schema::create (' clients ', function (Blueprint $table) {
            $table->increments (' Id ');
            $table->string (' User_email ',);
            $table->string (' user_pwd ', +);
            $table->string (' user_name ',);
            $table->timestamps ();
        });
    }
And then execute PHP Artisan Migrate, so the new test data sheet is built. Then we need to modify the config/jwt.php "user" and "App\user" as follows:

' User ' = ' app\client ',


add dingo code under ②routes.php:

$api = App (' Dingo\api\routing\router ');
 ($API) {
    ($api) {
        $api->post (' User/login ', ' authcontroller@authenticate ');  Login Authorization
        $api->post (' User/register ', ' authcontroller@register ');
         ($API) {

            //path is/api/tests
            $api->get (' Tests ', ' testscontroller@index ');
            Request method:
            //http://localhost:8000/api/tests?token=xxxxxx  (obtained from login or registration, currently available only with Get)
            $api->get (' Tests/{id} ', ' testscontroller@show ');
            $api->get (' user/me ', ' authcontroller@authenticateduser '); (according to});});
The above we have to add a corresponding module.

Note: The above focus is (for specifying a specific model):

' Middleware ' = [' Client.change ']
The code for the middleware is as follows:

Handle ($request, Closure $next)
{
    config ([' jwt.user ' = ' \app\client ']);    Important for specifying a specific model
    config ([' auth.providers.users.model ' = + \app\client::class]);//important for specifying a specific model ....

    $next ($request);} 


③ Base Module Additions

First create the api/controllers and api/transformers directories in the app directory, as shown below:


The basecontroller.php is then created under controllers as the authentication base module that is inherited, with the following code:

<?php

namespace App\api\controllers;

Use App\http\controllers\controller;
Use dingo\api\routing\helpers;


Class Basecontroller extends Controller
{use
    Helpers;

    /****
     * Basecontroller constructor.
     *
    /Public Function __construct ()
    {

    }
}


④ Authentication Module Add

Authentication module is divided into login, registration, access to user information, all the code is as follows:

<?php namespace App\api\controllers;
Use app\client;
Use Illuminate\http\request;
Use Jwtauth;
Use tymon\jwtauth\exceptions\jwtexception;
Use tymon\jwtauth\exceptions\tokenexpiredexception;


Use tymon\jwtauth\exceptions\tokeninvalidexception;
     Class Authcontroller extends Basecontroller {/** * The authentication guard that should is used.

    * * @var String */Public function __construct () {parent::__construct (); }/** * @param Request $request * @return \illuminate\http\jsonresponse */Public function authent Icate (Request $request) {$payload = [' user_email ' = + $request->get (' email '), '
        Password ' = $request->get (' password ')]; try {if (! $token = Jwtauth::attempt ($payload)) {return response ()->json ([' error ' = ' = ' t
            Oken_not_provided '], 401); }} catch (Jwtexception $e) {return response ()->json ([' ERROR ' = ' cannot create token '], 500);
    } return Response ()->json (Compact (' token ')); }/** * @param request $request */Public Function register (request $request) {$newUser =
            [' user_email ' = $request->get (' email '), ' user_name ' = ' $request->get (' name '),
        ' Password ' = bcrypt ($request->get (' password '))];
        $user = Client::create ($newUser);
        $token = Jwtauth::fromuser ($user);
    return $token;
    }/**** * Get user's information * @return \illuminate\http\jsonresponse */Public Function Authenticateduser () {try {if (! $user = Jwtauth::p arsetoken ()->authenticate ()) {return response ()-
            >json ([' User_not_found '], 404); }} catch (Tokenexpiredexception $e) {return response ()->json ([' token_expired '], $e-&GT;GETSTATUSC
        Ode ()); } catch (Tokeninvalidexception $E) {return response ()->json ([' Token_invalid '], $e->getstatuscode ());
        } catch (Jwtexception $e) {return response ()->json ([' token_absent '], $e->getstatuscode ()); }//The token is valid and we have found the user via the sub claim Return response ()->json (Compact (' U
    Ser ')); }
}
Process Analysis:
① inherits from Basecontroller.php, inherits Dingo's Operation method

② inherits the Basecontroller.php constructor and changes its specified model with CONFIG.

③ here, if there is no configuration error, three modules will work.


⑤ Certification Module use explanation

Here we first use the postman (unclear search.) A Google plugin) request localhost:8000/api/user/register Registration Interface:


Then request the Localhost:8000/api/user/login request as shown below:

We also got a new token, which shows that each login will refresh token so that we can copy the latest token, the following useful


Next we use the latest personal information we've just acquired.



⑥token Get information module

⑤ the last access to personal information module also belongs here ... The following main explanation returns a specific data format

First, add the teststransformer.php file code under the Transformers directory as follows:

<?php

namespace App\api\transformers;

/** This class for Dingo API encapsulation Good **/use
league\fractal\transformerabstract;

Class Teststransformer extends Transformerabstract
{
    /***
     * Separate for understanding coupling
     * Data fields Select
     * @param $lesson
     * @return Array
     *
    /Public Function transform ($lesson)
    {
        /****** hidden database field *****/
        return ['
            username ' = $lesson [' user_name '],
            ' email ' = ' + ' $lesson [' user_email '], '
        ;
    }
}
Note: This inherits the Transformerabstract class of Dingo.


Then create the new testscontroller.php as the base information in the controllers directory, with the following code:

<?php
namespace App\api\controllers;


Use App\api\transformers\teststransformer;
Use app\client;

Class Testscontroller extends Basecontroller
{public
    Function index ()
    {
        $tests = Client::all ();
        return $this->collection ($tests, New Teststransformer ());
    }

    Public function Show ($id)
    {
        $test = Client::find ($id);
        if (! $test) {
            return $this->response->errornotfound (' Test not found ');
        }
        return $this->item ($test, New Teststransformer ());
    }
}

Note: Teststransformer is referenced here as a data format, item is dingo with function, processing data format and returning

Request the way and ⑤ request localhost:8000/api/user/me?token=xxxxxxxxxxxxxxxxxxxx consistent, details request address see routes file.

This is the end of the

DINGO+JWT interface developed ...... ..... ..... .................

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.