我按照教程发现here创建了一个JWT令牌来访问JIRA的REST API。在没有传递/rest/api/2/project
和/rest/api/2/issue/ISSUE-KEY
之类的查询字符串的情况下访问端点没有任何问题,但在尝试传递查询字符串时我得到401 Unauthorized
,比如/rest/api/2/user/assignable/search?project=PROJECT-KEY
我猜测我错过了某些内容,特别是规范网址的生成,
以下是生成get请求和JWT令牌的代码:
@Override
public CloseableHttpResponse get(String url) throws HttpException,
IOException, NoSuchAlgorithmException, ParseException,
JOSEException {
CloseableHttpClient client = HttpClientBuilder.create()
.setUserAgent("Kevin 6.9").build();
String token = createToken(url, JIRAClient.Method.GET);
HttpGet method = new HttpGet(jwt.getBaseUrl() + url);
method.setHeader("Authorization", "JWT " + token);
return client.execute(method);
}
/**
* Create JWT token
*
* @return
* @throws UnsupportedEncodingException
* @throws NoSuchAlgorithmException
*/
private String createToken(String apiPath, JIRAClient.Method method)
throws UnsupportedEncodingException, NoSuchAlgorithmException {
long issuedAt = System.currentTimeMillis() / 1000L;
long expiresAt = issuedAt + 1000L;
String httpMethod = method.toString();
System.out.println(httpMethod);
String contextPath = "/jira";
JwtJsonBuilder jwtBuilder = new JsonSmartJwtJsonBuilder()
.issuedAt(issuedAt).expirationTime(expiresAt)
.issuer(jwt.getKey());
HashMap<String, String[]> parameters = new HashMap<String, String[]>();
CanonicalHttpUriRequest canonical = new CanonicalHttpUriRequest(
httpMethod, apiPath, contextPath, parameters);
System.out.println("Canonical : " + canonical.getRelativePath());
JwtClaimsBuilder.appendHttpRequestClaims(jwtBuilder, canonical);
JwtWriterFactory jwtWriterFactory = new NimbusJwtWriterFactory();
String jwtbuilt = jwtBuilder.build();
String jwtToken = jwtWriterFactory.macSigningWriter(
SigningAlgorithm.HS256, jwt.getSharedSecret()).jsonToJwt(
jwtbuilt);
return jwtToken;
}
请注意,我将空HashMap<String, String[]>
传递给CanonicalHttpUriRequest
...这是正确的吗?
答案 0 :(得分:0)
显然,Map<String, String[]>
需要生成适当的规范URI。
请注意,我将空
HashMap<String, String[]>
传递给。{CanonicalHttpUriRequest
......这是对的吗?
我修改了方法签名,因此我可以将其作为参数传递。注意:createQueryString
是我的类中的一个方法,它从参数映射中手动创建查询字符串。
@Override
public CloseableHttpResponse get(String url,
@SuppressWarnings("rawtypes") Map parameters) throws Exception {
CloseableHttpClient client = HttpClientBuilder.create()
.setUserAgent("Kevin 5.0").build();
String token = createToken(url, JIRAClient.Method.GET, parameters);
HttpGet method = new HttpGet(jwt.getBaseUrl() + url
+ createQueryString(parameters));
method.setHeader("Authorization", "JWT " + token);
return client.execute(method);
}
它有效。
@Test
public void testJQL() throws Exception {
HashMap param = new HashMap();
param.put("jql", new String[] {"project=COR"});
param.put("startAt", new String[] {"0"});
HttpResponse response = client.get("/rest/api/2/search", param);
Assert.assertTrue(response.getStatusLine().getStatusCode() == 200);
}