令牌提交的身份验证失败_AngularJS和Laravel应用的基于令牌的身份验证

令牌提交的身份验证失败

Adding authentication to an AngularJS and Laravel application is not the most straight-forward, especially if we take the approach of creating independent front-end and backend applications and connecting them with an API exposed by Laravel. Laravel comes with easy-to-use authentication out of the box, but it is session-based and is therefore most useful for traditional round-trip applications.

向AngularJS和Laravel应用程序添加身份验证并不是最简单的方法,特别是如果我们采用创建独立的前端和后端应用程序并将它们与Laravel公开的API连接的方法,则尤其如此。 Laravel开箱即用,具有易于使用的身份验证,但是它是基于会话的,因此对于传统的往返应用程序最有用。

For single page applications that rely on an API, a better way to handle authentication is with JSON Web Tokens, or JWTs. Put simply, a JWT (pronounced jot) is a JSON object with three distinct parts that are used together to convey information between two parties. JWTs consist of a header, a payload and a signature which are all encoded. We won't get into full detail about the structure and inner workings of JWTs in this tutorial, but Chris covers it in The Anatomy of a JSON Web Token.

对于依赖API的单页应用程序,一种更好的身份验证方法是使用JSON Web令牌或JWT。 简而言之,JWT(发音为jot )是一个JSON对象,具有三个不同的部分,这些部分一起用于在两方之间传递信息。 JWT由标头,有效负载和签名组成,它们均已编码。 在本教程中,我们不会详细介绍JWT的结构和内部工作原理,但是Chris在JSON Web令牌剖析对此进行了介绍

To fully understand how JWTs are used, we have to shift our thinking a bit. Traditional authentication requires that the server store the user's authentication information which is checked every time the user makes a request. This method creates challenges when the application grows and needs to scale up, especially if it is distributed across several different servers. It also becomes problematic when we want to use our API for other purposes, such as for mobile applications. To get a better understanding of the limitations of server-based authentication and how JWTs can help, read The Ins and Outs of Token Based Authentication.

为了完全理解JWT的用法,我们必须稍微改变一下思路。 传统身份验证要求服务器存储用户的身份验证信息,每次用户发出请求时都会检查该信息。 当应用程序增长并且需要扩展时,尤其是如果它分布在多个不同的服务器上时,此方法会带来挑战。 当我们想将我们的API用于其他目的(例如用于移动应用程序)时,这也成为问题。 为了更好地理解基于服务器的身份验证的局限性以及JWT如何提供帮助,请阅读基于令牌的身份验证的来龙去脉。

