我是一个有Spring安全性的新手,我想用数据库验证用户身份。 我已经创建了一个登录页面和一个带有jdbc的身份验证提供程序,如果用户存在于数据库中,则会对其进行检查。 但是我的代码没有这样做的问题,它允许所有用户登录! 我的代码有什么问题? 谢谢你的帮助。
@Component(value = "userService")
public class UserService implements AuthenticationProvider {
@Inject
@Named(value = "dataSource")
private DataSource dataSource;
ResultSet resultSet = null;
PreparedStatement preparedStatement = null;
Connection connection = null;
name=auth.getName();
pwd=auth.getCredentials().toString();
public Authentication authenticate(Authentication auth)
throws AuthenticationException {
final String select_auth = "select username,password from users where username='"+name+"' and password='"+pwd+"'";
try {
connection = dataSource.getConnection();
preparedStatement = connection.prepareStatement(select_auth);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
//what to return here ?
}
这是我的security-confg.xml:
<http auto-config="true">
<form-login login-page="/login" username-parameter="j_username"
password-parameter="j_password" default-target-url="/accueil"
authentication-failure-url="/403" />
<logout logout-success-url="/login" />
</http>
<authentication-manager>
<authentication-provider ref="userService">
</authentication-provider>
</authentication-manager>
答案 0 :(得分:0)
在代码中,我没有看到为查询设置用户名和密码的地方。您尝试获取名称和密码,并检查您的查询是否返回任何结果
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String select_auth = "select username,password from users where username=? and password=?";
String username = authentication.getName();
String password = (String) authentication.getCredentials();
preparedStatement = connection.prepareStatement(select_auth);
p.setString(1, username);
p.setString(2, password);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
List<SampleAuthority> authorities = new ArrayList<SampleAuthority>();
SampleAuthority a = new SampleAuthority();
authorities.add(a);
Collection<? extends GrantedAuthority> authorities1 = authorities;
return new UsernamePasswordAuthenticationToken(username, password, authorities1);
}
}
@Override
public boolean supports(Class<?> arg0) {
return true;
}
class SampleAuthority implements GrantedAuthority {
@Override
public String getAuthority() {
return "ROLE_USER";
}
}
在配置中,您可以添加
<intercept-url pattern="/**" access="hasRole('ROLE_USER')" />
<logout logout-url="/logout" />