如何使用JWT令牌从android

时间:2015-09-15 13:09:54

标签: android authentication httpurlconnection jwt

到目前为止我做了什么

我正在尝试与具有自定义身份验证的Java Web应用程序进行通信。在这种情况下,我需要首先点击请求正文参数JSON类型的链接,以便在我的Cookie中获取JWT auth-token

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

对邮差测试:

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

  • 发布,网址:http://iitjeeacademy.com/iitjeeacademy/api/v1/login
  • 标题:Content-Type:application/json
  • 请求正文(原始):{"password":"123","type":"student","email":"shobhit@gmail.com"}

登录后使用以下方式获取回复:

  • 获取,网址:http://iitjeeacademy.com/iitjeeacademy/api/v1/student/me

存储在邮递员中的Cookie的屏幕截图: Postman screenshot of stored cookie

存储在Chrome中的Cookie的屏幕截图 enter image description here

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

“发布”方法,此连接用于获取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();
    }

“获取”方法,会话Cookie中必须有auth-token才能获得响应。 此方法提供401 Unauthorized Error。

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();
    }

问题: 如何使用HttpURLConnection android中的cookie存储的JWT令牌来获取Web服务的响应。

2 个答案:

答案 0 :(得分:8)

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

对于JWT身份验证,我发送格式为:

的HTTP请求标头
  

授权: Bearer jwtHeader.jwtPayload.jwtSignature

示例:

Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

规范和详细信息可在以下网址获得:https://jwt.io/introduction/

答案 1 :(得分:0)

以jaygeek的答案为基础(使用过度简化的JavaScript客户端示例设置Authorization标题和'Bearer'前缀):

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

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);