如何在spring security中使用jdbc从oracle数据库验证用户?

时间:2015-07-28 14:11:21

标签: java jsp spring-mvc spring-security

我是春季Mvc的新手。我创建了一个login.jsp页面,我想使用spring security从数据库动态验证用户。

这是我的春季安全配置:

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

这是我的userService:

@Component(value = "userService")
public class UserService implements AuthenticationProvider {
    @Inject
    @Named(value = "dataSource")
    private DataSource dataSource1;

    final String select_auth = "select username,password from users";

    public Authentication authenticate(Authentication auth) throws AuthenticationException {
        ResultSet resultSet = null;
        PreparedStatement preparedStatement = null;
        Connection connection = null;
        try {
            connection = dataSource1.getConnection();
            preparedStatement = connection.prepareStatement(select_auth);
            resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                String name=resultSet.getString("username");
                String pwd =resultSet.getString("password");
                if (name.equals("what?")){
                }
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {

                }
            }
            if (preparedStatement != null) {
                try {
                    preparedStatement.close();
                } catch (SQLException e) {

                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {

                }
            }
        }

        return new UsernamePasswordAuthenticationToken("", "");
    }

    public boolean supports(Class<?> arg0) {
        return true;
    }
}

与数据库的连接有效,但我的问题是如何从login.jsp获取输入并测试数据库中的用户名和密码是否相同?

如果用户存在于数据库中,该返回什么?

1 个答案:

答案 0 :(得分:0)

用户名和密码存储在身份验证对象

    String username = auth.getName();
    String password = auth.getCredentials().toString();

所以你可以根据你的数据库数据检查它们(正如我在评论中所建议的那样)。

    final String select_auth = "select username,password from users WHERE username=?"; // Use your prepared statement to bind the username

获得记录后(如果存在),您可以使用PasswordEncoder检查密码(希望您的密码 编码,例如加密/散列)。然后,例如。

    return new UsernamePasswordAuthenticationToken(new MyUserDetails(username, password, ...), password); // There is also a constructor that accepts granted authorities