java BCrypt:使用Spring Security的空密码

whlutmcx  于 2023-03-06  发布在  Java
关注(0)|答案(5)|浏览(186)

当尝试在Spring Boot应用程序中实现jwt-security时,我遇到了以下问题:
当我尝试通过Postman使用x-www-form-urlencoded登录时,我得到了**"Bad client credentials"(错误的客户端凭据)错误,而我知道凭据是正确的。
当我查看我的日志时,我看到
BCrypt给出了"Empty Encoded Password"警告**。这很奇怪,因为当我通过MySQL解释器查看数据库时,我在数据库中看到了正确加密的密码。

    • 信息**

我正在使用Hibernate构建MySQL数据库。
编译"组织。Spring框架。安全性。oauth: spring security -oauth 2:2.3.6.RELEASE"
编译"www.example.com:Spring安全-jwt:1.0.10.RELEASE"org.springframework.security:spring-security-jwt:1.0.10.RELEASE'
编译"org. springframework.引导:Spring引导启动器数据jpa"
Java 1.8.0版本_212
"我所尝试的"
在开始实现安全性之前,控制器、存储库和MySQL数据库都运行正常。
当我在网上搜索这个问题时,有些人认为它与"loadUserByUsername"函数有关。但是当我调试这个函数时,我注意到它根本没有被调用
我还尝试了允许程序中的每一个路径,并禁用crsf以防它与访问权限有关,但这两种方法都没有改变任何东西。(http.requestMatchers.andMatcher("/**").permitAll().and().csrf().disable();)
更新:当在数据库中放置NO用户时,我仍然得到相同的错误。

    • 部分代码:**

loadUserByUsername方法:

@Override
public UserDetails loadUserByUsername(String userName) {
    return userRepository.findByUsername(userName)
            .map(user -> new User(
                        user.getUsername(),
                        user.getPassword(),
                        UserRoleAuthority.getAuthorities(user.getRoles())
                ))
            .orElseThrow(() -> new UsernameNotFoundException("Unknown user: " + userName));

}

身份验证提供程序和密码编码器:

@Bean
public DaoAuthenticationProvider getAuthenticationProvider() {
    DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
    authenticationProvider.setUserDetailsService(userDetailsService);
    authenticationProvider.setPasswordEncoder(passwordEncoder());
    return authenticationProvider;
}

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

签名密钥:

@Bean
public JwtAccessTokenConverter jwtTokenEnhancer() {
    JwtAccessTokenConverter result = new JwtAccessTokenConverter();
    result.setSigningKey(signingKey);
    return result;
}

添加新用户:

userRepository.save(new User()
                            .withUsername("test")
                            .withPassword(passwordEncoder.encode("password"))
                            .withFirst("Admin")
                            .withLast("Nator")
                            .withEmail("test@notadmin.com")
                            .withRole(new HashSet<>(Arrays.asList(Role.Admin, Role.NotAdmin)))
            );

以及Http配置:

@Override
public void configure(HttpSecurity http) throws Exception {

    http.requestMatchers()
            .antMatchers("/iungo/*/**")
            .and()
            .authorizeRequests()
            .antMatchers("/iungo/system/**")
            .permitAll()
            .antMatchers("/iungo/**");
}

@Override
public void configure(HttpSecurity http) throws Exception {
    // We don't use this endpoint but we have to define it anyway in order to not enable web security on the whole application.
    http
            .userDetailsService(userDetailsService)
            .requestMatchers()
            .antMatchers("/oauth/authorize");
}

最后,我的"控制台"

