SparkJava:如何在 before() 过滤器中验证 OAuth 令牌?



我有一个用Spark-java(不是Apache Spark(编写的非常简单的Web服务器,并希望从初始请求中收集Auth令牌并将其发送到辅助URL,以便根据我公司的身份验证数据库进行身份验证。我已经浏览了文档,但不确定如何完成此操作。我还需要知道如何为对身份验证服务器的请求设置查询参数。下面是我的代码:

/*
* This Java source file was generated by the Gradle 'init' task.
*/
package c2c_server;
import static spark.Spark.*;
public class HelloWorld {
public static void main(String[] args) {
before((before_req, before_res) -> {
System.out.println("I'm in before");
String token = before_req.headers("Authorization");
// No token, reject
if (token == null) {
halt(401, "Unauthorized");
}
else if (token != null) {
System.out.println("Token is : " + token);
String url = "https://my-auth-url";
}
});
get("/command/:command", (req, res) -> {
System.out.println("You sent the command: " + req.params(":command") + " and the headers: " + req.headers());
if (req.params(":command").equals("run")) {
res.status(200);
return "You'll run the Java app to push data to S3!";
}
else {
res.status(400);
return "I don't understand that command";
}
});
System.out.println("Server listening");
}
}

从一些研究来看,JavaSpark项目似乎没有办法自己做到这一点。我需要利用 Apache HttpClient 库来提供这段代码来处理第二个请求来验证令牌:

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import org.apache.http.impl.client.HttpClients;
private static boolean IsAuthenticated(final String environment, final String token) throws Exception {
String url = "";
if (environment.equalsIgnoreCase("DEV")) {
url = "https://dev-oauth2-internal.com/validate/AppIdClaimsTrust";
}
else if (environment.equalsIgnoreCase("QA")) {
url = "https://qa-oauth2-internal.com/validate/AppIdClaimsTrust";
}
else if (environment.equalsIgnoreCase("PROD")) {
url = "https://oauth2-internal.com/validate/AppIdClaimsTrust";
}
else {
throw new Exception("Environment not supported");
}
HttpGet request = new HttpGet(url + "?token=" + token);
try (CloseableHttpResponse response = httpClient.execute(request)) {
int statusCode = response.getStatusLine().getStatusCode();
return (statusCode == 200);
}

最新更新