我有一个reactjs项目(在端口3000上运行),一个带Spring的JAVA API REST(在8080上运行),我必须将其配置为与OpenID服务器一起使用。
我可以从前端项目(使用Implicit Flow)登录OpenId,但如果我尝试访问API,这会抛出302并尝试重定向到Auth的登录页面服务器
我在API中安装了pac4。
如何向API发送内容以及如何配置API以验证此令牌?因为现在,API正在回答一个302到OpenId的登录页面。
我的问题的想法是知道我是否可以做以下事情:
1-从节点服务器登录OpenId。
2-将id_token发送到API Rest
3- API REST验证此令牌(我认为是针对OpenId服务器)
4-如果令牌有效,请退回请愿书。
谢谢!
答案 0 :(得分:0)
好的,我看到很多人有同样的问题或疑问,所以我会发布我的解决方案。
我用于前端项目的openId javascript客户端帐户。你需要要求“令牌id_token”。这意味着它将检索回调中的access_token。
使用此access_token,您可以点击API。 我使用了HeaderClient(pac4j库),并将标题中的access_token作为“授权”发送:“Bearer ...”。
在API中我创建了一个拦截器并添加了以下验证:
final HeaderClient headerClient = new HeaderClient("Authorization", "Bearer " , (credentials, ctx) -> {
final String token = ((TokenCredentials) credentials).getToken();
JWSAlgorithm jwsAlg = JWSAlgorithm.RS256;
try {
URL jwkSetURL = new URL(authority + jwks);
try {
if (CommonHelper.isNotBlank(token)) {
// Set up a JWT processor to parse the tokens and then check their signature
// and validity time window (bounded by the "iat", "nbf" and "exp" claims)
ConfigurableJWTProcessor jwtProcessor = new DefaultJWTProcessor();
// The public RSA keys to validate the signatures will be sourced from the
// OAuth 2.0 server's JWK set, published at a well-known URL. The RemoteJWKSet
// object caches the retrieved keys to speed up subsequent look-ups and can
// also gracefully handle key-rollover
JWKSource keySource = new RemoteJWKSet(jwkSetURL , new DefaultResourceRetriever() );
// Configure the JWT processor with a key selector to feed matching public
// RSA keys sourced from the JWK set URL
JWSKeySelector keySelector = new JWSVerificationKeySelector(jwsAlg, keySource);
jwtProcessor.setJWSKeySelector(keySelector);
// Process the token
JWTClaimsSet claimsSet = jwtProcessor.process(token, null);
// Print out the token claims set
if (claimsSet != null) {
CommonProfile profile = new CommonProfile();
profile.setId(token);
// save in the credentials to be passed to the default AuthenticatorProfileCreator
credentials.setUserProfile(profile);
}
}
} catch (BadJOSEException e) {
System.out.println("Invalid Authorization token");
} catch (JOSEException e) {
System.out.println("Error on Authorization token");
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
});