【问题标题】:How to get authentication infomation when using spring security?使用spring security时如何获取认证信息?
【发布时间】:2011-04-20 10:09:00
【问题描述】:

在我使用标签的页面上: 安全性:授权 ifAnyGranted="ROLE_USER,ROLE_ADMIN" ... 有用。 但在服务器端:我使用 SecurityContextHolder.getContext().getAuthentication().isAuthenticated(),它总是正确的。当我没有登录时,系统以anonymousUser为登录用户。

我怎样才能避免这种情况?

【问题讨论】:

    标签: spring-security


    【解决方案1】:

    SecurityContextHolder.getContext().getAuthentication().isAuthenticated() 几乎总是会返回 true。 用这个

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    return authentication != null && !(authentication instanceof AnonymousAuthenticationToken) && authentication.isAuthenticated();
    

    【讨论】:

      【解决方案2】:

      如果是spring security 2.x,有AuthorityUtils.userHasAuthority(String authority)可以用来明确检查角色。

      您可以遍历 SecurityContextHolder.getContext().getAuthentication().getAuthorities() 并确保您只允许对您想要的角色进行操作。

      【讨论】:

      • 谢谢,我知道这种方法,我通过其他方法。SecurityContextHolder.getContext().getAuthentication().getAuthorities()
      猜你喜欢
      • 2019-12-15
      • 2013-04-17
      • 1970-01-01
      • 2017-12-21
      • 1970-01-01
      • 1970-01-01
      • 2011-03-11
      • 1970-01-01
      • 2015-03-09
      相关资源
      最近更新 更多