![](/img/trans.png)
[英]How to configure open fire to authenticate users from external database?
[英]How to authenticate users from database with an authentication provider?
我是Spring Security的新手,我想使用數據庫對用戶進行身份驗證。 我創建了一個登錄頁面和一個帶有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>
在代碼中,我看不到為查詢設置用戶名和密碼的地方。 您嘗試獲取名稱和密碼,並檢查查詢是否返回任何結果
@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" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.