SpringBoot Security&MongoRepository如何按用户名和密码提取用户

huangapple 未分类评论57阅读模式
标题翻译

SpringBoot Security & MongoRepository how to fetch user by username and password

问题

我有一个使用Spring Boot的应用程序,使用MongoDB作为数据库。我正在使用Spring Security来保护我的端点:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

然而,我想引入一个登录端点,用户将能够提供用户名和密码。一旦我获得他们的凭据,我将验证是否在MongoDB中存在具有此密码和用户名的用户。我尝试从MongoDB中通过用户名和密码检索用户的所有尝试都失败了。

我的仓库看起来像这样:

public interface UserRepository extends MongoRepository<User, String> {

    @Query("{'username' : ?0}")
    User findUserByUsername(String username);
    
    @Query("{username : ?0, password : ?1}")
    User findUserByUsernameAndPassword(String username, String password);
}

方法User findUserByUsernameAndPassword(String username, String password)总是返回null,即使在数据库中存在这样的用户。

应用程序以以下配置启动:

@SpringBootApplication
public class AccountApplication {

    @Bean
    RestTemplate restTemplate() {
        return new RestTemplate();
    }

    public static void main(String[] args) {
        SpringApplication.run(AccountApplication.class, args);
    }
}
@EnableWebSecurity
@Configuration
class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
            .addFilterAfter(new JWTAuthorizationFilter(), UsernamePasswordAuthenticationFilter.class)
            .authorizeRequests()
            .antMatchers(HttpMethod.POST, "/id/login", "/users").permitAll()
            .antMatchers(HttpMethod.GET, "/users").permitAll()
            .anyRequest().authenticated();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

即使我试图注释掉这一行:.addFilterAfter(new JWTAuthorizationFilter(), UsernamePasswordAuthenticationFilter.class),仍然无法通过用户名和密码获取用户。

我如何通过用户名和密码获取用户?

编辑
我在这里找到了解决方案:https://stackoverflow.com/questions/56397924/why-spring-security-gives-empty-password-to-password-encoder

我忘记设置密码字段的Getter方法。

英文翻译

I have Spring boot app that uses mongo as db. I am using spring-security to secure my endpoints:

    &lt;dependency&gt;
		&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
		&lt;artifactId&gt;spring-boot-starter-security&lt;/artifactId&gt;
	&lt;/dependency&gt;

However I would like to introduce login endpoint where users will be able to provide username & password. Once I have their credentials I am going to verify if such user (with this password and username) exists in mongodb. All of my attempts to retrieve the user by username and password from Mongodb failed.

My repository looks like:

public interface UserRepository  extends MongoRepository&lt;User, String&gt; {

@Query(&quot;{ &#39;username&#39; : ?0 }&quot;)
User findUserByUsername(String username);

@Query(&quot;{username : ?0, password : ?1}&quot;)
User findUserByUsernameAndPassword(String username, String password);
 }

method User findUserByUsernameAndPassword(String username, String password); always returns null even though such user exists in db.

Application starts with the following configuration:

@SpringBootApplication

public class AccountApplication {

@Bean
RestTemplate restTemplate() {
	return new RestTemplate();
}

public static void main(String[] args) {
	SpringApplication.run(AccountApplication.class, args);
}

}

@EnableWebSecurity
@Configuration
class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
	http.csrf().disable()
			.addFilterAfter(new JWTAuthorizationFilter(), UsernamePasswordAuthenticationFilter.class)
			.authorizeRequests()
			.antMatchers(HttpMethod.POST, &quot;/id/login&quot;, &quot;/users&quot;).permitAll()
			.antMatchers(HttpMethod.GET,  &quot;/users&quot;).permitAll()
			.anyRequest().authenticated();
}

@Bean
public PasswordEncoder passwordEncoder() {
	return new BCryptPasswordEncoder();
}

}

Even if I tried to comment this row: .addFilterAfter(new JWTAuthorizationFilter(), UsernamePasswordAuthenticationFilter.class)
the user can not be fetched by username and password.

How I can fetch the user by username and password?

Thanks in advance!

EDIT
I founded the solution here: https://stackoverflow.com/questions/56397924/why-spring-security-gives-empty-password-to-password-encoder

I forgot to set Getter of password field.

huangapple
  • 本文由 发表于 2020年5月31日 05:01:53
  • 转载请务必保留本文链接:https://java.coder-hub.com/62108629.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定