如何使用Struts 2 / Spring 3进行HTTP基本身份验证?

时间:2011-12-02 16:15:02

标签: java web-services struts2

我正在编写RESTful Web服务,某些API需要用户身份授权。由于HTTP基本身份验证足以满足我的要求,我决定使用它。

我想检查我的API用户提供的用户凭据对存储这些凭据的MySQL数据库表。

如何使用Struts 2 / Spring 3实现这一目标?

1 个答案:

答案 0 :(得分:0)

你可以使用spring-security。我刚刚按照http://syntx.co/languages-frameworks/adding-http-basic-auth-to-restful-services-in-java-and-spring/

的教程完成了这项工作

要对数据库进行身份验证,您可能需要创建自己的身份验证提供程序;有一个示例:Spring Security 3 database authentication with Hibernate

简而言之:

1)在pom.xml中添加spring-security:

    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-web</artifactId>
        <version>3.1.3.RELEASE</version>
    </dependency>       

    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-config</artifactId>
        <version>3.1.3.RELEASE</version>
    </dependency>   

2)将过滤器添加到web.xml:

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

(你还需要Spring ContextLoaderListener,但是如果你已经使用了spring它可能已经在你的web.xml中了)

3)更新spring xml配置

<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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    ...
    http://www.springframework.org/schema/security
    http://www.springframework.org/schema/security/spring-security-3.1.xsd">

    <security:http auto-config='true'>
        <security:intercept-url pattern="/**" access="ROLE_USER" />
        <security:http-basic />
    </security:http>

    <security:authentication-manager>
        <security:authentication-provider>
            <!-- this is an demo example with hardcoded username and password -->
            <security:user-service>
                <security:user name="..." password="..." authorities="ROLE_USER" />
            </security:user-service>
        </security:authentication-provider>
    </security:authentication-manager>
    ....
</beans>

我的示例没有显示如何对数据库进行身份验证:正如我上面所述,它已经在Spring Security 3 database authentication with Hibernate中介绍了(没有尝试过,因为我现在只需要硬编码的用户名和密码)。