Symfony2和Angular.用户认证

xge*_*86x 6 symfony angularjs

我正在开发一个涉及Symfony2和AngularJs的Web应用程序.我有一个关于在网站中验证用户身份的正确方法的问题.

我在我的API REST(内置Symfony)中构建了一个函数,它通过请求中传递的参数对用户进行身份验证.

/**
 * Hace el login de un usuario
 * 
 * @Rest\View()
 * @Rest\Post("/user/login")
 * @RequestParam(name="mail", nullable=false, description="user email")
 * @RequestParam(name="password", nullable=false, description="user password")
 */
public function userLoginAction(Request $request, ParamFetcher $paramFetcher) {
    $mail = $paramFetcher->get('mail');
    $password = $paramFetcher->get("password");
    $response = [];
    $userManager = $this->get('fos_user.user_manager');
    $factory = $this->get('security.encoder_factory');
    $user = $userManager->findUserByUsernameOrEmail($mail);          
    if (!$user) {
        $response = [
            'error' => 1,
            'data' => 'No existe ese usuario'
        ];
    } else {
        $encoder = $factory->getEncoder($user);
        $ok = ($encoder->isPasswordValid($user->getPassword(),$password,$user->getSalt()));

        if ($ok) {
            $token = new UsernamePasswordToken($user, null, "main", $user->getRoles());
            $this->get("security.context")->setToken($token);
            $event = new InteractiveLoginEvent($request, $token);
            $this->get("event_dispatcher")->dispatch("security.interactive_login", $event);
            if ($user->getType() == 'O4FUser') {
                $url = $this->generateUrl('user_homepage'); 
            } else {
                $url = $this->generateUrl('gym_user_homepage'); 
            }
            $response = [
                'url' => $url
            ];
        } else {
            $response = [
                'error' => 1,
                'data' => 'La contraseña no es correcta'
            ];
        }
    }
    return $response;
}
Run Code Online (Sandbox Code Playgroud)

如您所见,该函数设置了令牌,一切正常.

但昨天,我一直在阅读,最好使用无状态系统,使用像这个捆绑提供的JSON令牌:

https://github.com/lexik/LexikJWTAuthenticationBundle/blob/master/Resources/doc/index.md

所以我的问题是两种选择中的哪一种更好.

谢谢!

NoX*_*NoX 18

正如我最近做与Symfony2中和角认证实施,以及大量的研究后这样做我最终选择的最佳方式API平台(使用JSON-LD /水润新词汇提供REST的API,而不是FOSRest我假设你使用)和Angular前端应用程序的restangular.

对于无状态,这是一个更好的解决方案,但你必须建立你的登录场景,以选择最好的技术.

登录系统和JWT不兼容,可以使用这两种解决方案.在使用JWT之前,我使用OAuth进行了大量研究,显然很难实现并需要一个完整的开发团队.JWT提供了实现这一目标的最佳和简单方法.

您应该考虑首先使用FOSUser捆绑包,如@chalasr建议的那样.此外,使用Lexik的API-PlatformJWT Bundle,您将需要NelmioCors来显示应该出现的CrossDomain错误:

(仔细阅读本文档的文档)

HTTPS协议是强制在api和front之间进行通信的!

在以下示例代码中,我使用了特定的实体映射.联系实体得到了抽象的CommunicationWays,它有手机.我稍后会提供完整的映射和类示例.

适应您的需求.

# composer.json