我们将建立什么 (What We'll Build)

This tutorial will demonstrate how to implement token-based authentication in an AngularJS and Laravel application. To do so, we'll build a simple app that will authenticate users with a login form. If successfully authenticated, the user will be redirected to a view where they can get a list of all users in the database. The focus of the tutorial will be on how we can generate JWTs on the Laravel side, obtain them on the front-end and then send them along with every request to the API.

本教程将演示如何在AngularJS和Laravel应用程序中实现基于令牌的身份验证。 为此,我们将构建一个简单的应用程序,该应用程序将使用登录表单对用户进行身份验证。 如果成功通过身份验证,该用户将被重定向到一个视图,在该视图中他们可以获取数据库中所有用户的列表。 本教程的重点是如何在Laravel端生成JWT,在前端获取它们,然后将它们与每个请求一起发送给API。

angular-laravel-auth-9

We'll be using a couple open source packages for this application: jwt-auth for creating JWTs on the Laravel side and Satellizer for handling the AngularJS authentication logic.

我们将为此应用程序使用几个开源软件包: jwt-auth用于在Laravel端创建JWT, Satellizer用于处理AngularJS身份验证逻辑。

安装Laravel依赖项 (Installing the Laravel Dependencies)

Let's create a new Laravel application called jot-bot. Assuming you have Composer and the Laravel installer setup and ready to go, from the command line:

让我们创建一个名为jot-bot的新Laravel应用程序。 假设您已经完成Composer和Laravel安装程序的安装并可以从命令行开始:

laravel new jot-bot

If everything worked correctly you should have all the Laravel files installed. The next step is to rename .env.example to .env so that Laravel can properly pull environment variables for the app.

如果一切正常,则应该安装所有的Laravel文件。 下一步是将.env.example重命名为.env以便Laravel可以正确提取应用程序的环境变量。

It's possible that the application key doesn't properly generate for you on installation. If that is the case, you can generate a new key:

应用程序密钥可能无法在安装时为您正确生成。 在这种情况下,您可以生成一个新密钥:

php artisan key:generate

APP_KEY within the .env file will need to be set to this new key. You can also take this opportunity to create a new database for the application and set the database credentials in the .env file. My .env file looks like this:

APP_KEY文件中的.env将需要设置为此新密钥。 您还可以借此机会为应用程序创建一个新数据库,并在.env文件中设置数据库凭据。 我的.env文件如下所示:

APP_ENV=local
APP_DEBUG=true
APP_KEY=lk7IqejFTEqaIep8guBE16Mg5JWpZtHj

DB_HOST=localhost
DB_DATABASE=jot-bot
DB_USERNAME=root
DB_PASSWORD=root

Next, let's fire up the app to make sure everything is working:

接下来,让我们启动该应用程序以确保一切正常:

cd jot-bot
php artisan serve

If everything is working you should see the Laravel welcome page.

如果一切正常,您应该看到Laravel欢迎页面。

angular-laravel-auth-1

Now that the core Laravel files are installed, let's install jwt-auth. Open composer.json and update the require object to include jwt-auth:

现在已经安装了核心Laravel文件,让我们安装jwt-auth。 打开composer.json并更新require对象以包括jwt-auth:

// composer.json

...

"require": {
       "php": ">=5.5.9",
       "laravel/framework": "5.1.*",
       "tymon/jwt-auth": "0.5.*"
   },

Next, let's bring this package in by running an update. From the command line:

接下来,让我们通过运行更新来引入此软件包。 在命令行中:

composer update

We'll now need to update the providers array in config/app.php with the jwt-auth provider. Open up config/app.php, find the providers array located on line 111 and add this to it:

现在,我们需要使用jwt-auth provider更新config/app.php的providers数组。 打开config/app.php ,找到位于第111行的providers数组,并将其添加到其中:

Tymon\JWTAuth\Providers\JWTAuthServiceProvider::class

We should also add in the jwt-auth facades which we can do in config/app.php. Find the aliases array and add these facades to it:

我们还应该在config/app.php添加jwt-auth外观。 找到aliases数组并将以下外观添加到其中:

'JWTAuth'   => Tymon\JWTAuthFacades\JWTAuth::class,
'JWTFactory' => Tymon\JWTAuthFacades\JWTFactory::class

We also need to publish the assets for this package. From the command line:

我们还需要发布此程序包的资产。 在命令行中:

php artisan vendor:publish --provider="Tymon\JWTAuthProviders\JWTAuthServiceProvider"

After you run this command you will see a new file in the config folder called jwt.php. This file contains settings for jwt-auth, one of which we need to change right away. We need to generate a secret key which we can do from the command line:

运行此命令后,您将在config文件夹中看到一个名为jwt.php的新文件。 该文件包含jwt-auth的设置,我们需要立即更改其中之一。 我们需要生成一个可以从命令行执行的密钥:

php artisan jwt:generate

You'll see that after running this command we get a new value next to 'secret' where "changeme" was before.

您会看到运行此命令后,我们在'secret'旁边获得了一个新值,其中“ changeme”在此之前。

We've got everything installed on the Laravel side---now let's take care of the AngularJS dependencies.

我们已经在Laravel端安装了所有东西-现在让我们来照顾AngularJS依赖项。

安装AngularJS依赖项 (Installing the AngularJS Dependencies)

There are a number of things that need to happen on the front-end so that we can send a JWT with every request to the Laravel API after our user is authenticated. Namely, we need to keep the JWT in local storage once we retrieve it from the API and also need to add a header to every subsequent request that contains the token. We could write the appropriate JavaScript to accomplish this on our own, but a package has already been created that does a great job of it. Instead of spending extra effort, let's make use of Satellizer.

前端需要做很多事情,以便我们的用户通过身份验证后,我们可以将每个请求的JWT发送到Laravel API。 即,一旦从API检索到JWT,就需要将其保留在本地存储中,并且还需要向包含令牌的每个后续请求中添加标头。 我们可以自己编写适当JavaScript来完成此任务,但是已经创建了一个可以很好完成工作的程序包。 不用花费额外的精力,让我们使用Satellizer

Let's use npm to install our front-end dependencies. From the command line:

让我们使用npm安装我们的前端依赖项。 在命令行中:

cd public
npm install angular satellizer angular-ui-router bootstrap

创建一些测试数据 (Creating Some Test Data)

Laravel comes with a migration for a users table out of the box and this is the only one we'll need for the tutorial. Let's run the migrations so that this table gets created in the database and then seed it with some test data. From the command line:

Laravel开箱即用地为users表提供了迁移,这是本教程唯一需要的迁移。 让我们运行迁移,以便在数据库中创建该表,然后将其与一些测试数据一起播种。 在命令行中:

php artisan migrate

For seeding, we'll put the array of users and the logic to insert them into the database right within DatabaseSeeder.php, but you can also create a separate seeder file and call it from that file if you like.

对于播种,我们将放置用户数组和将其插入到DatabaseSeeder.php的数据库中的逻辑,但是您也可以创建一个单独的种子文件,并根据需要从该文件中调用它。

// database/seeds/DatabaseSeeder.php

<?php

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
use App\User;

class DatabaseSeeder extends Seeder
{
    public function run()
    {
        Model::unguard();

        DB::table('users')->delete();

        $users = array(
                ['name' => 'Ryan Chenkie', 'email' => 'ryanchenkie@gmail.com', 'password' => Hash::make('secret')],
                ['name' => 'Chris Sevilleja', 'email' => 'chris@scotch.io', 'password' => Hash::make('secret')],
                ['name' => 'Holly Lloyd', 'email' => 'holly@scotch.io', 'password' => Hash::make('secret')],
                ['name' => 'Adnan Kukic', 'email' => 'adnan@scotch.io', 'password' => Hash::make('secret')],
        );

        // Loop through each user above and create the record for them in the database
        foreach ($users as $user)
        {
            User::create($user);
        }

        Model::reguard();
    }
}

In this seeder we are creating an array of users and then looping through them to add them to the database. This file relies on us using AppUser which is the User model that also ships with Laravel. As we loop through the users we call create on each to add that record to the database. With this in place, we just need to run the seeder.

在此播种器中,我们创建一个用户数组,然后遍历用户以将其添加到数据库中。 该文件依赖我们使用AppUser ,这是AppUserUser模型。 当我们遍历用户时,我们在每个用户上调用create将该记录添加到数据库中。 有了这个,我们只需要运行播种机即可。

php artisan db:seed

创建API路由 (Creating the API Routes)

Once we've confirmed that the database has been seeded properly, let's get the API setup in routes.php.

一旦确认数据库已正确植入种子,就可以在routes.php获取API设置。

// app/Http/routes.php

<?php

Route::get('/', function () {
    return view('index');
});

Route::group(['prefix' => 'api'], function()
{
    Route::resource('authenticate', 'AuthenticateController', ['only' => ['index']]);
    Route::post('authenticate', 'AuthenticateController@authenticate');
});

We've done a couple things here---first, we've changed the starting route to load a view that we'll create later called index instead of welcome. Next, we've created a route group that is prefixed with api and that currently serves a resource called authenticate. We only really want the index method of this resource controller which we indicate with the third argument. We'll also need a custom method called authenticate on this controller which handles generating and returning a JWT.

我们在这里做了两件事-首先,我们更改了开始路线,以加载我们稍后将创建的称为index而不是welcome的视图。 接下来,我们创建了一个以api为前缀的路由组,该路由组当前提供一个名为authenticateresource 。 我们只真正想要此资源控制器的index方法,该方法将用第三个参数指示。 我们还将在此控制器上需要一个名为authenticate的自定义方法,该方法处理生成和返回JWT。

Now we need to create a resource controller called AuthenticateController. From the command line:

现在我们需要创建一个称为AuthenticateController的资源控制器。 在命令行中:

php artisan make:controller AuthenticateController

If that runs successfully you should now see AuthenticateController.php in app/Http/Controllers.

如果成功运行,您现在应该在app/Http/Controllers看到AuthenticateController.php

We're going to need to use some pieces of the JWTAuth package in this controller.

我们将需要在此控制器中use一些JWTAuth软件包。

// app/Http/controllers/AuthenticateController.php

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;

use AppHttpRequests;
use AppHttpControllersController;
use JWTAuth;
use Tymon\JWTAuthExceptions\JWTException;

class AuthenticateController extends Controller
{

    public function index()
    {
        // TODO: show users
    }    

    public function authenticate(Request $request)
    {
        $credentials = $request->only('email', 'password');

        try {
            // verify the credentials and create a token for the user
            if (! $token = JWTAuth::attempt($credentials)) {
                return response()->json(['error' => 'invalid_credentials'], 401);
            }
        } catch (JWTException $e) {
            // something went wrong
            return response()->json(['error' => 'could_not_create_token'], 500);
        }

        // if no errors are encountered we can return a JWT
        return response()->json(compact('token'));
    }
}

The try block in the authenticate method attempts to produce a token using the JWTAuth facade with the user's credentials. If something goes wrong with that, the method will return a 401 and say the credentials are invalid. In other cases where an exception is thrown, it will return a 500 indicating an internal server error and saying that something went wrong. If we are able to get past that then we can return a token. Returning it with compact('token') puts the object on a key called token which will come in handy when we read it with Satellizer.

authenticate方法中的try块尝试使用具有用户凭证的JWTAuth外观来生成令牌。 如果出现问题,该方法将返回401并说凭据无效。 在引发异常的其他情况下,它将返回500指示内部服务器错误并指出出了问题。 如果我们能够超越那一步,那么我们可以返回一个令牌。 用compact('token')返回它会把对象放在一个叫做token的键上,当我们用Satellizer读取它时会派上用场。

We'll use this controller to show data for all users as well, but let's first test out the API.

我们还将使用该控制器为所有用户显示数据,但让我们首先测试一下API。

测试API (Testing Out the API)

By default, Laravel has CSRF token verification turned on, but since we're using JWTs in a stateless manner now, we don't really need CSRF tokens. We can turn this default behavior off by commenting out the VerifyCsrfToken middleware in Kernel.php.

默认情况下,Laravel启用了CSRF令牌验证,但是由于我们现在以无状态方式使用JWT,因此我们实际上并不需要CSRF令牌。 我们可以通过注释掉把这种默认行为关闭VerifyCsrfToken中间件Kernel.php

We're also eventually going to need to use the middleware that jwt-auth provides. We can set that up in the routeMiddleware array in Kernel.php as well.

我们最终还将需要使用jwt-auth提供的中间件。 我们也可以在Kernel.phprouteMiddleware数组中进行Kernel.php

// app/Http/Kernel.php

...

namespace AppHttp;

use IlluminateFoundationHttpKernel as HttpKernel;

class Kernel extends HttpKernel
{

    protected $middleware = [
        Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        App\Http\Middleware\EncryptCookies::class,
        Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        Illuminate\Session\Middleware\StartSession::class,
        Illuminate\View\Middleware\ShareErrorsFromSession::class,
        // App\Http\Middleware\Verify\CsrfToken::class,
    ];

    protected $routeMiddleware = [
        'auth' => App\Http\Middleware\Authenticate::class,
        'auth.basic' => Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'guest' => App\Http\Middleware\RedirectIfAuthenticated::class,
        'jwt.auth' => Tymon\JWTAuth\MiddlewareGetUserFromToken::class,
        'jwt.refresh' => TymonJWTAuth\MiddlewareRefreshToken::class
    ];
}

Now that VerifyCsrfToken is turned off, let's check the API with Postman.

现在, VerifyCsrfToken已关闭,让我们用Postman检查API。

If we send a POST request to localhost:8000/api/authenticate with the credentials for one of our users as URL parameters, we can see that we get a token returned.

如果我们使用localhost:8000/api/authenticate用户之一的凭据作为URL参数将POST请求发送到localhost:8000/api/authenticate ,我们可以看到我们得到了返回的令牌。

angular-laravel-auth-3-1

Now that we're successfully getting a token, let's put it to use and setup our index method in the controller to return the data for all users if a token is present.

现在我们已经成功获取了令牌,让我们使用它并在控制器中设置index方法,以在存在令牌的情况下为所有用户返回数据。

显示用户数据 (Showing User Data)

We're going to return the data for all of the users in the database, but only if there is a token passed along with the request. We can make this happen by protecting our API with the middleware that comes with jwt-auth.

我们将返回数据库中所有用户的数据,但前提是请求中传递了令牌。 我们可以通过使用jwt-auth随附的中间件保护我们的API来实现这一目标。

Let's add some logic to show all of the users if the token sent along with the request is valid.

让我们添加一些逻辑,以显示与请求一起发送的令牌是否有效的所有用户。

// app/Http/Controllers/AuthenticateController.php

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use App\User;

class AuthenticateController extends Controller
{

public function __construct()
   {
       // Apply the jwt.auth middleware to all methods in this controller
       // except for the authenticate method. We don't want to prevent
       // the user from retrieving their token if they don't already have it
       $this->middleware('jwt.auth', ['except' => ['authenticate']]);
   }

public function index()
{
    // Retrieve all the users in the database and return them
    $users = User::all();
    return $users;
}

...

Here we are saying we want the jwt-auth middleware to be applied to everything in the controller except the authenticate method (we don't want to block the user from retrieving their token) and we have the index method returning a list of all users.

在这里,我们要说的是,我们希望将jwt-auth中间件应用于控制器中除authenticate方法(我们不想阻止用户检索其令牌)之外的所有内容,并且让index方法返回所有用户的列表。

If we try making a GET request to localhost:8000/api/authenticate without a JWT in as a header or URL parameter, we get a 400 error that says no token was provided.

如果我们尝试向localhost:8000/api/authenticate发出GET请求而没有JWT作为标头或URL参数,则会出现400错误,提示未提供令牌。

angular-laravel-auth-4-1

If, however, we copy and paste the JWT we retrieved earlier as a URL parameter with the key of token, we get all the user data returned to us.

但是,如果我们使用token的键将先前检索到的JWT复制并粘贴为URL参数,则将所有用户数据返回给我们。

angular-laravel-auth-5-1

The jwt-auth middleware checks for the presence of the token and let's the request through if it is there and is valid, but rejects the request if it is not.

jwt-auth中间件检查令牌的存在,让请求通过,如果令牌存在且有效,但如果令牌不存在则拒绝该请求。

Just to prove that the middleware is doing its job, let's try removing a character from the token to invalidate it. We can see that the call we then make to the index method gets denied and we can't see the users list.

只是为了证明中间件正在发挥作用,让我们尝试从令牌中删除一个字符以使其无效。 我们可以看到我们随后对index方法的调用被拒绝,并且看不到用户列表。

angular-laravel-auth-6-1

设置前端 (Setting up The Front-End)

Now that the API is setup and the middleware is functioning properly we can create the front-end of our app.

现在已经设置了API并且中间件运行正常,我们可以创建应用程序的前端。

We'll need to setup our initial view in an index.php file because this is what our Laravel routes.php file is setup to return when the user hits the main / route.

我们需要设置我们的初步看法在index.php文件,因为这是我们的Laravel routes.php文件被设定,当用户点击主返回/路线。

<!-- resources/views/index.php -->

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Angular-Laravel Authentication</title>
        <link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.css">
    </head>
    <body ng-app="authApp">

        <div class="container">
            <div ui-view></div>
        </div>        

    </body>

    <!-- Application Dependencies -->
    <script src="node_modules/angular/angular.js"></script>
    <script src="node_modules/angular-ui-router/build/angular-ui-router.js"></script>
    <script src="node_modules/satellizer/satellizer.js"></script>

    <!-- Application Scripts -->
    <script src="scripts/app.js"></script>
    <script src="scripts/authController.js"></script>
    <script src="scripts/userController.js"></script>
</html>

In the index.php file we have included all of the application dependency scripts that we installed earlier and have also put references in for the application scripts that we've yet to create. Since we're using UI Router we are serving a ui-view in the middle of the page which is what will be used to handle our different states.

index.php文件中,我们包含了先前安装的所有应用程序依赖项脚本,并且还为尚未创建的应用程序脚本添加了引用。 由于我们使用的是UI Router,因此我们在页面中间提供一个ui-view ,该ui-view将用于处理不同的状态。

Next, let's create our main app.js file.

接下来,让我们创建我们的主app.js文件。

// public/scripts/app.js

(function() {

    'use strict';

    angular
        .module('authApp', ['ui.router', 'satellizer'])
        .config(function($stateProvider, $urlRouterProvider, $authProvider) {

            // Satellizer configuration that specifies which API
            // route the JWT should be retrieved from
            $authProvider.loginUrl = '/api/authenticate';

            // Redirect to the auth state if any other states
            // are requested other than users
            $urlRouterProvider.otherwise('/auth');

            $stateProvider
                .state('auth', {
                    url: '/auth',
                    templateUrl: '../views/authView.html',
                    controller: 'AuthController as auth'
                })
                .state('users', {
                    url: '/users',
                    templateUrl: '../views/userView.html',
                    controller: 'UserController as user'
                });
        });
})();

Here we are loading the ui.router and satellizer modules and setting up some configuration for them. Satellizer gives us an $authProvider which can be used to configure its settings. In particular, we want to specify that when using Satellizer to login, the HTTP requests that get made to retrieve the JWT from the API should go to api/authenticate.

在这里,我们加载ui.routersatellizer模块和设置一些配置它们。 Satellizer为我们提供了一个$authProvider ,可用于配置其设置。 特别是,我们要指定使用Satellizer登录时,从API检索JWT的HTTP请求应转到api/authenticate

We also use $stateProvider to setup configuration for the two states that we'll be using: auth and users.

我们还使用$stateProvider为将要使用的两个状态设置配置: authusers

We'll now need to create views for the auth and users states and controllers to handle their behavior.

现在,我们需要为authusers状态以及控制器创建视图以处理其行为。

设置身份验证状态 (Setting Up the Auth State)

// public/scripts/authController.js

(function() {

    'use strict';

    angular
        .module('authApp')
        .controller('AuthController', AuthController);

    function AuthController($auth, $state) {

        var vm = this;

        vm.login = function() {

            var credentials = {
                email: vm.email,
                password: vm.password
            }

            // Use Satellizer's $auth service to login
            $auth.login(credentials).then(function(data) {

                // If login is successful, redirect to the users state
                $state.go('users', {});
            });
        }

    }

})();

In our AuthController we are injecting $auth which is a service provided by Satellizer for communicating with the API and also $state so that we can handle redirects.

在我们的AuthController我们注入了$auth ,这是Satellizer提供的用于与API通信的服务,还注入$auth $state以便我们可以处理重定向。

We've got one method in this controller---login---which is responsible for using the $auth service to make a call to the API to retrieve the user's JWT. We setup our credentials object to contain an email address and password which we'll get from the form fields in the view and then pass them to the login method on the $auth service. If the token is successfully retrieved we are redirected to the users state.

在此控制器中,我们有一种方法- login -负责使用$auth服务调用API以检索用户的JWT。 我们将凭据对象设置为包含一个电子邮件地址和密码,这些电子邮件地址和密码将从视图的表单字段中获取,然后将其传递给$auth服务的login方法。 如果成功检索到令牌,我们将被重定向到users状态。

So what does the $auth service do exactly? If we dig into the Satellizer source we can see what's happening when the login method is called on line 422.

那么$auth服务到底能做什么? 如果我们深入研究Satellizer源,我们可以看到在第422行调用login方法时发生了什么。

// node_modules/satellizer/satellizer.js
...

local.login = function(user, redirect) {
    var loginUrl = config.baseUrl ? utils.joinUrl(config.baseUrl, config.loginUrl) : config.loginUrl;
    return $http.post(loginUrl, user).then(function(response) {
        shared.setToken(response, redirect);
        return response;
    });
...

We can see here that this method makes an $http.post call to the login URL that we specified in our config block in app.js and, if successful, sets the returned token in local storage.

我们可以在这里看到,此方法对在app.js的config块中指定的登录URL进行了$http.post调用,如果成功,则将返回的令牌设置在本地存储中。

Now let's setup the template for the login page.

现在,让我们为登录页面设置模板。

<!-- public/views/authView.html -->

<div class="col-sm-4 col-sm-offset-4">
    <div class="well">
        <h3>Login</h3>
        <form>
            <div class="form-group">
                <input type="email" class="form-control" placeholder="Email" ng-model="auth.email">
            </div>
            <div class="form-group">
                <input type="password" class="form-control" placeholder="Password" ng-model="auth.password">
            </div>
            <button class="btn btn-primary" ng-click="auth.login()">Submit</button>
        </form>
    </div>
</div>

In this view we setup two form fields---one for the user's email address and the other for their password. Next we call the login method in our AuthController to submit the data.

在此视图中,我们设置了两个表单字段-一个用于用户的电子邮件地址,另一个用于其密码。 接下来,我们在AuthController调用login方法来提交数据。

We can now try logging in to see if we get our token set in local storage.

现在,我们可以尝试登录以查看是否在本地存储中设置了令牌。

angular-laravel-auth-7

Password: secret

密码:秘密

If everything worked out we should now see the token saved in local storage.

如果一切顺利,我们现在应该看到令牌已保存在本地存储中。

angular-laravel-auth-8

We will also have been redirected to the users state which is what we want; however, we don't yet have a view or controller setup to handle this state. Let's put that in now.

我们还将被重定向到我们想要的users状态; 但是,我们还没有视图或控制器设置来处理此状态。 现在放进去。

设置用户状态 (Setting Up the Users State)

// public/scripts/userController.js

(function() {

    'use strict';

    angular
        .module('authApp')
        .controller('UserController', UserController);  

    function UserController($http) {

        var vm = this;

        vm.users;
        vm.error;

        vm.getUsers = function() {

            // This request will hit the index method in the AuthenticateController
            // on the Laravel side and will return the list of users
            $http.get('api/authenticate').success(function(users) {
                vm.users = users;
            }).error(function(error) {
                vm.error = error;
            });
        }
    }

})();

This controller has one method, getUsers, which makes an $http.get request to the API to fetch the data for all users. If the call is successful, the users data is placed on the vm.users key. If not, the error message that gets returned is placed on the vm.error key. Now let's reflect this data in a view:

该控制器有一个方法getUsers ,它向API发出$http.get请求以获取所有用户的数据。 如果调用成功,则将用户数据放在vm.users键上。 如果不是,则将返回的错误消息放在vm.error项上。 现在,让我们在视图中反映这些数据:

<!-- public/views/userView.html -->

<div class="col-sm-6 col-sm-offset-3">
    <div class="well">
        <h3>Users</h3>  
        <button class="btn btn-primary" style="margin-bottom: 10px" ng-click="user.getUsers()">Get Users!</button>
        <ul class="list-group" ng-if="user.users">
            <li class="list-group-item" ng-repeat="user in user.users">
                <h4>{{user.name}}</h4>
                <h5>{{user.email}}</h5>
            </li>
        </ul>
        <div class="alert alert-danger" ng-if="user.error">
            <strong>There was an error: </strong> {{user.error.error}}
            <br>Please go back and login again
        </div>
    </div>
</div>

When this state is first loaded there won't be any data displayed because we have set it up so that the data is fetched when the Get Users! button is clicked. Since we have our token saved in local storage, we should be able to get a list of the users back when we click this button.

首次加载此状态时,将不会显示任何数据,因为我们已经对其进行了设置,以便在“ Get Users!Get Users!数据Get Users! 按钮被点击。 由于我们已将令牌保存在本地存储中,因此当我们单击此按钮时,我们应该能够重新获得用户列表。

angular-laravel-auth-9

You might be wondering how we are successfully getting data back when we haven't done anything to send the JWT along with our $http request. Satellizer is taking care of this for us behind the scenes and is including the token as a header. We can see this if we open up the network tab in developer tools and inspect the request that was just sent.

您可能想知道当我们没有做任何事情来将JWT和$http请求一起发送时,如何成功地取回数据。 Satellizer正在幕后为我们处理这件事,并将令牌作为标头包括在内。 如果我们在开发人员工具中打开“网络”标签并检查刚刚发送的请求,就可以看到这一点。

angular-laravel-auth-10

An Authorization header gets added to the request with a value of Bearer . The token from the header is parsed by the jwt-auth middleware on the backend and our request is granted if it is valid.

Authorization标头添加到请求中,其值为Bearer 。 头中的令牌由后端的jwt-auth中间件解析,如果请求有效,则授予我们的请求。



RewriteCond %{HTTP:Authorization} ^(.*) RewriteCond %{HTTP:Authorization} ^(.*)

RewriteRule .* - [e=HTTP_AUTHORIZATION:%1] RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]

To prove that the request won't be successful if the token isn't present, let's try deleting it from local storage. In developer tools, right-click the token and choose delete, then refresh the page.

为了证明如果令牌不存在,请求将不会成功,让我们尝试将其从本地存储中删除。 在开发人员工具中,右键单击令牌,然后选择“删除”,然后刷新页面。

angular-laravel-auth-11

As you can see, the error condition is hit in this case and we aren't able to get the user data.

如您所见,在这种情况下会遇到错误情况,因此我们无法获取用户数据。

结语 (Wrapping Up)

In this tutorial we have seen how we can authenticate our AngularJS and Laravel applications with JSON Web Tokens. We secured our API with jwt-auth and setup middleware so that the user data only gets returned if the token is present. We then used Satellizer to set the user's token in local storage and to add it to the Authorization header of every subsequent request to the API.

在本教程中,我们看到了如何使用JSON Web令牌对AngularJS和Laravel应用程序进行身份验证。 我们使用jwt-auth和设置中间件保护了我们的API,以便仅在存在令牌的情况下才返回用户数据。 然后,我们使用Satellizer在本地存储中设置用户的令牌,并将其添加到对API的每个后续请求的Authorization标头中。

There are a few other important things necessary for a full authentication setup that we didn't look at in this tutorial, including:

完整的身份验证设置还需要其他一些重要的事情,我们在本教程中没有提到,包括:

  • Setting the logged-in user's data (such as name and email address) and their authentication status in local storage or on $rootScope so that we can pass their information around from state to state

    在本地存储或$rootScope设置登录用户的数据(例如姓名和电子邮件地址)及其身份验证状态,以便我们可以在各个州之间传递其信息
  • A way to redirect the user to the login state if they become logged out somehow (for example, if the token expires)

    如果用户以某种方式注销(例如,令牌过期),则将用户重定向到登录状态的方法
  • How to log the user out and the implications of token-based authentication on logout

    如何注销用户以及注销时基于令牌的身份验证的含义

To dive into these additional authentication aspects, head over to my site where we'll continue Token-Based Authentication for AngularJS and Laravel Apps!

要深入研究其他身份验证方面,请转到我的网站,我们将继续针对AngularJS和Laravel Apps进行基于令牌的身份验证

给我留言! (Drop Me a Line!)

If you’d like to get more AngularJS and Laravel tutorials, feel free to head over to my website and signup for my mailing list. You should follow me on Twitter---I'd love to hear about what you're working on!

如果您想获得更多AngularJS和Laravel教程,请随时访问我的网站注册我的邮件列表 。 您应该在Twitter上关注我---我很想知道您在做什么!

翻译自: https://scotch.io/tutorials/token-based-authentication-for-angularjs-and-laravel-apps

令牌提交的身份验证失败

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值