java - Spring Security 使用模型属性来应用角色

标签 java spring spring-mvc annotations spring-security

我有一个 Spring MVC 应用程序,我希望将 Spring Security 与 (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>

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

例如用户应具有角色 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 :

@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";
    }

}

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

@PreAuthorize 注解

我尝试在该 Controller (以及处理 URI 的其他 Controller )上的每个 @RequestMapping 方法上使用 @PreAuthorize("hasRole(#sportName.toUpperCase() + '_USER')")请求在层次结构中更靠下。我无法让它工作;没有错误,但它似乎没有做任何事情。

缺点:

  • 不起作用?
  • @Controller 上的方法级注释,而不是类级注释。那不是很干。此外,如果添加了更多功能并且有人忘记将注释添加到新代码,则可能会留下安全漏洞。
  • 我无法为其编写测试。

Spring Security链中拦截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>

这感觉应该可行,对于其他开发人员来说很明显它在做什么,但我没有成功使用这种方法。我对这种方法的唯一痛点是无法编写一个测试来标记问题,如果事情发生了变化。

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)

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);
    }
}

和:

<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" />

加分点:

  • 这有效

缺点:

  • 没有测试。
  • 如果我们的应用程序 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();
    }
}

加分点:

  • 这行得通。

缺点:

  • 这是否依赖于 Controller 中的每个 @RequestMapping 注释方法都具有检索 Sport 实例的 @PathVariable?
  • 没有测试。

请指出我遗漏了精美手册的哪一部分。

最佳答案

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

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

另请参阅:

关于java - Spring Security 使用模型属性来应用角色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4828758/

相关文章:

java - MongoDB Java : Finding objects in Mongo using QueryBuilder $in operator returns nothing

java - 收集多维数组的列来设置

java - Spring Boot CORS设置: CrossOrigin annotation works addCorsMappings doesn't

java - 为什么 Chrome DevTools 说我的静态资源在使用 Spring 的 mvc :resources? 映射时显式不可缓存

java - Spring MVC Hibernate 错误 java.lang.Object;无法转换为 model.Employee

java - 无法在 Spring Boot 应用程序中启动 Tomcat

java - UnsupportedClassVersionError : has been compiled by a more recent version of the Java Runtime (class file version 55. 0),此版本 (..) 最高为 52.0

java.lang.NumberFormatException : Invalid double: "" Edit Text 异常

java - 如何在Spring中添加/设置查询参数?

Java Spring REST 调用参数