我在后端使用symfony,在前端使用角度js 1.6进行身份验证,但现在我发送错误时发送错误状态401(无效凭据)..我使用jwtauthentificationBundle生成令牌..我在localStorage中添加令牌拦截器,但是当我点击页面中的任何按钮时,你会发现服务拦截器......
config.yml:
imports:
- { resource: parameters.yml }
- { resource: security.yml }
- { resource: services.yml }
- { resource: "@MedBundle/Resources/config/services.yml" }
# Put parameters here that don't need to change on each machine where the app is deployed
# https://symfony.com/doc/current/best_practices/configuration.html#application-related-configuration
parameters:
locale: en
framework:
secret: "%secret%"
csrf_protection: ~
form: ~
session:
handler_id: ~
fos_user:
db_driver: orm
firewall_name: main
user_class: AppBundle\Entity\User
from_email:
address: "test@test.com"
sender_name: "Demo String"
service:
mailer: fos_user.mailer.twig_swift
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%
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:
'^/': ~
# Doctrine Configuration
doctrine:
dbal:
driver: pdo_mysql
host: '%database_host%'
port: '%database_port%'
dbname: '%database_name%'
user: '%database_user%'
password: '%database_password%'
charset: UTF8
# if using pdo_sqlite as your database driver:
# 1. add the path in parameters.yml
# e.g. database_path: '%kernel.root_dir%/data/data.db3'
# 2. Uncomment database_path in parameters.yml.dist
# 3. Uncomment next line:
#path: '%database_path%'
orm:
auto_generate_proxy_classes: '%kernel.debug%'
naming_strategy: doctrine.orm.naming_strategy.underscore
auto_mapping: true
# Swiftmailer Configuration
swiftmailer:
transport: '%mailer_transport%'
host: '%mailer_host%'
username: '%mailer_user%'
password: '%mailer_password%'
spool: { type: memory }
fos_rest:
view:
view_response_listener: 'force'
formats:
json: true
format_listener:
rules:
- { path: '^/api', priorities: ['json'], fallback_format: json, prefer_extension: true }
- { path: '^/', stop: true }
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
login:
pattern: ^/api/login
stateless: true
anonymous: true
form_login:
check_path: /api/login_check
success_handler: lexik_jwt_authentication.handler.authentication_success
failure_handler: lexik_jwt_authentication.handler.authentication_failure
require_previous_session: 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/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/api/register, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/api, role: IS_AUTHENTICATED_FULLY }
app.js:
var app = angular.module("myApp", ["ngRoute","ngStorage"]);
app.config(['$routeProvider','$httpProvider', function($routeProvider,$httpProvider) {
$routeProvider
.when("/login", {
templateUrl: Routing.generate('login',
{template:"default/login.html.twig"}),
controller: 'loginctrl',
})
.when("/register", {
templateUrl: Routing.generate('register',
{template:"default/registere.html.twig"}),
controller: 'httpgetctrl',
})
.when("/affiche", {
templateUrl: Routing.generate('get',
{template:"default/affiche.html.twig"}),
controller: 'httpgetctrl',
});
$httpProvider.interceptors.push('authInterceptor');
}]);
app.controller("httpgetctrl", function ($scope, $http) {
$scope.SendData = function () {
// use $.param jQuery function to serialize data from JSON
var data = $.param({
username: $scope.username,
email: $scope.email,
pass: $scope.password,
confir: $scope.confirmationpass
});
var config = {
headers : {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
}
}
$http.post(Routing.generate('register'), data, config)
.then(function (response) {
console.log("success");
})
.catch(function() {
console.log("error");
})
};
});
app.controller("loginctrl", function ($scope, $http,$localStorage) {
$scope.login = function () {
// use $.param jQuery function to serialize data from JSON
var data = $.param({
username: $scope.user,
password: $scope.pass
});
var config = {
headers : {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
}
}
$http.post(Routing.generate('login'), data, config)
.then(function (response) {
console.log("success login");
localStorage.token = response.data['token'] ;
console.log(localStorage.token);
})
.catch(function() {
console.log("error login");
})
};
});
app.factory('authInterceptor', function($rootScope, $q, $window) {
return {
request: function (config) {
config.headers = config.headers || {};
if (localStorage.token) {
//config.headers.Authorization = 'Bearer ' + localStorage.token;
config.headers['x-access-token'] = localStorage.token;
console.log('done');
}
return config;
},
response: function (response) {
if (response.status === 401) {
// if 401 unauthenticated
console.log("error 401");
}
return response || $q.when(response);
}
};
// call the factory ...
})
index.html.twig:
{% extends 'base.html.twig' %}
{% block title %} Acceuil {% endblock %}
{% block stylesheets %}<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootswatch/3.3.7/cerulean/bootstrap.min.css">
<style>
a {
text-decoration:none;
color: #e74c3c;
margin-right: 25px;
}
</style>
{% endblock %}
{% block body %}
<div class="container" ng-app="myApp">
<a href="#/!">Acceuil</a>
<a href="#!login">Login</a>
<a href="#!register">Register</a>
<a href="#!affiche">Affiche</a>
<br><br>
<div ng-view></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.5/angular-route.js"></script>
<script src="angularJwt.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/ngstorage/0.3.6/ngStorage.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/todc-bootstrap/3.3.7-3.3.13/js/bootstrap.min.js"></script>
<script type="text/javascript" src="{{ asset('bundles/fosjsrouting/js/router.js') }}"></script>
<script type="text/javascript" src="{{ path('fos_js_routing_js', {"callback": "fos.Router.setData"}) }}"></script>
<script type="text/javascript" src="{{ asset('bundles/fosjsrouting/js/app.js') }}"></script>
<script>
</script>
</div>
{% endblock %}
和代码控制器:
<?php
namespace MedBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use FOS\RestBundle\Controller\Annotations\RouteResource;
use Symfony\Component\HttpFoundation\JsonResponse;
use FOS\RestBundle\View\ViewHandler;
use FOS\RestBundle\View\View;
use MedBundle\Entity\Med;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\HttpFoundation\Response;
use AppBundle\EventListener\JWTCreatedlistener;
Class ApiController extends Controller {
public function getAction() {
$em = $this->getDoctrine()->getManager();
$test = $em->getRepository('MedBundle:Med')->findAll();
//$viewHandler = $this->get('fos_rest.view_handler');
// Création d'une vue FOSRestBundle
//$view = View::create($test);
//$view->setFormat('json');
// Gestion de la réponse
//return $viewHandler->handle($view);
return array('test'=>$test);
}
public function loginAction() {
$em = $this->getDoctrine()->getManager();
$request = $this->getRequest();
$test = null; $token = null; $res = 'null';
if ($request->getMethod() == 'POST') {
$username = $request->request->get('username');
$password = $request->request->get('password');
$test = $em->getRepository('MedBundle:Med')->findOneBy(array('username' => $username));
if (!($test)) { $res = "error"; } else{
$salt= $test->getSalt();
$pass = crypt($password,$salt);
if ( $pass !== $test->getPassword() ) { $res='error password'; } else {
$res='success';
$token = $this->get('lexik_jwt_authentication.jwt_manager')->create($test);
$test->setToken($token);
$em->persist($test);
$em->flush();
} }
//return new Response($res);
$test = [];
$test['token'] = $token;
$test['res'] = $res;
return new JsonResponse($test);
}
return $this->render('default/login.html.twig',array('test' => json_encode($test), 'token' => $token,'res' => json_encode($res)));
}
public function logoutAction() {
}
}