Spring安全性使用模型属性来应用角色

jab*_*ley 1 java spring annotations spring-mvc spring-security

我有一个Spring MVC应用程序,我希望将Spring Security与Spring(Spring 3.0.x)集成.

web.xml包含:

<context-param>
    <description>Context Configuration locations for Spring XML files</description>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        classpath*:spring/spring-model.xml
        classpath*:spring/spring-compiler.xml
        classpath*:spring/spring-ui.xml
        classpath*:spring/spring-security.xml
    </param-value>
</context-param>
<listener>
    <description><![CDATA[
        Loads the root application context of this web app at startup, use 
        contextConfigLocation paramters defined above or by default use "/WEB-INF/applicationContext.xml".
        - Note that you need to fall back to Spring's ContextLoaderServlet for
        - J2EE servers that do not follow the Servlet 2.4 initialization order.

        Use WebApplicationContextUtils.getWebApplicationContext(servletContext) to access it anywhere in the web application, outside of the framework.

        The root context is the parent of all servlet-specific contexts.
        This means that its beans are automatically available in these child contexts,
        both for getBean(name) calls and (external) bean references.
    ]]></description>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
    <description>Configuration for the Spring MVC webapp servlet</description>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:spring/spring-mvc.xml</param-value>
    </init-param>
</servlet>
<servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/app/*</url-pattern>
</servlet-mapping>
Run Code Online (Sandbox Code Playgroud)

我想添加基于角色的安全性,以便用户无法访问网站的某些部分.

例如,用户应具有的角色CRICKET_USER才能够访问http://example.com/sports/cricket和角色FOOTBALL_USER访问http://example.com/sports/football.

应用程序中的URI保留此层次结构,因此可能存在资源,例如http://example.com/sports/football/leagues/premiership,类似地要求用户具有该角色FOOTBALL_USER.

我有一个像这样的控制器:

@Controller("sportsController")
@RequestMapping("/sports/{sportName}")
public class SportsController {

    @RequestMapping("")
    public String index(@PathVariable("sportName") Sport sport, Model model) {
        model.addAttribute("sport", sport);
        return "sports/index";
    }

}
Run Code Online (Sandbox Code Playgroud)

我一直在努力使用最惯用,最明显的方式来满足这个要求,但我不确定我是否已找到它.我尝试了4种不同的方法.

@PreAuthorize注释

我试图@PreAuthorize("hasRole(#sportName.toUpperCase() + '_USER')")在该控制器上使用每个@RequestMapping方法(以及在层次结构中进一步处理URI请求的其他控制器.我无法正常工作;没有错误,但似乎没有做任何事情.

坏点:

  • 不起作用?
  • 方法级注释,而不是类级别@Controller.那不是很干.如果添加更多功能并且有人忘记将注释添加到新代码,则可能会留下安全漏洞.
  • 我不能为它写一个测试.

Spring Security链中的Intercept-url

<http use-expressions="true">

    <!--  note that the order of these filters are significant -->
    <intercept-url pattern="/app/sports/**" access="hasRole(#sportName.toUpperCase() + '_USER')" />

    <form-login always-use-default-target="false"
        authentication-failure-url="/login/" default-target-url="/"
        login-page="/login/" login-processing-url="/app/logincheck"/>
    <!-- This action catch the error message and make it available to the view -->
    <anonymous/>
    <http-basic/>
    <access-denied-handler error-page="/app/login/accessdenied"/>
    <logout logout-success-url="/login/" logout-url="/app/logout"/>
</http>
Run Code Online (Sandbox Code Playgroud)

这感觉它应该工作,对其他开发人员来说,它正在做什么是显而易见的但是我没有成功使用这种方法.我采用这种方法唯一的痛点就是无法编写一个测试标记问题,如果事情发生变化.

java.lang.IllegalArgumentException: Failed to evaluate expression 'hasRole(#sportName.toUpper() + '_USER')'
at org.springframework.security.access.expression.ExpressionUtils.evaluateAsBoolean(ExpressionUtils.java:13)
at org.springframework.security.web.access.expression.WebExpressionVoter.vote(WebExpressionVoter.java:34)
...
Caused by: 
org.springframework.expression.spel.SpelEvaluationException: EL1011E:(pos 17): Method call: Attempted to call method toUpper() on null context object
at org.springframework.expression.spel.ast.MethodReference.getValueInternal(MethodReference.java:69)
at org.springframework.expression.spel.ast.CompoundExpression.getValueInternal(CompoundExpression.java:57)
Run Code Online (Sandbox Code Playgroud)

Spring Security链中的标准过滤器.

public class SportAuthorisationFilter extends GenericFilterBean {

    /**
     * {@inheritDoc}
     */
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest httpRequest = (HttpServletRequest) request;

        String pathInfo = httpRequest.getPathInfo();

        /* This assumes that the servlet is coming off the /app/ context and sports are served off /sports/ */
        if (pathInfo.startsWith("/sports/")) {

            String sportName = httpRequest.getPathInfo().split("/")[2];

            List<String> roles = SpringSecurityContext.getRoles();

            if (!roles.contains(sportName.toUpperCase() + "_USER")) {
                throw new AccessDeniedException(SpringSecurityContext.getUsername()
                        + "is  not permitted to access sport " + sportName);
            }
        }

        chain.doFilter(request, response);
    }
}
Run Code Online (Sandbox Code Playgroud)

