我有一個使用Jersey的JAX-RS項目。現在我正在嘗試添加Spring Security的方法級安全性,但不幸的是它不工作,儘管intercept-url
xml方式工作正常。@Secured在Jersey項目中整合Spring Security時不起作用
- 加在我的
pom.xml
依賴更新
web.xml
爲<context-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/security.xml, /WEB-INF/beans.xml </param-value> </context-param> <!-- this is default security impl name used by deletetingFiterProxy --> <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>
更新
/WEB-INF/security.xml
<beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd"> <!-- kind of authentication applied 1) Basic 2) form-based etc.. auto-config="true" use-expressions="true"--> <http auto-config="true"> <http-basic /> </http> <!-- this allow to enable security annotations in restful resoruces --> <global-method-security secured-annotations="enabled" /> <!-- for defining users and roles --> <authentication-manager> <authentication-provider> <user-service> <user name="admin" password="admin" authorities="ROLE_CUSTOMER,ROLE_ADMIN"/> <user name="student" password="student" authorities="ROLE_CUSTOMER"/> </user-service> </authentication-provider> </authentication-manager> </beans:beans>
詮釋服務inteface方法
public interface StudentServiceInterface { @GET @Path("/students") @Secured("ROLE_CUSTOMER") public Response getStudents(); @GET @Path("/students/{id}") @Secured("ROLE_CUSTOMER") public Response getStudent(@PathParam("id") int id); @POST @Path("/students") @Consumes(MediaType.APPLICATION_JSON) @Secured("ROLE_ADMIN") public Response addStudent(Student stu); }
現在,當我嘗試訪問它打開資源的學生(/student
)類不問密碼。
http://localhost:3126/securitydemo/webapi/db/students
StudentServiceInterface接口實現
@Path("/db")
@Produces(MediaType.APPLICATION_JSON)
public class StudentService implements StudentServiceInterface{
static StudentDao data= new StudentDaoImpl();
@Override
public Response getStudents(){
GenericEntity<List<Student>> entity = new GenericEntity<List<Student>>(data.getAllStudents()){};
return Response.ok(entity).build();
}
@Override
public Response getStudent(@PathParam("id") int id){
return Response.ok(data.getStudent(id)).build();
}
@Override
public Response addStudent(Student stu) {
data.addStudent(stu);
return Response.ok(stu).build();
}
}
Jersey verion 2.25.1 –