Laravel - Send api_token within the header

后端 未结 2 1621
后悔当初
后悔当初 2021-01-06 11:32

I\'m building an API for Laravel and I want to send the api_token within the header instead of the form post. Is this something that is already built in or would I have to g

相关标签:
2条回答
  • 2021-01-06 12:11

    After struggling a little with this myself I got it working. You need to first follow this little tutorial on how to use the api_token for your laravel API: https://gistlog.co/JacobBennett/090369fbab0b31130b51

    Then once you have the api_token in the users table etc you can now pass this in the header of each request.

    My laravel is using the Vueify templates, ie I have under /components/Comment.vue etc files.

    First step is to pass the users api_token to the Vue Template by passing a property through the component definition in your blade template:

    <comments id_token="{{ access()->user()->api_token }}"></comments>
    

    Then ensure in your .vue file that you accept the property by adding it to the "props":

    export default {
        data: function() {
            return {
                edit: false,
                list: [],
                comment: {
                    id: '',
                    name: '',
                    body: ''
                }
            };
        },
    
        props: ['id_token'],
    
        created: function() {
            Vue.http.headers.common['Authorization'] = 'Bearer ' + this.id_token;
    
            this.fetchCommentList();
        },
    

    Notice above that I also added the token to the common headers in order to have it go through each request used in all the methods further down.

    Vue.http.headers.common['Authorization'] = 'Bearer ' + this.id_token;
    
    0 讨论(0)
  • 2021-01-06 12:13

    If you are consuming your API, you don't need to create an auth driver, you need to make requests to your API endpoints. Choose the method you prefer, and make requests, don't think as the same way when you use the auth driver at a webpage.

    This is an example how send the $token through the headers. With cURL and Guzzle

    $data = [
        'value1' => 'value1',
        'value2' => 'value2'
    ];
    

    With CURL

    $headers = [
        'Authorization: Bearer '.$token
    ];
    
    $ch2 = curl_init();
    curl_setopt($ch2, CURLOPT_URL, 'http://api.domain.com/endpoint');
    curl_setopt($ch2, CURLOPT_POST, 1);
    curl_setopt($ch2, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch2, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec ($ch2);
    curl_close ($ch2);
    

    With Guzzle

    $headers = [
        'Authorization' => 'Bearer '.$token
    ];
    
    $client = new GuzzleHttp\Client();
    $res = $client->request('POST', 'http://api.domain.com/endpoint',[
               'form_params'   => $data,
               'headers'       => $headers,
    ]);
    

    I hope this helps!

    0 讨论(0)
提交回复
热议问题