我正在尝试Spring安全性,并使用@PreAuthorize注释了我的RestController的一些方法。 但是,我可以在未经过身份验证的情况下访问所有这些内容。
Web.xml中
<?xml version="1.0" encoding="UTF-8"?>
<web-app ...>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>
org.springframework.web.filter.DelegatingFilterProxy
</filter-class>
</filter>
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
安全配置,由root-context导入:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans ...>
<global-method-security pre-post-annotations="enabled" />
<http auto-config="true">
<intercept-url pattern="/service/public/**" />
<intercept-url pattern="/service/user/**" access="ROLE_USER,ROLE_ADMIN" />
<intercept-url pattern="/service/admin/**" access="ROLE_ADMIN" />
</http>
<authentication-manager alias="authenticationManager">
<authentication-provider> <user-service> <user name="admin" password="admin"
authorities="ROLE_ADMIN" /> <user name="user" password="user" authorities="ROLE_USER"
/> </user-service> </authentication-provider>
</authentication-manager>
</beans:beans>
我的服务:
@RestController
@RequestMapping("/service")
public class Service {
@RequestMapping(value = "/public/{name}", method = RequestMethod.GET)
public String storeEntityPublic(@PathVariable String name) {
String result = "Hello " + name + ", I am saving on the db. (PUBLIC)";
return result;
}
@PreAuthorize("hasAnyRole('ROLE_USER','ROLE_ADMIN')")
@RequestMapping(value = "/user/{name}", method = RequestMethod.GET)
public String storeEntityUserOrAdmin(@PathVariable String name) {
String result = "Hello " + name
+ ", I am saving on the db. (USER OR ADMIN)";
return result;
}
@PreAuthorize("hasRole('ROLE_ADMIN')")
@RequestMapping(value = "/admin/{name}", method = RequestMethod.GET)
public String storeEntityAdmin(@PathVariable String name) {
String result = "Hello Admin " + name
+ ", I am saving on the db. (ADMIN ONLY)";
return result;
}
}
它出了什么问题?