如何在安卓设备中使用JWT令牌从Cookie存储发送HTTP请求进行身份验证

7

我迄今为止做了什么:

我正在尝试与具有自定义身份验证的Java Web应用程序通信。其中,我需要先使用请求正文参数JSON类型点击一个链接,以在我的cookie中获取JWTauth-token

我在Postman中测试了连接,我收到了正确的JSON响应。但是当我在我的Android应用程序中尝试相同操作时,它返回Bad Request错误。

用于Postman测试:

用于登录并在cookie存储中获取auth-token:

  • Post,URL:http://iitjeeacademy.com/iitjeeacademy/api/v1/login
  • Headers: Content-Type:application/json
  • Request body (raw): {"password":"123","type":"student","email":"shobhit@gmail.com"}

登录后使用以下内容获取响应:

  • Get, URL: http://iitjeeacademy.com/iitjeeacademy/api/v1/student/me

在Postman中存储的cookie截图: Postman screenshot of stored cookie

在Chrome中存储的cookie截图: enter image description here

以下是我的Android中HttpURLConnection请求代码:

“Post”方法,此连接用于获取auth-token此方法返回200响应。

HttpURLConnection connection = null;
try {
        // Created URL for connection.
        URL url = new URL(link);

        // Input data setup
        byte[] postData = request.getBytes(StandardCharsets.UTF_8);
        int postDataLength = postData.length;

        // Created connection
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setInstanceFollowRedirects(false);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("charset", "utf-8");
        connection.setRequestProperty("Content-Length", Integer.toString(postDataLength));
        connection.setUseCaches(false);

        // loaded inputs
        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.write(postData);
        wr.flush();
        wr.close();

        // getting a response
        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK){
            // Read response
            response = convertToString(connection.getInputStream());
            return response;
        }else{
            // Read Error
            String response = connection.getResponseMessage();
            return response;
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
        Log.v("MalformedURL ---> ", e.getMessage());
    } catch (ProtocolException p) {
        p.printStackTrace();
        Log.v("Connection ---> ", p.getMessage());
    } catch (IOException i) {
        i.printStackTrace();
        Log.v("IO Exception ---> ", i.getMessage());
    } finally {
        connection.disconnect();
    }

"Get"方法,必须在会话cookie中具有auth-token才能获得响应。 该方法会返回401未经授权的错误。

HttpURLConnection connection = null;
try{
        // Created URL for connection
        URL url = new URL(link);

        // Created connection
        connection = (HttpURLConnection) url.openConnection();
        connection.setInstanceFollowRedirects(false);
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("charset", "utf-8");

        // getting a response
        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK){
            response = convertToString(connection.getInputStream());
            return response;
        }else{
            // Read Error
            String response = connection.getResponseMessage();
            return response;
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (ProtocolException p) {
        p.printStackTrace();
    } catch (IOException i) {
        i.printStackTrace();
    } finally {
        connection.disconnect();
    }

问题: 如何在 Android 中使用来自 Cookie 的存储 JWT Token,在 HttpURLConnection 中获取 Web 服务的响应。

2个回答

22

我确定你已经继续前进了,但是...

对于JWT身份验证,我将发送格式化为HTTP请求头的:

授权:Bearer jwtHeader.jwtPayload.jwtSignature

示例:

Authorization:Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

规范和详细信息可在此处找到:https://jwt.io/introduction/


4

在jaygeek的回答基础上(设置Authorization头和'Bearer'前缀),这是一个过度简化的JavaScript客户端示例:

localStorage.jwt = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ';

fetch('/api/example', {method: 'POST',
headers: {
   'Authorization':`Bearer ${localStorage.jwt}`,
   'Content-type':'application/json'
}, body: JSON.stringify({stuff:'things'})
})
.then(console.log).catch(console.error);

function jwtRequest(url, token){
    var req = new XMLHttpRequest();
    req.open('get', url, true);
    req.setRequestHeader('Authorization','Bearer '+token);
    req.send();
}

jwtRequest('/api/example', localStorage.jwt);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接