Spring Securitiy 保护 REST API 端点
在 pom.xml
中添加以下条目。
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>3.1.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>3.1.0.RELEASE</version>
</dependency>
对于大于 3.1 的 Spring 版本很重要:
当你使用高于 3.1 的 Spring 版本并且未在 pom.xml
中手动为 spring-aop
,spring-jdbc
,spring-tx
和 spring-expressions
添加依赖项时,会出现 org.springframework.security.filterChains
的 Bean 创建错误。
在 Spring 上下文中添加以下条目。我们想要保护两个 REST 端点(helloworld 和 goodbye)。根据 Spring 版本调整 XSD 版本。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<security:http auto-config='true' create-session="never">
<security:intercept-url pattern="/helloworld/**" access="ROLE_USER" />
<security:intercept-url pattern="/goodbye/**" access="ROLE_ADMIN" />
<security:intercept-url pattern="/**" access="IS_AUTHENTICATED_ANONYMOUSLY" />
<security:http-basic />
</security:http>
<security:authentication-manager>
<security:authentication-provider>
<security:user-service>
<security:user name="username1" password="password1"
authorities="ROLE_USER" />
<security:user name="username2" password="password2"
authorities="ROLE_ADMIN" />
</security:user-service>
</security:authentication-provider>
</security:authentication-manager>
</beans>
在 web.xml
中添加以下条目。
<!-- Spring security-->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:security-context.xml</param-value>
</context-param>