简体   繁体   English

Symfony2 API和Angular2 / 4之间的CORS标头问题

[英]CORS Header issue between Symfony2 API and Angular2/4

I'am working on a project which has an API built with symfony2 as backend and front end app in Angular2. 我正在一个项目中,该项目具有使用symfony2作为Angular2的后端和前端应用程序构建的API。 After logging in and getting token when I try to sent get request to my backend this issue happend 登录并获取令牌后,当我尝试将get请求发送到后端时,发生了此问题

A Token was not found in the TokenStorage 在令牌存储中找不到令牌

My backend is on online server and my frontend app is run on localhost. 我的后端在联机服务器上,而我的前端应用程序在localhost上运行。 I also mention that everything works fine if I use postman. 我还提到如果使用邮递员,一切都可以正常工作。

BACKEND SETTING 后台设置

#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: ['^\.']

BACKEND SETTING SECURITY.YML 后端设置SECURITY.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

FRONT-END SERVICE calling API 前端服务调用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);

}

config.yml file config.yml文件

htpservice.ts htpservice.ts

HI this configuration working for me 嗨,这个配置对我有用

in config.yml 在config.yml中

nelmio_cors:
    paths:
        '^/':
            origin_regex: true
            allow_origin: ['*']
            allow_headers: ['Content-Type','Authorization']
            allow_methods: ['POST', 'PUT', 'GET', 'DELETE']
            max_age: 3600

angular api call 角度api调用

login(data, apiurl) {
    let headers = new Headers;
    headers.append("Content-Type", "application/json");
    let body = JSON.stringify(data);
    return this.http.post(apiurl, body, { headers: headers })
        .toPromise()
        .then((res: Response) => {
           console.log(res)
        })
        .catch(err=>
         {
         console.log(err)
    });
   }

the above configuration working for me in scenario 以上配置在场景中对我有用

 welcome(){
    let headers = new Headers();
    headers.append('Authorization', 'Token ' + localStorage.getItem('id_token'));
    this.http.post(apiUrl, {}, { headers: headers })
        .subscribe(
        data => {
            console.log(data)
         })
  }

your token name must be define in config.yml 您的令牌名称必须在config.yml中定义

allow_headers: ['Content-Type','Authorization'] allow_headers:['Content-Type','Authorization']

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:  ^/api/(_(profiler|wdt|doc))/
          security: false


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

        api:
           pattern:   ^/api
           stateless: true
           anonymous: false
           logout:       true
           provider: fos_userbundle
           guard:
               authenticators:
                    - app.jwt_token_authenticator

   access_control:
    - { path: ^/api/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/api, roles: IS_AUTHENTICATED_FULLY }

and do changes in config.yml 并在config.yml中进行更改

parameters:
    locale: en
    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: 'star123'
    jwt_token_ttl: 86400
nelmio_cors:
    paths:
        '^/':
            origin_regex: true
            allow_origin: ['*']
            allow_headers: ['Content-Type','Authorization']
            allow_methods: ['POST', 'PUT', 'GET', 'DELETE']
            max_age: 3600

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM