当前位置: 首页 > 知识库问答 >
问题:

Spring Boot BCryptPasswordEncoder编码的密码看起来不像BCrypt

刘兴朝
2023-03-14

我正在使用OAuth2和JPA编写spring boot REST安全API。当访问访问令牌时,我会收到警告,因为编码密码看起来不像BCrypt。当我点击邮递员http://localhost:8080/oauth/token的URL时?grant_type=password&username=user&password=user i get

WARN 26648 --- [nio-8080-exec-2] o.s.s.c.bcrypt.BCryptPasswordEncoder     : Encoded password does not look like BCrypt
{
    "timestamp": "2018-04-28T12:05:53.462+0000",
    "status": 401,
    "error": "Unauthorized",
    "message": "Unauthorized",
    "path": "/oauth/token"
}

我已经定义了Bean和存储库。我已经使用了secret(“{bcrypt}”和secret(“{noop}”),但两者都没有帮助。如果有任何帮助,我将不胜感激。下面是应用程序的详细信息

授权服务器

@Configuration
@EnableAuthorizationServer

public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

@Autowired
private PasswordEncoder passwordEncoder;

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        // TODO Auto-generated method stub
        endpoints.authenticationManager(authenticationManager);
         //.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);;
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        // TODO Auto-generated method stub
        security.checkTokenAccess("isAuthenticated()");
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        // TODO Auto-generated method stub


        clients.inMemory().withClient("my-trusted-client")
        .authorizedGrantTypes("client_credentials", "password")
        .authorities("ROLE_CLIENT","ROLE_TRUSTED_CLIENT").scopes("read","write","trust")
        .resourceIds("oauth2-resource").accessTokenValiditySeconds(5000).secret("{bcrypt}secret");
    }

}

资源服务器

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

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

        http.headers().frameOptions().disable().and()
        .authorizeRequests()
        .antMatchers("/","/home","/register","/login").permitAll()
        .antMatchers("/asd/**").authenticated();
    }

}
@Service
public class UserService extends WebSecurityConfigurerAdapter {
     @Autowired
        private UserRepository repo;

     @Autowired
     private BCryptPasswordEncoder  passwordEncoder;


     public void save(User user){
          // user.setPassword(getPasswordEncoder().encode(user.getPassword()));
         user.setPassword(passwordEncoder.encode(user.getPassword()));
         // user.setPassword(user.getPassword());
         repo.save(user);
        }


     @Bean
        @Override
        public AuthenticationManager authenticationManager() throws Exception {

            return super.authenticationManager();
        }
}
public class CustomUserDetails implements UserDetails {

    private String username;
    private String password;
    Collection <? extends GrantedAuthority> authorities;

    public CustomUserDetails(User username) {
        this.username= username.getUsername();
        this.password=username.getPassword();
         this.authorities = translate(username.getRoles());

    }

    private Collection<? extends GrantedAuthority> translate(List<Role> roles) {
        List<GrantedAuthority> authorities = new ArrayList<>();
        for (Role role : roles) {
            String name = role.getName().toUpperCase();
            //Make sure that all roles start with "ROLE_"
            if (!name.startsWith("ROLE_"))
                name = "ROLE_" + name;
            authorities.add(new SimpleGrantedAuthority(name));
        }
        return authorities;
    }


    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        // TODO Auto-generated method stub
        return authorities;
    }

    @Override
    public String getPassword() {
        // TODO Auto-generated method stub
        return password;
    }

    @Override
    public String getUsername() {
        // TODO Auto-generated method stub
        return username;
    }

    @Override
    public boolean isAccountNonExpired() {
        // TODO Auto-generated method stub
        return true;
    }
@ComponentScan
@SpringBootApplication
@Configuration
@EnableWebSecurity
public class SpringBootOauth2Application {

    /*@Autowired
    private PasswordEncoder passwordEncoder;
    */
    public static void main(String[] args) {
        SpringApplication.run(SpringBootOauth2Application.class, args);
    }


