从Spring Security中的文件读取用户名/密码

时间:2019-03-14 07:03:25

标签: java spring spring-security

<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-3.0.xsd
    http://www.springframework.org/schema/security
    http://www.springframework.org/schema/security/spring-security-3.2.xsd">

    <http use-expressions="true" auto-config="true">
        <intercept-url pattern="/login**" access="permitAll"/>
        <intercept-url pattern="/resources/**" access="permitAll"/>
        <intercept-url pattern="/favicon.ico" access="permitAll"/>
        <intercept-url pattern="/**" access="hasRole('ROLE_USER')" />

        <form-login 
            login-page="/login" 
            default-target-url="/" 
            always-use-default-target="true" 
            authentication-failure-url="/login?error=" 
            username-parameter="username"
            password-parameter="password" />
        <logout invalidate-session="true" logout-success-url="/login?logout="  />
        <!-- enable csrf protection -->
        <!-- <csrf/> -->
    </http>

    <authentication-manager>
        <authentication-provider>
            <user-service>
                <user name="soguha9@gmail.com" password= "soham123" authorities="ROLE_USER"/>
            </user-service>
        </authentication-provider>
    </authentication-manager>

</beans:beans>

我想在单独的文件中添加用户名和密码。

3 个答案:

答案 0 :(得分:0)

您可以使用:

 <context:property-placeholder location="classpath:myapp.properties" />

将属性文件添加到资源文件夹,确保其中包含属性

myapplication.username=soguha9@gmail.com
myapplication.password=soham
myapplication.authorities=ROLE_USER

然后在用户服务中使用如下属性:

 <property name="username" value="${myapplication.username}" />
 <property name="password" value="${myapplication.password}" />
 <property name="authorities" value="${myapplication.authorities}" />

答案 1 :(得分:0)

<authentication-manager>
    <authentication-provider user-service-ref="userServiceBean">        
    </authentication-provider>
</authentication-manager>

您可以具有自定义用户服务,该服务可以从属性文件读取用户详细信息。

答案 2 :(得分:0)

Spring Security Reference Guide中所述,您可以将user-service指向包含所需信息的属性文件。

users.properties中创建属性文件src/main/resources

soguha9@gmail.com=soham123,ROLE_USER,enabled

然后将user-service指向此文件

<user-service properties="classpath:users.properties" />