Spring Boot BCryptPasswordEncoder Кодированный пароль не похож на BCrypt - PullRequest
0 голосов
/ 28 апреля 2018

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

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();
        }
}

My 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

1 Ответ

0 голосов
/ 08 июля 2018

В следующем коде вы фактически не кодируете свой клиентский секрет с помощью 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");
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...