Java 从Spring boot中的id令牌获取主题

Java 从Spring boot中的id令牌获取主题,java,spring-boot,authentication,oauth-2.0,Java,Spring Boot,Authentication,Oauth 2.0,我已将Spring引导应用程序配置为资源服务器。它通过阻止所有不包含身份验证承载令牌的请求而完美地工作。然而,一旦我投入服务,我想从令牌中获取主题(JWT令牌中的sub)并使用它。如何从Spring身份验证框架中获取subject的值 因为我使用的是Spring Boot的自动配置,所以我自己不验证令牌,它是自动完成的,所以我不知道主题。我在参数中添加了原则 import org.springframework.security.core.Authentication; import org.s

我已将Spring引导应用程序配置为资源服务器。它通过阻止所有不包含身份验证承载令牌的请求而完美地工作。然而,一旦我投入服务,我想从令牌中获取主题(JWT令牌中的sub)并使用它。如何从Spring身份验证框架中获取subject的值


因为我使用的是Spring Boot的自动配置,所以我自己不验证令牌,它是自动完成的,所以我不知道主题。

我在参数中添加了原则

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;    
...
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
...
@Controller
public class SecurityController {

    @RequestMapping(value = "/username", method = RequestMethod.GET)
    @ResponseBody
    public String currentUserName(Principal principal) {
        return principal.getName();
    }
}

这帮助了我

我在论点中加入了原则

@Controller
public class SecurityController {

    @RequestMapping(value = "/username", method = RequestMethod.GET)
    @ResponseBody
    public String currentUserName(Principal principal) {
        return principal.getName();
    }
}

这对我很有帮助

嗨,我现在无法测试,但我有个主意。我相信您可以使用SecurityContext访问
SecurityContextHolder.getContext()
为您提供SecurityContext,因此通过访问身份验证obj,您应该能够获取主题等。这对我很有帮助。我找到了答案。基本上,您可以将
Principal
放入控制器参数,然后为您提取原理。这就是春靴的魅力所在。嗨,我现在不能测试,但我有个主意。我相信您可以使用SecurityContext访问
SecurityContextHolder.getContext()
为您提供SecurityContext,因此通过访问身份验证obj,您应该能够获取主题等。这对我很有帮助。我找到了答案。基本上,您可以将
Principal
放入控制器参数,然后为您提取原理。这就是春靴的魅力所在。