【问题标题】:In Spring how do you get the current user whose credentials are not part of the current http request?在 Spring 中,如何获取其凭据不属于当前 http 请求的当前用户?
【发布时间】:2011-04-01 05:26:39
【问题描述】:

Spring 中是否有“getCurrentUser”方法来访问当前属于请求的用户 - 即使该用户的名称没有作为 Web 请求的一部分传递?

【问题讨论】:

    标签: java spring spring-mvc spring-security authentication


    【解决方案1】:

    由于您已使用 spring-security 标记您的问题,我假设您的问题是在相同的上下文中。使用 spring-security 您可以检索当前用户:

    Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    UserDetails userDetails = null;
    if (principal instanceof UserDetails) {
      userDetails = (UserDetails) principal;
    }
    String userName = userDetails.getUsername();
    

    【讨论】:

    • Spring Security 还通过HttpServletRequest.getPrincipal() 公开其身份验证数据。
    • 这对我不起作用 getAuthentication() 返回 null,即使用户已登录 stackoverflow.com/q/7811200/106261
    猜你喜欢
    • 1970-01-01
    • 2016-03-05
    • 1970-01-01
    • 1970-01-01
    • 2017-10-14
    • 2017-12-21
    • 2021-05-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多