Bonjour,
J'ajoute token au localStorage et Interceptors mais je peux pas accéder à les pages qui sécurisé avec la token ..
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',
});
$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("test");
console.log(response.data.length);
$localStorage.token = response.data['token'] ;
console.log($localStorage.token);
})
.catch(function() {
console.log("error");
})
};
});
app.factory('authInterceptor', function($rootScope, $q, $window) {
return {
request: function (config) {
config.headers = config.headers || {};
if ($window.localStorage.token) {
config.headers.Authorization = 'Bearer ' + $window.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 ...
})
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 }
et controller:
<?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() {
}
}
maintenant quand il on peut accéder à la page https://localhost/authenti/web/app_dev.php/api/ .. je trouve message json de statut 401 (invalide token)
ou est l'erreur s'il vous plait
Héhé :D
Sinon, renseigne toi sur le code de statut de réponse HTTP 401 Unauthorized.
C'est un des statuts les plus parlant.