首页 > 解决方案 > 如何使用 Spring Boot for Azure B2C 获取 AccessToken

问题描述

再次明确地说,访问是通过 Azure B2C。这显然是一个很大的区别,因为有两种不同的访问方式。

我遵循了本指南:https ://docs.microsoft.com/en-us/azure/java/spring-framework/configure-spring-boot-starter-java-app-with-azure-active-directory-b2c-oidc

我之前尝试过其他指南,但这不适用于B2Chttps ://docs.microsoft.com/en-us/azure/java/spring-framework/configure-spring-boot-starter-java-app-with -azure 活动目录

身份验证工作正常。我被重定向到登录页面并在成功登录后被重定向回来。用户信息可以从OAuth2AuthenticationToken.

在浏览器中,我的应用程序有一个 JSESSIONID。

在同一个域上,我想使用 Vue.js 直接从应用程序前端使用一个 REST 服务。

所以我想我会向前端提供一个 AccessToken,它可以用来访问 REST API。

我搜索了一个比较简单的例子:https ://spring.io/blog/2018/03/06/using-spring-security-5-to-integrate-with-oauth-2-secured-services-such-as -facebook和github

但是当我尝试注入时OAuth2AuthorizedClientService

@RequestMapping(path = "/user")
public ResponseEntity<User> test(@NonNull final OAuth2AuthenticationToken token,
        @AuthenticationPrincipal(expression = "idToken") final OidcIdToken idToken, final
OAuth2AuthorizedClientService clientService) {
    LOG.debug("GET called on /api/user resource");
    LOG.debug("OidcIdToken: {}", idToken.getTokenValue());

    final OAuth2AuthorizedClient client = clientService
            .loadAuthorizedClient(token.getAuthorizedClientRegistrationId(), token.getName());

    LOG.debug("Access: {}", client.getAccessToken().getTokenValue());

访问时出现以下错误:

java.lang.NoSuchMethodException: org.springframework.security.oauth2.client.OAuth2AuthorizedClientService.<init>()
    at java.lang.Class.getConstructor0(Class.java:3082) ~[na:1.8.0_231]
    at java.lang.Class.getDeclaredConstructor(Class.java:2178) ~[na:1.8.0_231]
    at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.createAttribute(ModelAttributeMethodProcessor.java:216) ~[spring-web-5.2.3.RELEASE.jar:5.2.3.RELEASE]

有人可以将我推向正确的方向吗?

更新

这是我的错。从指南中我得到的印象OAuth2AuthorizedClientService可以通过该方法注入。
事实并非如此。仅当该类通过构造函数或直接注入时才有效@inject

现在我有我的访问令牌......

标签: javaspring-bootazure-active-directoryazure-ad-b2c

解决方案


OAuth2AuthorizedClientService 必须注入到类中,而不是作为方法参数。往上看...


推荐阅读