和:

<http use-expressions="true">

    <!--  note that the order of these filters are significant -->

    <!--
      Custom filter for /app/sports/** requests. We wish to restrict access to those resources to users who have the
      {SPORTNAME}_USER role.
    -->
    <custom-filter before="FILTER_SECURITY_INTERCEPTOR" ref="sportsAuthFilter"/>
    <form-login always-use-default-target="false"
        authentication-failure-url="/login/" default-target-url="/"
        login-page="/login/" login-processing-url="/app/logincheck"/>
    <!-- This action catch the error message and make it available to the view -->
    <anonymous/>
    <http-basic/>
    <access-denied-handler error-page="/app/login/accessdenied"/>
    <logout logout-success-url="/login/" logout-url="/app/logout"/>
</http>

<beans:bean id="sportsAuthFilter" class="com.example.web.controller.security.SportsAuthorisationFilter" />
Run Code Online (Sandbox Code Playgroud)

加点:

  • 这有效

坏点:

  • 没有测试.
  • 如果我们的应用程序URI结构发生变化,则可能非常脆弱
  • 对于改变代码的下一个人来说并不明显.

在@PathVariable使用的Formatter实现中验证

@Component
public class SportFormatter implements DiscoverableFormatter<Sport> {

@Autowired
private SportService SportService;

public Class<Sport> getTarget() {
    return Sport.class;
}

public String print(Sport sport, Locale locale) {
    if (sport == null) {
        return "";
    }
    return sport.getName();
}

public Sport parse(String text, Locale locale) throws ParseException {
    Sport sport;

    if (text == null || text.isEmpty()) {
        return new Sport();
    }

    if (NumberUtils.isNumber(text)) {
        sport = sportService.getByPrimaryKey(new Long(text));
    } else {
        Sport example = new Sport();
        example.setName(text);
        sport = sportService.findUnique(example);
    }

    if (sport != null) {
        List<String> roles = SpringSecurityContext.getRoles();

        if (!roles.contains(sportName.toUpperCase() + "_USER")) {
            throw new AccessDeniedException(SpringSecurityContext.getUsername()
                    + "is  not permitted to access sport " + sportName);
        }      
    }

    return sport != null ? sport : new Sport();
    }
}
Run Code Online (Sandbox Code Playgroud)

加点:

  • 这有效.

坏点:

  • 这是否依赖于具有检索Sport实例的@PathVariable的控制器中的每个@RequestMapping带注释的方法?
  • 没有测试.

请指出我遗漏的精细手册的哪一部分.

axt*_*avt 6

而不是#sportName.toUpper()你需要使用类似的东西#sport.name.toUpper(),因为#...变量在@PreAuthorize引用方法参数:

@RequestMapping(...)
@PreAuthorize("hasRole(#sport.name.toUpper() + '_USER')") 
public String index(@PathVariable("sportName") Sport sport, Model model) { ... }
Run Code Online (Sandbox Code Playgroud)

也可以看看: