且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用Azure AD B2C保护Spring Boot REST API?

更新时间:2021-12-22 18:07:44

解决方案一经了解就非常简单.

Solution seems to be quite simple once you know it.

首先,添加以下依赖项:

First, add the following dependencies:

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-oauth2-resource-server</artifactId>
            <version>5.2.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-oauth2-jose</artifactId>
            <version>5.2.0.RELEASE</version>
        </dependency>

接下来,在 application.properties 文件中指定 spring.security.oauth2.resourceserver.jwt.jwk-set-uri 属性.

Next specify the spring.security.oauth2.resourceserver.jwt.jwk-set-uri property in your application.properties file.

要知道此值,请在 https://< my-tenant-id> .b2clogin.com/< my-tenant-id> .onmicrosoft.com/v2.0/.well-known/openid-configuration?p = B2C_1_< my-custom-policy>

这将返回具有 jwks_uri 值的JSON正文.取该值并将其放在您的 application.properties 文件中.

This will return a JSON body with jwks_uri value. Take that value and put it in your application.properties file.

现在在项目中创建此Java类:

Now create this Java class in the project:

import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer;

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/api/**")
            .authenticated()
            .and()
            .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
    }
}

如果您现在拥有这样的控制器:

If you now have controller like this:

@RestController
public class ApiController {

    @GetMapping("/api/test")
    public String apiTest(@AuthenticationPrincipal Principal principal) {
        return "test " + principal;
    }
}

如果您使用正确的 Authorization 标头(其类型为org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken )

You will see that the principal is not-null if you do a GET on api/test with a correct Authorization header (and it is of type org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken)

唯一不幸的是,校长没有权限,我仍然需要弄清楚原因.

The only thing that is unfortunate is that the Principal has no authorities, something I still need to figure out why.