Spring MVC - 检查用户是否已通过Spring Security登录?

Jas*_*per 41 java security spring spring-mvc spring-security

我有一个Spring MVC应用程序.它使用自己的自定义登录页面.成功登录后,会在HTTPSession中放置一个"LOGGED_IN_USER"对象.

我想只允许经过身份验证的用户访问URL.我知道我可以通过使用网络过滤器实现这一目标.但是,这部分我想使用Spring Security(我的检查将保持不变 - 在HTTPSession中查找'LOGGED_IN_USER'对象,如果存在,您已登录).

我的约束是我目前无法改变登录行为 - 这还不会使用Spring Security.

我可以使用Spring Security的哪个方面单独实现此部分 - 检查请求是否经过身份验证(来自登录用户)?

Ral*_*lph 110

至少有4种不同的方式:

spring security XML配置

这是最简单的方法

<security:http auto-config="true" use-expressions="true" ...>
   ...
  <security:intercept-url pattern="/forAll/**" access="permitAll" />
  <security:intercept-url pattern="/**" access="isAuthenticated()" />
</security:http>
Run Code Online (Sandbox Code Playgroud)

Per @Secured Annotation

要求 <global-method-security secured-annotations="enabled" />

@Secured("ROLE_ADMIN")
@RequestMapping(params = "onlyForAdmins")    
public ModelAndView onlyForAdmins() {
    ....
}
Run Code Online (Sandbox Code Playgroud)

Per @PreAuthorize Annotation

要求 <global-method-security pre-post-annotations="enabled" />

 @PreAuthorize("isAuthenticated()")
 @RequestMapping(params = "onlyForAuthenticated")
 public ModelAndView onlyForAuthenticatedUsers() {
     ....
 }
Run Code Online (Sandbox Code Playgroud)

编程

 SecurityContextHolder.getContext().getAuthentication() != null &&
 SecurityContextHolder.getContext().getAuthentication().isAuthenticated() &&
 //when Anonymous Authentication is enabled
 !(SecurityContextHolder.getContext().getAuthentication() 
          instanceof AnonymousAuthenticationToken) 
Run Code Online (Sandbox Code Playgroud)

自定义表达

如果内置表达式不够,可以扩展它们.如何扩展方法注释的SpEL表达式,例如:

但是对于拦截器<security:intercept-url ... access="myCustomAuthenticatedExpression" />,可能存在一种稍微不同的方法,不需要处理私有类问题.- 我只为Spring Security 3.0做过,但我希望它也适用于3.1.

1.)您需要创建一个扩展自的新类WebSecurityExpressionRoot(前缀Web是重要的部分!).

public class MyCustomWebSecurityExpressionRoot
         extends WebSecurityExpressionRoot {
     public MyCustomWebSecurityExpressionRoot(Authentication a,
                 FilterInvocation f) {
          super(a, f);
     }

     /** That method is the one that does the expression evaluation! */
     public boolean myCustomAuthenticatedExpression() {
        return super.request.getSession().getValue("myFlag") != null;
     }
}
Run Code Online (Sandbox Code Playgroud)

2.)你需要一个扩展,DefaultWebSecurityExpressionRootHandler以拥有一个提供自定义表达式root的处理程序

 public class MyCustomWebSecurityExpressionHandler
              extends DefaultWebSecurityExpressionHandler {

      @Override        
      public EvaluationContext createEvaluationContext(Authentication a,
                FilterInvocation f) {
          StandardEvaluationContext ctx =
                   (StandardEvaluationContext) super.createEvaluationContext(a, f);

           WebSecurityExpressionRoot myRoot =
                    new MyCustomWebSecurityExpressionRoot(a, f);

           ctx.setRootObject(myRoot);
           return ctx;
      }
 }
Run Code Online (Sandbox Code Playgroud)

3.)然后你需要向选民登记你的处理程序

<security:http use-expressions="true"
 access-decision-manager-ref="httpAccessDecisionManager" ...>
      ...
    <security:intercept-url pattern="/restricted/**"
              access="myCustomAuthenticatedExpression" />         
      ...
</security:http>

<bean id="httpAccessDecisionManager"
      class="org.springframework.security.access.vote.AffirmativeBased">
    <constructor-arg name="decisionVoters">
            <list>
                <ref bean="webExpressionVoter" />
            </list>
    </constructor-arg>
</bean>

<bean id="webExpressionVoter"
      class="org.springframework.security.web.access.expression.WebExpressionVoter">
    <property name="expressionHandler"
              ref="myCustomWebSecurityExpressionHandler" />
</bean>

<bean id="myCustomWebSecurityExpressionHandler"
    class="MyCustomWebSecurityExpressionHandler" />
Run Code Online (Sandbox Code Playgroud)

Spring Security 3.1更新

从Spring Security 3.1开始,实现自定义表达式要容易一些.一个人不再需要sublcass WebSecurityExpressionHandler和覆盖createEvaluationContext.而是一个AbstractSecurityExpressionHandler<FilterInvocation>子类或其子类DefaultWebSecurityExpressionHandler和覆盖SecurityExpressionOperations createSecurityExpressionRoot(final Authentication a, final FilterInvocation f).

 public class MyCustomWebSecurityExpressionHandler
              extends DefaultWebSecurityExpressionHandler {

      @Override        
      public SecurityExpressionOperations createSecurityExpressionRoot(
                Authentication a,
                FilterInvocation f) {
           WebSecurityExpressionRoot myRoot =
                    new MyCustomWebSecurityExpressionRoot(a, f);

           myRoot.setPermissionEvaluator(getPermissionEvaluator());
           myRoot.setTrustResolver(this.trustResolver);
           myRoot.setRoleHierarchy(getRoleHierarchy());
           return myRoot;
      }
 }
Run Code Online (Sandbox Code Playgroud)


Ale*_*nko 14

另一个解决方案,你可以创建类:

public class AuthenticationSystem {
    public static boolean isLogged() {
        final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return null != authentication && !("anonymousUser").equals(authentication.getName());
    }
    // ...
    // Any another methods, for example, logout
}
Run Code Online (Sandbox Code Playgroud)

然后,在控制器中:

@Controller
@RequestMapping(value = "/promotion")
public final class PromotionController {  
    @RequestMapping(value = {"", "/"}, method = RequestMethod.GET)
    public final String root() {
        if (!AuthenticationSystem.isLogged()) return "login"; // or some logic
        // some logic
        return "promotion/index";
    }
}
Run Code Online (Sandbox Code Playgroud)

PS:

以前的解决方案有一个问题,在评论中解释了彼得.

@Controller
@RequestMapping(value = "/promotion")
public final class PromotionController {  
    @RequestMapping(value = {"", "/"}, method = RequestMethod.GET)
    public final String root(final Principal principal) {
        if (null == principal) return "login"; // or some logic
        // some logic
        return "promotion/index";
    }
}
Run Code Online (Sandbox Code Playgroud)


Chr*_*ang 9

这是你想要实现的目标吗?

<c:choose>
  <c:when test="${pageContext.request.userPrincipal.authenticated}">Show something</c:when>
  <c:otherwise>Show something else</c:otherwise>
</c:choose>
Run Code Online (Sandbox Code Playgroud)