[英]Spring security using model properties to apply roles
我有一個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("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種不同的方法。
我試圖在該控制器(以及其他處理URI請求的其他控制器@PreAuthorize("hasRole(#sportName.toUpperCase() + '_USER')")
上的每個@RequestMapping方法上使用@PreAuthorize("hasRole(#sportName.toUpperCase() + '_USER')")
能夠使它正常工作;沒有錯誤,但似乎沒有任何作用。
壞點:
@Controller
上的方法級別的注釋,而不是類級別的注釋。 那不是很干。 此外,如果添加了更多功能並且有人忘記將注釋添加到新代碼中,則可能會留下安全漏洞。 <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)
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" />
加分:
壞點:
@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();
}
}
加分:
壞點:
請指出我缺少精美手冊的哪一部分。
代替#sportName.toUpper()
您需要使用#sport.name.toUpper()
類的東西,因為@PreAuthorize
#...
變量引用方法參數:
@RequestMapping(...)
@PreAuthorize("hasRole(#sport.name.toUpper() + '_USER')")
public String index(@PathVariable("sportName") Sport sport, Model model) { ... }
也可以看看:
我也找到了一個解決方案,使用:
<security:global-method-security secured-annotations="enabled" proxy-target-class="true"/>
希望對您有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.