    @Bean
    public BCryptPasswordEncoder  getPasswordEncoder() {
       return new BCryptPasswordEncoder();

 }

    @Autowired
    public void authenticationManager(AuthenticationManagerBuilder builder, UserRepository user, UserService service) throws Exception
    {
        if(user.count()==0)
            service.save(new User("user","user", Arrays.asList(new Role("USER"), new Role("ACTUATOR"))));

        builder.userDetailsService(userDetailsService(user)).passwordEncoder(getPasswordEncoder());
    }
    private UserDetailsService userDetailsService(final UserRepository repository) {
        return username -> new CustomUserDetails(repository.findByUsername(username));
    }

}

Application.Properties

spring.datasource.url=jdbc:mysql://localhost:3306/db1
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.security.oauth2.resource.filter-order=3

spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl


spring.jpa.hibernate.ddl-auto=create-drop

spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect


 spring.jpa.properties.hibernate.hbm2ddl.auto = update

spring.jpa.properties.hibernate.show_sql=true

共有1个答案

戚翰飞
2023-03-14

在下面的代码中,您实际上并没有使用Bcrypt对客户端机密进行编码。

clients.inMemory().withClient("my-trusted-client")
        .authorizedGrantTypes("client_credentials", "password")
        .authorities("ROLE_CLIENT","ROLE_TRUSTED_CLIENT").scopes("read","write","trust")
        .resourceIds("oauth2-resource").accessTokenValiditySeconds(5000).secret("{bcrypt}secret");

用像...

accessTokenValiditySeconds(5000).secret("{bcrypt}$2a$10$ePPx/3nSFjJA2ZQTr2T1rOnpO3hWiWt.GmUj0wL.Xh9sEzUSWrrYm");
 类似资料:
  • 我无法使用正确的详细信息登录,因为程序不断声明编码的密码看起来不像bcrypt。有人知道怎么解决这个吗?我正在使用JDBC身份验证。 我也有正确的数据库表,有足够的空间用于编码密码。我不确定哪里出了问题。 JSP表单: 安全配置: 登录控制器 我的数据库:这里

  • 我最近遵循了Spring boot安全中的身份验证和授权教程,我想我在谈到sql时迷路了。尽管它没有显示任何错误,即使我输入了正确的用户名和密码,它仍然显示错误的凭据。这是我的代码: UserDetailsServiceImpl.java WebUserMapper.java WebSecurityConfig.java 这是我的数据库: 它返回以下错误: 密码是123。我不知道为什么它不工作,即

  • 即使输入了正确的电子邮件和密码,同样的错误也会一次又一次地出现。 更多参考请参见我的回复-https://github.com/ajitlol404/smartcontactmanager/tree/master/smartcontactmanager 控制台错误

  • 我有一个spring boot 1.5.9授权服务器,它使用BCrypt存储密码。我正在尝试迁移到2.0,但是,我不再能够检索授权令牌。 服务器的响应是: 控制台输出以下内容:。 这部分应用程序以前工作得很好。我所做的唯一更改是build.gradle文件(更改、添加插件和添加。 中的密码哈希逻辑可在两个单独的配置文件中找到: 而且 OAuthUser类: 我知道spring的安全有很大的变化,但

  • 问题内容: 我正在尝试使用JWT实施spring AuthorizationServer。我能够生成JWT令牌并登录,直到将BCrypt添加到混合中为止。现在,当我尝试登录时,我从API获得“错误的凭据”。 OAuth2Configuration.java WebSecurityConfig.java SeedData.java 谢谢你的帮助。 问题答案: 我需要进行以下更改才能使其正常工作。如果

  • 我正在使用spring boot,spring安全,OAuth2和JWT来验证我的应用程序,但我一直得到这个令人讨厌的错误,我不知道什么是错误的。我的类: : : 除: 我的实体模型类是: 实体: 实体: 我在数据库中的密码是正确加密的spring安全BCrypt,它的数据类型是varchar(255),大于60。