我正在开发一个项目,该项目有一个使用 symfony2 作为 Angular2 中的后端和前端应用程序构建的 API。当我尝试向后端发送获取请求时登录并获取令牌后,此问题发生
在 TokenStorage 中找不到 Token
我的后端在在线服务器上,我的前端应用程序在本地主机上运行。我还提到,如果我使用邮递员,一切正常。
后端设置
#nelmioCorsBundle configuration IN CONFIG.YML
nelmio_cors:
defaults:
allow_credentials: true
allow_origin: '*'
allow_headers: ['accept', 'content-type', 'authorization', 'x-http-method-override']
allow_methods: ['POST', 'PUT', 'PATCH', 'GET', 'DELETE']
max_age: 3600
paths:
'^/':
allow_origin: ['http://localhost:4201']
allow_headers: ['Authorization', 'X-Requested-With', 'Content-Type', 'Accept', 'Origin', 'X-Custom-Auth']
allow_methods: ['POST', 'PUT', 'GET', 'DELETE', 'OPTIONS']
max_age: 3600
hosts: []
origin_regex: false
hosts: ['^\.']
后端设置安全.YML
firewalls:
login:
pattern: ^/login
form_login:
provider: fos_userbundle
login_path: /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
api:
pattern: ^/
anonymous: false
provider: fos_userbundle
lexik_jwt: #par defaut check token in Authorization Header prefixer par Bearer
authorization_header: # check token in Authorization Header
enabled: true
prefix: Bearer
name: Authorization
cookie: # check token in a cookie
enabled: false
name: BEARER
query_parameter: # check token in query string parameter
enabled: true
name: bearer
throw_exceptions: true # When an authentication failure occurs, return a 401 response immediately
create_entry_point: false # When no authentication details are provided, create a default entry point that returns a 401 response
authentication_provider: lexik_jwt_authentication.security.authentication.provider
authentication_listener: lexik_jwt_authentication.security.authentication.listener
前端服务调用 API
constructor(private http: HttpClient) {
this.postUrlCommandes='myBackend_Url_Command';
let my_token = localStorage.getItem('id_token');
this.headers = new Headers();
this.headers.append("Access-Control-Allow-Origin", "*");
this.headers.append('Content-Type', 'application/json');
this.headers.append("Access-Control-Allow-Credentials", "true");
this.headers.append('Accept', 'application/json');
this.headers.append("Authorization", 'Bearer ' +my_token);
this.options = new RequestOptions({headers: this.headers});
}
// method for get all comand
getListcommandes(idcommande: number): Observable<Commande[]> {
let myParams= new URLSearchParams();
//myParams.append('id',idcommande);
const url=`${this.postUrlCommandes}/${idcommande}`;
return this.http.get(url,this.headers)
.map((response: Response) => {
console.log(" JE SUIS DANS LE SERVICE ");
var result = response.json();
console.log("je suis longmene resultat"+JSON.stringify(result['mes_commandes']));
return result;
});
// .map(this.parseData)
// .catch(this.handleError);
}