spring-boot - Spring Boot Azure AD 自定义角色

标签 spring-boot azure spring-security azure-active-directory

我有这个普通的 spring boot/azure/starter 应用程序,连接到我们的内部 azure 服务。 https://learn.microsoft.com/de-de/azure/developer/java/spring-framework/configure-spring-boot-starter-java-app-with-azure-active-directory

通常它会按设计工作。

如果我想添加自定义角色进行授权,我有哪些选项?

我想要这样的流程:

  1. 使用 user/pw 登录 azure(按预期工作)
  2. 从本地数据库 (postgres) 加载用户角色
  3. 将此角色注入(inject)/添加到 spring 的 GrantedAuthority 列表中

对于 Spring Security,我们通常使用自定义的 AuthenticationProvider

目前我有这个工作代码:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends AadWebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);
        http
                .authorizeHttpRequests()
                .anyRequest()
                .authenticated()
                .and()
                .oauth2Login();

    }
}

我想要这样的东西:

@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Slf4j
public class ThdAuthenticationProvider implements AuthenticationProvider {

    private final
    @NonNull
    IApplicationUserService userService;

    /**
     * Performs authentication with the same contract as .
     *
     * @param authentication the authentication request object.
     * @return a fully authenticated object including credentials. May return <code>null</code> if the
     * <code>AuthenticationProvider</code> is unable to support authentication of the passed
     * <code>Authentication</code> object. In such a case, the next <code>AuthenticationProvider</code> that
     * supports the presented <code>Authentication</code> class will be tried.
     * @throws AuthenticationException if authentication fails.
     */
    @Override
    public org.springframework.security.core.Authentication authenticate(org.springframework.security.core.Authentication
                                                                                 authentication)
            throws AuthenticationException {
        final String name = authentication.getName().toLowerCase();
        final String password = authentication.getCredentials().toString();

        // go to azure, login with name/password
        // come back if sucessfull

        List<String> roles = userService.fetchRoles(name);
        
        List<GrantedAuthority> grantedAuth = new ArrayList<>();
        grantedAuth.addAll(roles);
        return new UsernamePasswordAuthenticationToken(name, password, grantedAuth);
}

编辑

我最终是这样的: 基于此文档:https://docs.spring.io/spring-security/site/docs/5.2.12.RELEASE/reference/html/oauth2.html#oauth2login-advanced-map-authorities-oauth2userservice

我的自定义用户服务 - 将从数据库或其他地方获取角色:

@Service
public class UserService {
    List<String> fetchUserRoles(String user){
        return List.of("Administrator", "Product Owner", "Developer");
    }
}

我的自定义安全链应用这些角色:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends AadWebSecurityConfigurerAdapter {

    private final UserService userService;

    @Autowired
    public SecurityConfiguration(UserService userService) {
        this.userService = userService;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);
        http
                .authorizeHttpRequests()
                .anyRequest()
                .authenticated()
                .and()
                .oauth2Login()
                .userInfoEndpoint(userInfoEndpointConfig -> {
                    userInfoEndpointConfig.oidcUserService(this.oidcUserService());
                });

    }

    private OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService() {
        final OidcUserService delegate = new OidcUserService();
        return (userRequest) -> {
            // Delegate to the default implementation for loading a user
            OidcUser oidcUser = delegate.loadUser(userRequest);

            OAuth2AccessToken accessToken = userRequest.getAccessToken();
            Set<GrantedAuthority> mappedAuthorities = new HashSet<>();

            // TODO
            // 1) Fetch the authority information from the protected resource using accessToken
            // 2) Map the authority information to one or more GrantedAuthority's and add it to mappedAuthorities

            // 3) Create a copy of oidcUser but use the mappedAuthorities instead

            List<String> dummy = userService.fetchUserRoles("dummy");
            dummy.forEach(user -> mappedAuthorities.add((GrantedAuthority) () -> user));
            oidcUser = new DefaultOidcUser(mappedAuthorities, oidcUser.getIdToken(), oidcUser.getUserInfo());

            return oidcUser;
        };
    }
}

最佳答案

Spring Boot Azure AD custom roles

请点击以下链接,其中有详细说明:

  • 注册 Web API 应用程序并配置 API 范围

  • 为用户分配这些角色

  • 在 Azure AD 中注册客户端应用程序并配置 API 权限

引用:

Using Azure AD premium custom roles with spring security for role based access

关于spring-boot - Spring Boot Azure AD 自定义角色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72054267/

相关文章:

grails - Spring Security 3.0 - 自定义基本的 http 身份验证对话框

hibernate - 参数值 [....] 与预期类型不匹配 [java.util.Collection (n/a)]

java - 不想将服务层URL暴露给外界

java - Spring Boot 2 JasperReportsMultiFormatView

android - 从 Windows Azure blob 下载图像?

azure - 通过Azure数据工厂创建blob存储容器

spring-boot - 如何使用 grafana 可视化 Prometheus 端点指标

mysql - Azure:无法加载文件或程序集 MySql.Data

java - Spring Boot 2.0 Gradle 在 IntelliJ 中运行和测试

java - 将 Spring Security 添加到 Spring Boot 应用程序导致异常