【发布时间】:2020-02-25 21:56:29
【问题描述】:
我正在使用带有 azure-active-directory-b2c-spring-boot-starter 2.2.0 的 Spring Boot 2.2.0。我设法用它保护了一个 Thymeleaf 网页(按照他们的教程)。现在,我想要一个以相同方式保护的 REST API,因为实际的应用程序将是一个移动应用程序,它对我的 Spring Boot 后端进行 REST 调用。
我已经想出了如何使用密码授予流程获取令牌:
POST https://<my-tenant-id>.b2clogin.com/<my-tenant-id.onmicrosoft.com/oauth2/v2.0/token?p=B2C_1_<my-custom-policy>
(以用户名和密码为参数)
所以移动应用可以使用该调用。但是我应该如何配置我的 Spring Boot 应用程序以便在 API 调用上使用 Authorization: Bearer <access-token> 有效?我需要什么依赖项/启动器,我应该如何配置?
更新:
我尝试添加:
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>2.3.7.RELEASE</version>
</dependency>
与:
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class OAuth2ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.resourceId("my-azure-b2c-test");
}
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/api/**")
.authenticated();
}
}
但是当我在我的 Spring Boot 应用程序上发出请求时,我收到一个带有“invalid_token”错误的 401。
【问题讨论】:
-
你有没有尝试过?
-
您必须检查 Spring Boot 应用程序中传入请求标头中包含的 JWT 令牌(对于每个传入请求)。
-
@ieggel 你能详细解释一下这应该怎么做吗?
-
@Michael 我用我尝试过的方法更新了问题
-
@WimDeblauwe 我没有使用 Azure 的经验,但我之前提到的是它必须如何完成。在我看来,您使用的库已经可以为您处理 JWT 验证并将其集成到 Spring 安全上下文中。这里似乎有一些例子:github.com/microsoft/azure-spring-boot/tree/master/…
标签: java spring-boot spring-security azure-ad-b2c