【问题标题】:Design pattern for using Auth Tokens?使用 Auth Tokens 的设计模式?
【发布时间】:2014-04-12 12:51:10
【问题描述】:

我是一名客户端开发人员,正在转向服务器端开发。 我遇到的一个常见问题是需要进行一次 API 调用(比如获取身份验证令牌),然后进行后续 API 调用以获取我想要的数据。有时,我需要为数据连续进行两次 API 调用,同时也没有身份验证令牌。

是否有通用的设计模式或 Java 库来解决这个问题?还是每次需要手动创建调用字符串?

编辑:我希望看起来像这样

CustomClassBasedOnJson myStuff = callAPI("url", getResponse("authURL"));

这将使用从“authURL”接收的数据调用“url”。 这里的重点是我正在串接多个 url 调用,使用一个调用的结果来定义下一个。

【问题讨论】:

  • 我不明白你的问题是什么。如果您想要 oauth 库,请搜索 scribe 或其 fork subscribe。
  • @LeosLiterak 我正在寻找更通用的东西。除非oauth库可以用于非oauth场景?
  • 没有。从各个提供者那里获取访​​问令牌只是帮手
  • 是什么阻止你做你想做的事?问题出在哪里?
  • @JBNizet 我不知道从哪里开始。我已经习惯于使用预先存在的 Oauth 或 Facebook 等库,这些库在幕后做了这类事情。

标签: java restful-authentication


【解决方案1】:

在做服务器端编程时,同步调用HTTP调用是可以接受的。

因此,正确的模式是简单地进行第一次调用,接收结果,然后在下一行中使用它。除非在 http 调用之间发生主要处理,否则无需将调用分离到单独的线程或异步调用中。

例如:

 JsonResponseEntry getJsonReportResponse() throws IOException {
         String sReportURL = "https://someurl.com/v2/report/report?" +
                 "startts=" + getDateYesterday("ts") +
                 "&endts=" + getDateNow("ts") +
                 "&auth=" + getAuthCode();

         URL reportURL = new URL(sReportURL);
         URLConnection conn = reportURL.openConnection();
         BufferedReader buf = new BufferedReader(new InputStreamReader(conn.getInputStream()));
         ObjectMapper mapper = new ObjectMapper();
        JsonNode reportResult = mapper.readTree(buf);
         return convertJSonNodeToJsonResponseEntry(reportResult);
    }

    String getAuthCode() throws IOException {
        String sReportURL = "https://someurl.com/auth";
        URL reportURL = new URL(sReportURL);

        HttpURLConnection conn = (HttpURLConnection) reportURL.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.connect();

        String urlParameters = "username=myUserName&password=mypassword";
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();
        BufferedReader buf = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        ObjectMapper mapper = new ObjectMapper();
        AuthResponse response = mapper.readValue(buf, AuthResponse.class);
        return response.toString();
    }

getAuthCode() 函数在需要响应的 URL 调用中同步调用。

【讨论】:

    猜你喜欢
    • 2011-12-31
    • 1970-01-01
    • 2012-11-13
    • 1970-01-01
    • 2012-08-12
    • 2011-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多