【问题标题】:How can I access the SecurityContext in a MethodInterceptor?如何访问 MethodInterceptor 中的 SecurityContext?
【发布时间】:2013-07-03 15:46:46
【问题描述】:

我正在开发一个带有 Spring Security 设置的 Spring MVC 应用程序,该设置通过 LDAP 对 Active Directory 用户进行身份验证。我正在尝试设置 AOP 来记录每个被调用的控制器方法。我已经一切正常,我可以拦截该方法..但我似乎无法访问 SecurityContext 来获取正在执行该方法的登录用户的用户名。

UserInvokedMethodLogger.java

public class UserInvokedMethodLogger implements MethodInterceptor
{
    private SecurityContext security = SecurityContextHolder.getContext();

    @Override
    public Object invoke(MethodInvocation interceptedMethod) throws Throwable
    {
        long start = System.currentTimeMillis();
        Object result = interceptedMethod.proceed();
        long end = System.currentTimeMillis();

        String dbgMessage =
                (security.getAuthentication() != null)
                    ? "User '" + security.getAuthentication().getName() + "' called method '"
                    : "Unauthenticated user called method '"
                + interceptedMethod.getMethod().getName()
                + "' which executed in " + (end - start) + "ms.";

        System.out.println(dbgMessage);
        return result;
    }
}

即使我已登录,输出始终是“未经身份验证的用户”。

【问题讨论】:

    标签: java spring spring-security spring-aop


    【解决方案1】:

    尝试在每个方法调用期间调用 SecurityContextHolder.getContext()。只需删除您的 private SecurityContext security 属性并直接使用 SecurityContextHolder.getContext()。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-12
      • 2017-08-24
      相关资源
      最近更新 更多