How to handle file downloads with JWT based authentication?

前端 未结 5 740
北荒
北荒 2020-12-07 07:24

I\'m writing a webapp in Angular where authentication is handled by a JWT token, meaning that every request has an \"Authentication\" header with all the necessary informati

5条回答
  •  情书的邮戳
    2020-12-07 08:22

    Technique

    Based on this advice of Matias Woloski from Auth0, known JWT evangelist, I solved it by generating a signed request with Hawk.

    Quoting Woloski:

    The way you solve this is by generating a signed request like AWS does, for example.

    Here you have an example of this technique, used for activation links.

    backend

    I created an API to sign my download urls:

    Request:

    POST /api/sign
    Content-Type: application/json
    Authorization: Bearer...
    {"url": "https://path.to/protected.file"}
    

    Response:

    {"url": "https://path.to/protected.file?bewit=NTUzMDYzZTQ2NDYxNzQwMGFlMDMwMDAwXDE0NTU2MzU5OThcZDBIeEplRHJLVVFRWTY0OWFFZUVEaGpMOWJlVTk2czA0cmN6UU4zZndTOD1c"}
    

    With a signed URL, we can get the file

    Request:

    GET https://path.to/protected.file?bewit=NTUzMDYzZTQ2NDYxNzQwMGFlMDMwMDAwXDE0NTU2MzU5OThcZDBIeEplRHJLVVFRWTY0OWFFZUVEaGpMOWJlVTk2czA0cmN6UU4zZndTOD1c
    

    Response:

    Content-Type: multipart/mixed; charset="UTF-8"
    Content-Disposition': attachment; filename=protected.file
    {BLOB}
    

    frontend (by jojoyuji)

    This way you can do it all on a single user click:

    function clickedOnDownloadButton() {
    
      postToSignWithAuthorizationHeader({
        url: 'https://path.to/protected.file'
      }).then(function(signed) {
        window.location = signed.url;
      });
    
    }
    

提交回复
热议问题