donlih2986 2016-02-01 10:31
浏览 54
已采纳

了解JWT和HTTP授权标头? (客户端:Angular,服务器:php)

My angular app sends login credentials to my php server using HTTP Post. I receive the creds and create my JWT token fine. I can send the JWT token back in the response body, save it on the client side and use it to create an Authorization header for all subsequent client requests. That's all fine.

What I want to do is send the newly created JWT token back to the client in an Authorization header and have my client save it from the header rather than the body. That way I can refresh my token as need be and it can be seamless on the client side.

Searching around, it seems like the Authorization header is set when sending requests to a server. In php there is the curl functions, but I'm not sure if that's the right direction.

Is it possible to create an Authorization header for an Http Post response?

  • 写回答

1条回答 默认 最新

  • dongzhuo3202 2016-02-04 10:40
    关注

    Thilo's comment is right. More so, in php you can create any response header you want by simply using the "header" function:

    <?php
    ... POST api, generate $token, etc...
    header('MyCustomHeader: Bearer'.$token);
    ... 
    echo $http_body_response
    ?>
    

    My issue was that in Chrome, I was looking for my headers in the console response when I should have been looking under the Network tab. The network tab shows all the headers attached to the http response.

    Note: I'm using angular2-beta and I can only access my custom header in Angular2 if I add another response header exposing it. Once I do this, the header does show in the console. Therefore:

    <?php
    header("Access-Control-Expose-Headers: MyCustomHeader");
    ... POST api, generate $token, etc...
    header('MyCustomHeader: Bearer'.$token);
    ... 
    echo $http_body_response
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?