You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用spring-cloud-azure-starter-active-directory获取认证URL与用户ID?

使用spring-cloud-azure-starter-active-directory获取认证URL与用户ID

一、获取并输出认证URL

spring-cloud-azure-starter-active-directory会基于配置自动关联Azure AD的认证服务,你可以直接读取配置参数拼接认证URL并输出:

  1. 先在配置文件(如application.yml)中配置基础信息:
spring:
  cloud:
    azure:
      active-directory:
        client:
          client-id: {你的客户端ID}
          tenant-id: {你的租户ID}
          redirect-uri: "{你的回调地址}"
  1. 编写组件读取配置并生成认证URL:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import jakarta.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component
public class AdAuthUrlLogger {
    private static final Logger logger = LoggerFactory.getLogger(AdAuthUrlLogger.class);

    @Value("${spring.cloud.azure.active-directory.client.tenant-id}")
    private String tenantId;

    @Value("${spring.cloud.azure.active-directory.client.client-id}")
    private String clientId;

    @PostConstruct
    public void logAuthenticationUrl() {
        String authUrl = String.format("https://login.microsoftonline.com/%s/oauth2/v2.0/authorize?response_type=code&client_id=%s", tenantId, clientId);
        logger.info("认证URL: {}", authUrl);
    }
}

二、获取并输出登录用户ID

用户登录成功后,Spring Security会将认证信息存入SecurityContextHolder,你可以通过以下两种方式获取用户ID:

方式1:在控制器中直接获取

import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@RestController
public class UserInfoController {
    private static final Logger logger = LoggerFactory.getLogger(UserInfoController.class);

    @GetMapping("/current-user")
    public String getCurrentUser(@AuthenticationPrincipal OAuth2User oAuth2User) {
        // 优先取email,若不存在则取upn属性
        String userId = oAuth2User.getAttribute("email") != null ? oAuth2User.getAttribute("email") : oAuth2User.getAttribute("upn");
        logger.info("登录用户ID: {}", userId);
        return userId;
    }
}

方式2:监听认证成功事件

import org.springframework.context.event.EventListener;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.stereotype.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component
public class AuthSuccessLogger {
    private static final Logger logger = LoggerFactory.getLogger(AuthSuccessLogger.class);

    @EventListener
    public void onAuthSuccess(AuthenticationSuccessEvent event) {
        Object principal = event.getAuthentication().getPrincipal();
        if (principal instanceof OAuth2User oAuth2User) {
            String userId = oAuth2User.getAttribute("email") != null ? oAuth2User.getAttribute("email") : oAuth2User.getAttribute("upn");
            logger.info("登录用户ID: {}", userId);
        }
    }
}

注意事项

  • 确保已正确引入spring-cloud-azure-starter-active-directory依赖
  • 需要在Azure AD应用中配置获取用户邮箱/UPN的权限,否则无法读取对应属性

内容的提问来源于stack exchange,提问作者t-kitamura

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 00:46:03