我的授权客户端:角,资源服务器: Java,授权服务器: Azure Active
我正在使用oAuth2通过角通过PKCE授权流登录,然后将令牌传递到后端。我能够通过授权Beaer头访问后端的令牌,但是当我使用该令牌访问Microsoft时,我将得到一个无效的令牌异常。
com.microsoft.graph.http.GraphServiceException:错误代码: InvalidAuthenticationToken错误消息: CompactToken解析失败,错误代码: 80049217
我不知道它为什么会导致这个错误,因为它是有效的,我可以通过https://jwt.io/验证,并使用令牌访问postman中的其他受保护的api。
AuthProvider.java
public class AuthProvider implements IAuthenticationProvider {
private String accessToken = null;
public AuthProvider(String accessToken) {
this.accessToken = accessToken;
}
@Override
public void authenticateRequest(IHttpRequest request) {
// Add the access token in the Authorization header
request.addHeader("Authorization", "Bearer " + accessToken);
}
}SecurityConfiguration.java
http.cors().and()
.authorizeRequests().antMatchers("/home").permitAll()
.and()
.authorizeRequests().antMatchers("/actuator/health").permitAll()
.and()
.authorizeRequests().antMatchers("/**").authenticated()
.and()
.oauth2ResourceServer().jwt();GraphAPIController.java
private static IGraphServiceClient graphClient = null;
private static AuthProvider authProvider = null;
private static void ensureGraphClient(String accessToken) {
if (graphClient == null) {
// Create the auth provider
authProvider = new AuthProvider(accessToken);
// Create default logger to only log errors
DefaultLogger logger = new DefaultLogger();
logger.setLoggingLevel(LoggerLevel.ERROR);
// Build a Graph client
graphClient = GraphServiceClient
.builder()
.authenticationProvider(authProvider)
.logger(logger)
.buildClient();
}
}
@GetMapping("/getUser")
public static User getUser(@RequestHeader(value="Authorization") String token) {
System.out.println("THE TOKEN: " +token);
ensureGraphClient(token);
// GET /me to get authenticated user
User me = graphClient
.me()
.buildRequest()
.get();
System.out.println("THE USER: " + me);
return me;
}我的角度设置:

app.module:从“角-OAuth2-oidc”导入{ OAuthModule };

app.component.ts

邮差:

发布于 2020-12-16 01:53:31
访问令牌只能用于一个资源。我可以看到,您在角度设置中配置了scope: 'openid api://{appid}/app'。这意味着访问令牌用于此资源api://{appid}/app,而不是MicrosoftGraphhttps://graph.microsoft.com。这就是为什么您得到了InvalidAuthenticationToken错误。
因此,如果要在后端API中调用MicrosoftGraph,则需要考虑OAuth 2.0代表流。代表流的OAuth 2.0提供了应用程序调用服务/web的用例,而服务/web又需要调用另一个服务/web。
在您的例子中,后端API是web,Microsoft Graph是web。

一个示例供你参考。
https://stackoverflow.com/questions/65299734
复制相似问题