如何在控制器中以编程方式实现Spring Security SpEL isFullyAuthenticated()?

时间:2012-05-16 19:06:55

标签: spring spring-mvc spring-security

我有一个控制器,我想检查一下完全身份验证的用户是否与Spring Security isFullyAuthenticated()表达式提供的相似。我该怎么做?

我使用的解决方案基于Tomasz Nurkiewicz的回答,只是从org.springframework.security.access.expression.ExcurityExpressionRoot中窃取实现

 public class SpringSecurityUtils {
    private static final AuthenticationTrustResolver trustResolver = new AuthenticationTrustResolverImpl();

    public static boolean isFullyAuthenticated()
    {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return !trustResolver.isAnonymous(authentication) && !trustResolver.isRememberMe(authentication);
    }
}

2 个答案:

答案 0 :(得分:2)

查看SecurityExpressionRootAuthenticationTrustResolverImpl的源代码,您可以使用以下条件:

public boolean isFullyAuthenticated(Authentication auth) {
    return !(auth instanceof AnonymousAuthenticationToken || 
             auth instanceof RememberMeAuthenticationToken);
}

您获得身份验证的地方,例如使用:

SecurityContextHolder.getContext().getAuthentication()

答案 1 :(得分:1)

您可以使用字符串isUserInRole()调用SecurityContextHolderAwareRequestWrapper或[{1}}的{​​{3}}方法:

HttpServletRequest