Spring Boot BCryptPasswordEncoder Закодированный пароль не похож на BCrypt

Я пишу безопасный API REST для весенней загрузки с использованием OAuth2 и JPA. При доступе к токену доступа я получаю ПРЕДУПРЕЖДЕНИЕ, поскольку закодированный пароль не похож на BCrypt. Пока я нажимаю URL-адрес почтальона http: // localhost: 8080 / oauth / token? grant_type = пароль и имя пользователя = пользователь и пароль = пользователь я получил

WARN 26648 --- [nio-8080-exec-2] o.s.s.c.bcrypt.BCryptPasswordEncoder     : Encoded password does not look like BCrypt

И в почтальоне с результатом Basic Auth возвращается как 401

{
    "timestamp": "2018-04-28T12:05:53.462+0000",
    "status": 401,
    "error": "Unauthorized",
    "message": "Unauthorized",
    "path": "/oauth/token"
}

Я определил компонент и репозиторий. Я использовал 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();
        }
}

Мой CustomUserDetails

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

Может помочь stackoverflow.com/…

Raymond Nijland 28.04.2018 14:28

@RaymondNijland, спасибо, человек, это сработало, мы также должны убедиться, что кодируем секрет клиента.

Mohit Darmwal 29.04.2018 06:01
Освоение архитектуры микросервисов с Laravel: Лучшие практики, преимущества и советы для разработчиков
Освоение архитектуры микросервисов с Laravel: Лучшие практики, преимущества и советы для разработчиков
В последние годы архитектура микросервисов приобрела популярность как способ построения масштабируемых и гибких приложений. Laravel , популярный PHP...
Как построить CRUD-приложение в Laravel
Как построить CRUD-приложение в Laravel
Laravel - это популярный PHP-фреймворк, который позволяет быстро и легко создавать веб-приложения. Одной из наиболее распространенных задач в...
Освоение PHP и управление базами данных: Создание собственной СУБД - часть II
Освоение PHP и управление базами данных: Создание собственной СУБД - часть II
В предыдущем посте мы создали функциональность вставки и чтения для нашей динамической СУБД. В этом посте мы собираемся реализовать функции обновления...
Документирование API с помощью Swagger на Springboot
Документирование API с помощью Swagger на Springboot
В предыдущей статье мы уже узнали, как создать Rest API с помощью Springboot и MySql .
Роли и разрешения пользователей без пакета Laravel 9
Роли и разрешения пользователей без пакета Laravel 9
Этот пост изначально был опубликован на techsolutionstuff.com .
Как установить LAMP Stack - Security 5/5 на виртуальную машину Azure Linux VM
Как установить LAMP Stack - Security 5/5 на виртуальную машину Azure Linux VM
В предыдущей статье мы завершили установку базы данных, для тех, кто не знает.
1
2
3 928
1

Ответы 1

В следующем коде вы фактически не кодируете свой секрет клиента с помощью 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");

Другие вопросы по теме