gpt4 book ai didi

java - 在 Spring Security 中从文件中读取/添加用户凭据

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:03:58 24 4
gpt4 key购买 nike

是否可以在 Spring Security 的文件中存储和修改用户凭据?

现在我有 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-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd">
<http>
<intercept-url pattern="/**" access="ROLE_USER" />
<form-login />
<logout />
</http>

<authentication-manager>
<authentication-provider>
<user-service>
<user name="admin" password="admin" authorities="ROLE_USER, ROLE_ADMIN" />
<user name="user" password="user" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>

我只想将信息存储在 users.txt 或 users.xml 之类的文件中,并可以动态添加或修改用户/密码。

最佳答案

你需要为此覆盖UserDetailsS​​ervice

UserDao.java

import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

/**
* @author asif.hossain
* @since 3/9/17.
*/
public class UserDao implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

String password = readPasswordFromFileOrDatabase(username);

if (password == null) throw new UsernameNotFoundException("");

return User
.withUsername(username)
.password(password)
.authorities("ROLE_USER")
.build();
}

private String readPasswordFromFileOrDatabase(String username) {
// Edit this code and read password and roles from data base or files
if (username.equals("user")) return "password";
return null;
}
}

并在security.xml

中添加一个该类的bean
<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.xsd">
<http>
<intercept-url pattern="/**" access="ROLE_USER" />
<form-login />
<logout />
</http>

<bean id="userDao" class="UserDao"></bean>

<authentication-manager alias="authenticationManager">
<authentication-provider user-service-ref="userDao"></authentication-provider>
</authentication-manager>

关于java - 在 Spring Security 中从文件中读取/添加用户凭据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42690732/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com