JHipster authentication using Postman and JWT

后端 未结 4 1373
星月不相逢
星月不相逢 2020-12-25 14:07

I\'d been using the Postman in-tab extension to tests calls to call JHipster resource API\'s and found that it worked great (JHipster setup to use OAuth2). I authenticated

4条回答
  •  猫巷女王i
    2020-12-25 14:47

    If you have deployed a single microservice and you want to test it in isolation you can configure Postman to build a JWT token using a pre-request script.

    1. Go to the application-dev.yml file generated by JHipster and grab the base64-secret value:
    security:
        authentication:
            jwt:
                # This token must be encoded using Base64 and be at least 256 bits long (you can type `openssl rand -base64 64` on your command line to generate a 512 bits one)
                base64-secret: N2Y2MmFkNzg2ZTI4NTZiZGEwMTZhYTAzOTBhMjgwMzlkMzU2MzRlZjJjZDA2MzQ0NGMxOGFlZThjOWY0MjkzNGVlOGE3ZjkxZGI5ZTQxOGY3MjEwNWUwYTUxMTUxODYxY2U4ZWMzZjVhMjg0NTZkNzlhNWUyMmEyNjQ5NzkxZmI=
    
    1. Put the value in a variable named jhipster_jwt_secret inside the Postman Environment.

    2. Configure your pre-request script (this is largely copied from a Gist):

    function base64url(source) {
        // Encode in classical base64
        encodedSource = CryptoJS.enc.Base64.stringify(source);
    
        // Remove padding equal characters
        encodedSource = encodedSource.replace(/=+$/, '');
    
        // Replace characters according to base64url specifications
        encodedSource = encodedSource.replace(/\+/g, '-');
        encodedSource = encodedSource.replace(/\//g, '_');
    
        return encodedSource;
    }
    
    var header = {
        "typ": "JWT",
        "alg": "HS256"
    };
    
    var payload = {
      "sub": "user",
      "auth": "role"
    };
    
    var secret = CryptoJS.enc.Base64.parse(postman.getEnvironmentVariable("jhipster_jwt_secret"));
    
    // encode header
    var stringifiedHeader = CryptoJS.enc.Utf8.parse(JSON.stringify(header));
    var encodedHeader = base64url(stringifiedHeader);
    
    // encode data
    var stringifiedPayload = CryptoJS.enc.Utf8.parse(JSON.stringify(payload));
    var encodedPayload = base64url(stringifiedPayload);
    
    // build token
    var token = encodedHeader + "." + encodedPayload;
    
    // sign token
    var signature = CryptoJS.HmacSHA256(token, secret);
    signature = base64url(signature);
    var signedToken = token + "." + signature;
    
    postman.setEnvironmentVariable("jwt_token", signedToken);
    
    1. Inside the Authorization tab select "Bearer token" and write {{jwt_token}} in the Token input field.

提交回复
热议问题