【问题标题】:How to send HTTP request using JWT token for authentication from cookie storage in android如何使用 JWT 令牌发送 HTTP 请求以从 android 中的 cookie 存储进行身份验证
【发布时间】:2015-09-15 13:09:54
【问题描述】:

到目前为止我做了什么

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

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

对于 Postman 测试:

用于登录并在 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

存储在 Postman 中的 cookie 的屏幕截图:

存储在 Chrome 中的 cookie 的屏幕截图

以下是我在 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();
    }

“获取”方法,会话 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();
    }

问题: 如何使用HttpURLConnectionandroid中cookies中存储的JWT Token来获取Web服务的响应。

【问题讨论】:

    标签: android authentication httpurlconnection jwt


    【解决方案1】:

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

    对于 JWT 身份验证,我会发送一个 HTTP 请求 header,格式为:

    授权:承载jwtHeader.jwtPayload.jwtSignature

    示例:

    Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2023-03-10
        • 2019-08-07
        • 1970-01-01
        • 2018-07-22
        • 2012-02-29
        • 2017-10-31
        • 2010-12-03
        • 2019-08-02
        • 1970-01-01
        相关资源
        最近更新 更多