// ...
    "require": {
        // ...
        "friendsofsymfony/user-bundle": "~2.0@dev",
        "lexik/jwt-authentication-bundle": "^1.4",
        "nelmio/cors-bundle": "~1.4",
        "dunglas/api-bundle": "~1.1@beta"
// ...


# app/AppKernel.php

    public function registerBundles()
    {
        $bundles = array(
            // ...
            new Symfony\Bundle\SecurityBundle\SecurityBundle(),
            new FOS\UserBundle\FOSUserBundle(),
            new Lexik\Bundle\JWTAuthenticationBundle\LexikJWTAuthenticationBundle(),
            new Nelmio\CorsBundle\NelmioCorsBundle(),
            new Dunglas\ApiBundle\DunglasApiBundle(),
            // ...
        );
Run Code Online (Sandbox Code Playgroud)

然后更新您的配置:

# app/config/config.yml

imports:
    // ...
    - { resource: security.yml }
// ...
framework:
    // ...
    csrf_protection: ~
    form: ~
    session:
        handler_id: ~
    // ...
fos_user:
    db_driver: orm
    firewall_name: main
    user_class: AppBundle\Entity\User
lexik_jwt_authentication:
    private_key_path: %jwt_private_key_path%
    public_key_path:  %jwt_public_key_path%
    pass_phrase:      %jwt_key_pass_phrase%
    token_ttl:        %jwt_token_ttl%
// ...
dunglas_api:
    title:       "%api_name%"
    description: "%api_description%"
    enable_fos_user: true
nelmio_cors:
    defaults:
        allow_origin:   ["%cors_allow_origin%"]
        allow_methods:  ["POST", "PUT", "GET", "DELETE", "OPTIONS"]
        allow_headers:  ["content-type", "authorization"]
        expose_headers: ["link"]
        max_age:       3600
    paths:
        '^/': ~
// ...
Run Code Online (Sandbox Code Playgroud)

和参数dist文件:

parameters:
    database_host:     127.0.0.1
    database_port:     ~
    database_name:     symfony
    database_user:     root
    database_password: ~
    # You should uncomment this if you want use pdo_sqlite
    # database_path: "%kernel.root_dir%/data.db3"

    mailer_transport:  smtp
    mailer_host:       127.0.0.1
    mailer_user:       ~
    mailer_password:   ~

    jwt_private_key_path: %kernel.root_dir%/var/jwt/private.pem
    jwt_public_key_path:  %kernel.root_dir%/var/jwt/public.pem
    jwt_key_pass_phrase : 'test'
    jwt_token_ttl:        86400

    cors_allow_origin: http://localhost:9000

    api_name:          Your API name
    api_description:   The full description of your API

    # A secret key that's used to generate certain security-related tokens
    secret: ThisTokenIsNotSecretSoChangeIt
Run Code Online (Sandbox Code Playgroud)

创建使用ORM yml文件扩展baseUser的用户类:

# src/AppBundle/Entity/User.php

<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use FOS\UserBundle\Model\User as BaseUser;

class User extends BaseUser
{
    protected $id;
    protected $username;
    protected $email;
    protected $plainPassword;
    protected $enabled;
    protected $roles;
}

# src/AppBundle/Resources/config/doctrine/User.orm.yml

AppBundle\Entity\User:
    type:  entity
    table: fos_user
    id:
        id:
            type: integer
            generator:
                strategy: AUTO
Run Code Online (Sandbox Code Playgroud)

然后把security.yml配置:

# app/config/security.yml

security:
    encoders:
        FOS\UserBundle\Model\UserInterface: bcrypt

    role_hierarchy:
        ROLE_ADMIN:       ROLE_USER
        ROLE_SUPER_ADMIN: ROLE_ADMIN

    providers:
        fos_userbundle:
            id: fos_user.user_provider.username

    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false

        api:
            pattern: ^/api
            stateless: true
            lexik_jwt:
                authorization_header:
                    enabled: true
                    prefix: Bearer
                query_parameter:
                    enabled: true
                    name: bearer
                throw_exceptions: false
                create_entry_point: true

        main:
            pattern: ^/
            provider: fos_userbundle
            stateless: true
            form_login: 
                check_path: /login_check
                username_parameter: username
                password_parameter: password
                success_handler: lexik_jwt_authentication.handler.authentication_success
                failure_handler: lexik_jwt_authentication.handler.authentication_failure
                require_previous_session: false
            logout: true
            anonymous: true


    access_control:
        - { path: ^/api, role: IS_AUTHENTICATED_FULLY }
Run Code Online (Sandbox Code Playgroud)

和services.yml:

# app/config/services.yml

services:
    // ...
    fos_user.doctrine_registry:
        alias: doctrine
Run Code Online (Sandbox Code Playgroud)

最后路由文件:

# app/config/routing.yml

api:
    resource: "."
    type:     "api"
    prefix: "/api"

api_login_check:
    path: "/login_check"
Run Code Online (Sandbox Code Playgroud)

此时,作曲家更新,使用doctrine控制台命令创建数据库/更新架构,创建fosuser用户并生成JWT Lexik捆绑包所需的SSL公共和私有文件(请参阅doc).

您应该能够(例如使用POSTMAN)立即发送api调用或使用对http:// your_vhost/login_check的发布请求生成令牌

我们通常在这里为Symfony api部分完成.做你的测试!

现在,如何从Angular处理api?

这是我们的场景:

  1. 通过登录表单,向Symfony login_check url发送POST请求,该请求将返回JSON Web令牌
  2. 将该令牌存储在session/localstorage中
  3. 将此存储的令牌传递给我们对标头进行的每个api调用并访问我们的数据

这是角度部分:

首先需要安装角度全局模块:

$ npm install -g yo generator-angular bower
$ npm install -g ruby sass compass less
$ npm install -g grunt-cli karma-cli jshint node-gyp registry-url
Run Code Online (Sandbox Code Playgroud)

使用yeoman启动角度安装:

$ yo angular
Run Code Online (Sandbox Code Playgroud)

回答问题:

  • ...... Gulp .................. ..没有
  • ...... Sass /指南针......是的
  • ...... Bootstrap ..........是的
  • ...... Bootstrap-Sass.是的

并取消选中所有其他要求的模块.

安装本地npm包:

$ npm install karma jasmine-core grunt-karma karma-jasmine --save-dev
$ npm install phantomjs phantomjs-prebuilt karma-phantomjs-launcher --save-dev
Run Code Online (Sandbox Code Playgroud)

最后是凉亭套餐:

$ bower install --save lodash#3.10.1
$ bower install --save restangular
Run Code Online (Sandbox Code Playgroud)

打开index.html文件并将其设置如下:

# app/index.html

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width">
    <link rel="stylesheet" href="styles/main.css">
  </head>
  <body ng-app="angularApp">
    <div class="container">
    <div ng-include="'views/main.html'" ng-controller="MainCtrl"></div>
    <div ui-view></div>

    <script src="bower_components/jquery/dist/jquery.js"></script>
    <script src="bower_components/angular/angular.js"></script>
    <script src="bower_components/bootstrap-sass-official/assets/javascripts/bootstrap.js"></script>

    <script src="bower_components/restangular/dist/restangular.js"></script>
    <script src="bower_components/lodash/lodash.js"></script>

    <script src="scripts/app.js"></script>
    <script src="scripts/controllers/main.js"></script>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

配置restangular:

# app/scripts/app.js

'use strict';

angular
    .module('angularApp', ['restangular'])
    .config(['RestangularProvider', function (RestangularProvider) {
        // URL ENDPOINT TO SET HERE !!!
        RestangularProvider.setBaseUrl('http://your_vhost/api');

        RestangularProvider.setRestangularFields({
            id: '@id'
        });
        RestangularProvider.setSelfLinkAbsoluteUrl(false);

        RestangularProvider.addResponseInterceptor(function (data, operation) {
            function populateHref(data) {
                if (data['@id']) {
                    data.href = data['@id'].substring(1);
                }
            }

            populateHref(data);

            if ('getList' === operation) {
                var collectionResponse = data['hydra:member'];
                collectionResponse.metadata = {};

                angular.forEach(data, function (value, key) {
                    if ('hydra:member' !== key) {
                        collectionResponse.metadata[key] = value;
                    }
                });

                angular.forEach(collectionResponse, function (value) {
                    populateHref(value);
                });

                return collectionResponse;
            }

            return data;
        });
    }])
;
Run Code Online (Sandbox Code Playgroud)

配置控制器:

# app/scripts/controllers/main.js

'use strict';

angular
    .module('angularApp')
    .controller('MainCtrl', function ($scope, $http, $window, Restangular) {
        // fosuser user
        $scope.user = {username: 'johndoe', password: 'test'};

        // var to display login success or related error
        $scope.message = '';

        // In my example, we got contacts and phones
        var contactApi = Restangular.all('contacts');
        var phoneApi = Restangular.all('telephones');

        // This function is launched when page is loaded or after login
        function loadContacts() {
            // get Contacts
            contactApi.getList().then(function (contacts) {
                $scope.contacts = contacts;
            });

            // get Phones (throught abstrat CommunicationWays alias moyensComm)
            phoneApi.getList().then(function (phone) {
                $scope.phone = phone;
            });

            // some vars set to default values
            $scope.newContact = {};
            $scope.newPhone = {};
            $scope.contactSuccess = false;
            $scope.phoneSuccess = false;
            $scope.contactErrorTitle = false;
            $scope.contactErrorDescription = false;
            $scope.phoneErrorTitle = false;
            $scope.phoneErrorDescription = false;

            // contactForm handling
            $scope.createContact = function (form) {
                contactApi.post($scope.newContact).then(function () {
                    // load contacts & phones when a contact is added
                    loadContacts();

                    // show success message
                    $scope.contactSuccess = true;
                    $scope.contactErrorTitle = false;
                    $scope.contactErrorDescription = false;

                    // re-init contact form
                    $scope.newContact = {};
                    form.$setPristine();

                    // manage error handling
                }, function (response) {
                    $scope.contactSuccess = false;
                    $scope.contactErrorTitle = response.data['hydra:title'];
                    $scope.contactErrorDescription = response.data['hydra:description'];
                });
            };

            // Exactly same thing as above, but for phones
            $scope.createPhone = function (form) {
                phoneApi.post($scope.newPhone).then(function () {
                    loadContacts();

                    $scope.phoneSuccess = true;
                    $scope.phoneErrorTitle = false;
                    $scope.phoneErrorDescription = false;

                    $scope.newPhone = {};
                    form.$setPristine();
                }, function (response) {
                    $scope.phoneSuccess = false;
                    $scope.phoneErrorTitle = response.data['hydra:title'];
                    $scope.phoneErrorDescription = response.data['hydra:description'];
                });
            };
        }

        // if a token exists in sessionStorage, we are authenticated !
        if ($window.sessionStorage.token) {
            $scope.isAuthenticated = true;
            loadContacts();
        }

        // login form management
        $scope.submit = function() {
            // login check url to get token
            $http({
                method: 'POST',
                url: 'http://your_vhost/login_check',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                data: $.param($scope.user)

                // with success, we store token to sessionStorage
            }).success(function(data) {
                $window.sessionStorage.token = data.token;
                $scope.message = 'Successful Authentication!';
                $scope.isAuthenticated = true;

                // ... and we load data
                loadContacts();

                // with error(s), we update message
            }).error(function() {
                $scope.message = 'Error: Invalid credentials';
                delete $window.sessionStorage.token;
                $scope.isAuthenticated = false;
            });
        };

        // logout management
        $scope.logout = function () {
            $scope.message = '';
            $scope.isAuthenticated = false;
            delete $window.sessionStorage.token;
        };

        // This factory intercepts every request and put token on headers
    }).factory('authInterceptor', function($rootScope, $q, $window) {
    return {
        request: function (config) {
            config.headers = config.headers || {};

            if ($window.sessionStorage.token) {
                config.headers.Authorization = 'Bearer ' + $window.sessionStorage.token;
            }
            return config;
        },
        response: function (response) {
            if (response.status === 401) {
                // if 401 unauthenticated
            }
            return response || $q.when(response);
        }
    };
// call the factory ...
}).config(function ($httpProvider) {
    $httpProvider.interceptors.push('authInterceptor');
});
Run Code Online (Sandbox Code Playgroud)

最后我们需要带有表单的main.html文件:

<!—Displays error or success messages-->
<span>{{message}}</span><br><br>

<!—Login/logout form-->
<form ng-show="!isAuthenticated" ng-submit="submit()">
    <label>Login Form:</label><br>
    <input ng-model="user.username" type="text" name="user" placeholder="Username" disabled="true" />
    <input ng-model="user.password" type="password" name="pass" placeholder="Password" disabled="true" />
    <input type="submit" value="Login" />
</form>
<div ng-show="isAuthenticated">
    <a ng-click="logout()" href="">Logout</a>
</div>
<div ui-view ng-show="isAuthenticated"></div>
<br><br>

<!—Displays contacts list-->
<h1 ng-show="isAuthenticated">Liste des Contacts</h1>
<article ng-repeat="contact in contacts" ng-show="isAuthenticated" id="{{ contact['@id'] }}" class="row marketing">
    <h2>{{ contact.nom }}</h2>
    <!—Displays contact phones list-->
    <h3 ng-repeat="moyenComm in contact.moyensComm">Tél : {{ moyenComm.numero }}</h3>
</article><hr>

<!—Create contact form-->
<form name="createContactForm" ng-submit="createContact(createContactForm)" ng-show="isAuthenticated" class="row marketing">
    <h2>Création d'un nouveau contact</h2>
    <!—Displays error / success message on creating contact-->
    <div ng-show="contactSuccess" class="alert alert-success" role="alert">Contact publié.</div>
    <div ng-show="contactErrorTitle" class="alert alert-danger" role="alert">
        <b>{{ contactErrorTitle }}</b><br>
        {{ contactErrorDescription }}
    </div>
    <div class="form-group">
        <input ng-model="newContact.nom" placeholder="Nom" class="form-control">
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
</form>

<!—Phone form-->
<form name="createPhoneForm" ng-submit="createPhone(createPhoneForm)" ng-show="isAuthenticated" class="row marketing">
    <h2>Création d'un nouveau téléphone</h2>
    <div ng-show="phoneSuccess" class="alert alert-success" role="alert">Téléphone publié.</div>
    <div ng-show="phoneErrorTitle" class="alert alert-danger" role="alert">
        <b>{{ phoneErrorTitle }}</b><br>
        {{ phoneErrorDescription }}
    </div>
    <div class="form-group">
        <input ng-model="newPhone.numero" placeholder="Numéro" class="form-control">
    </div>
    <div class="form-group">
        <label for="contact">Contact</label>
        <!—SelectBox de liste de contacts-->
        <select ng-model="newPhone.contact" ng-options="contact['@id'] as contact.nom for contact in contacts" id="contact"></select>
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
</form>
Run Code Online (Sandbox Code Playgroud)

好吧,我知道这是很多简洁的代码,但是你可以使用Symfony&Angular在这里启动完整的api系统.有一天我会发一篇博文来更清楚,并且有时会更新这篇文章.

我希望它有所帮助.

最好的祝福.