我应该如何扩展 com.microsoft.azure.spring.autoconfigure.aad.UserPrincipal?

问题描述

我在前端 (PKCE) 上使用 MSAL 并在服务器上使用 azure-active-directory-spring-boot-starter 来提供代表登录用户及其声明的实体。

我构建了一个包含 Microsoft 的 UserPrincipal 的类,以提供对众所周知的声明的轻松访问:

import com.microsoft.azure.spring.autoconfigure.aad.UserPrincipal;
public class MyCustomUser {
    private UserPrincipal userPrincipal;

    public MyCustomUser(UserPrincipal userPrincipal) {
        this.userPrincipal = userPrincipal;
    }

    public String getEmployeeId() {
        return String.valueOf(this.userPrincipal.getClaim("emplid"));
    }
}

我通过辅助类提供此功能

@Component
public class MyAppSecurityContext {
    public MyCustomUser getUser() {
        UserPrincipal principal = (UserPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return new MyCustomUser(principal);
    }
}

然后在我的服务层使用它:

@Service
public class AnnouncementServiceImpl implements AnnouncementService {

    @Autowired
    private MyAppSecurityContext securityContext;

    @Override
    public List<Announcement> saveAnnouncement(Announcement announcement) {
        MyCustomUser currentUser = this.securityContext.getUser();
        String empid = currentUser.getEmployeeId();

        return this.announcementRepository.saveAnnouncement(empid,announcement);
    }
}

这行得通,但感觉不对。我更愿意让 MyCustomUser extend UserPrincipal 并让 getPrincipal() 返回我的自定义类型(无需有效地重新实现我自己的 UserPrincipal),而不是在成员对象前提供外观。问题在于 UserPrincipal 的 constructor expects JWT concerns,这表明这不是正确的方法。对于仅依赖客户端声明的 Spring 安全项目,是否有另一种更合适的方法来为用户建模?

解决方法

@Josh。

azure-active-directory-spring-boot-starter中,UserPrincipal用于AADAuthenticationFilterAADAppRoleStatelessAuthenticationFilter。现在这两个过滤器都已弃用。

能否请您使用最新版本的azure-spring-boot-starter-active-diectory?这是 3.7.0,它适用于 spring-boot:2.5.0。既然您使用了 UserPrincipal,那么您的应用程序就是一个资源服务器。

这里是文档:https://github.com/Azure/azure-sdk-for-java/tree/azure-spring-boot-starter-active-directory_3.7.0/sdk/spring/azure-spring-boot-starter-active-directory#accessing-a-resource-server

我们有一些样品。 您当前的应用程序类似于:

  1. https://github.com/Azure-Samples/azure-spring-boot-samples/tree/azure-spring-boot_3.6/aad/azure-spring-boot-sample-active-directory-resource-server-by-filter-stateless
  2. https://github.com/Azure-Samples/azure-spring-boot-samples/tree/azure-spring-boot_3.6/aad/azure-spring-boot-sample-active-directory-resource-server-by-filter

但是不推荐使用2的用法,建议你学习新的方法:https://github.com/Azure-Samples/azure-spring-boot-samples/tree/azure-spring-boot_3.6/aad/azure-spring-boot-sample-active-directory-resource-server

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...