2019-06-12 10:29:58.460  INFO 25207 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate Core {5.3.9.Final}
2019-06-12 10:29:58.461  INFO 25207 --- [           main] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
2019-06-12 10:29:58.532  INFO 25207 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
2019-06-12 10:29:58.599  INFO 25207 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2019-06-12 10:29:59.092  INFO 25207 --- [           main] o.h.t.schema.internal.SchemaCreatorImpl  : HHH000476: Executing import script 'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl@c30f26d'
2019-06-12 10:29:59.098  INFO 25207 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2019-06-12 10:29:59.382  WARN 25207 --- [           main] o.s.s.o.p.t.s.JwtAccessTokenConverter    : Unable to create an RSA verifier from verifierKey (ignoreable if using MAC)
2019-06-12 10:29:59.595  INFO 25207 --- [           main] o.s.s.web.DefaultSecurityFilterChain     : Creating filter chain: OrRequestMatcher [requestMatchers=[Ant [pattern='/oauth/token'], Ant [pattern='/oauth/token_key'], Ant [pattern='/oauth/check_token']]], [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@56a72887, org.springframework.security.web.context.SecurityContextPersistenceFilter@1ddba7a0, org.springframework.security.web.header.HeaderWriterFilter@7adbec34, org.springframework.security.web.authentication.logout.LogoutFilter@296bfddb, org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter@22ab1b8a, org.springframework.security.web.authentication.www.BasicAuthenticationFilter@54033a65, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@7dfec0bc, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@42734b71, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@3c8dea0b, org.springframework.security.web.session.SessionManagementFilter@6fe9c048, org.springframework.security.web.access.ExceptionTranslationFilter@526fc044, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@690e4b00]
2019-06-12 10:29:59.600  INFO 25207 --- [           main] o.s.s.web.DefaultSecurityFilterChain     : Creating filter chain: OrRequestMatcher [requestMatchers=[Ant [pattern='/iungo/*/**']]], [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@1978b0d5, org.springframework.security.web.context.SecurityContextPersistenceFilter@69a3bf40, org.springframework.security.web.header.HeaderWriterFilter@3186f8f5, org.springframework.security.web.authentication.logout.LogoutFilter@a4dcede, org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationProcessingFilter@760c777d, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@2c731a16, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@2a341e3d, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@6556471b, org.springframework.security.web.session.SessionManagementFilter@467cd4b9, org.springframework.security.web.access.ExceptionTranslationFilter@3f3f554f, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@d0e4972]
2019-06-12 10:29:59.603  INFO 25207 --- [           main] o.s.s.web.DefaultSecurityFilterChain     : Creating filter chain: OrRequestMatcher [requestMatchers=[Ant [pattern='/oauth/authorize']]], [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@6cf3b3d7, org.springframework.security.web.context.SecurityContextPersistenceFilter@462f8fe9, org.springframework.security.web.header.HeaderWriterFilter@24f2608b, org.springframework.security.web.csrf.CsrfFilter@713497cd, org.springframework.security.web.authentication.logout.LogoutFilter@56193e3a, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@3c6fc4cd, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@b2e1df3, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@2e785b28, org.springframework.security.web.session.SessionManagementFilter@12a9e864, org.springframework.security.web.access.ExceptionTranslationFilter@4b762988]
2019-06-12 10:29:59.731  INFO 25207 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-06-12 10:29:59.902  INFO 25207 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2019-06-12 10:29:59.903  INFO 25207 --- [           main] nl.highway.iungomain.Application         : Started Application in 2.937 seconds (JVM running for 3.345)
2019-06-12 10:29:59.923  INFO 25207 --- [           main] o.h.h.i.QueryTranslatorFactoryInitiator  : HHH000397: Using ASTQueryTranslatorFactory
2019-06-12 10:30:12.550  INFO 25207 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2019-06-12 10:30:12.550  INFO 25207 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2019-06-12 10:30:12.554  INFO 25207 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 4 ms
2019-06-12 10:30:12.632  WARN 25207 --- [nio-8080-exec-1] o.s.s.c.bcrypt.BCryptPasswordEncoder     : Empty encoded password
iyfjxgzm

iyfjxgzm1#

我发现了这个问题。我使用的是Sping Boot 2.1.4.RELEASE,但是这个设置只在1.5.12.RELEASE中有效。当然降级不是很好的做法,所以我仍然会尝试让它在2.1.4中工作。

f5emj3cl

f5emj3cl2#

必须在configureGlobal方法中添加bCryptPasswordEncoder

@Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .userDetailsService(userDetailsService)
            .passwordEncoder(bCryptPasswordEncoder());
    }
busg9geu

busg9geu3#

我也面临着同样的问题,在我的例子中,原因是我的CustomUserDetails类构造函数,它没有设置类的密码,所以它总是空的。
此答复的出处:why spring security gives empty password to password encoder?

xriantvc

xriantvc4#

我认为@ghazouanbadr的解决方案是正确的,尽管我在实践项目中采用了不同的实现方式:

@EnableWebSecurity
@Configuration
public class WebSecurity extends WebSecurityConfigurerAdapter {
    @Autowired
    UserService userService;
    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    public WebSecurity(UserService userService, BCryptPasswordEncoder bCryptPasswordEncoder) {
        this.userService = userService;
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
    } 

    @Override // Authorization
    protected void configure(HttpSecurity http) throws Exception {
        ...
    }

    @Override // Authentication
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userService(userService).passwordEncoder(bCryptPasswordEncoder);
   }
}

请注意,我创建这个类时才开始学习Java一个月左右。我对安全性的记忆不太清楚,所以我没有资格告诉你这是最好的方法。因为我记得我处理过同样的问题,所以我想它可能会引导你朝着正确的方向前进。

nmpmafwu

nmpmafwu5#

这个错误出现在我的代码中,位于Security中的UserPrincipal下,我的getter返回了null。

public String getEmail() {
    return null;
}

public String getPassword() {
    return null;
}

下面是它应该是什么:

public String getEmail() {
    return email;
}

public String getPassword() {
    return password;
}

相关问题