简体   繁体   中英

Securing a api with an token in Spring Boot

We have a simple application with only two consumers and 5 endpoints. For one endpoint I need some way of authentication. I like the stripe way of doing this, but I don't know how I can build this in spring boot.

"Authentication to the API is performed via HTTP Basic Auth. Provide your API key as the basic auth username value. You do not need to provide a password."

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
http
    .authorizeRequests()
    .antMatchers("/qr")
    .hasRole("user")
    .and()
    .sessionManagement()
    .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
    .and()
    .httpBasic()
    .and()
    .csrf()
    .disable();
}

@Bean
public UserDetailsService userDetailsService() {
val encodedPassword = new BCryptPasswordEncoder().encode("test");

final InMemoryUserDetailsManager manager = new               InMemoryUserDetailsManager();
   manager.createUser(User.withUsername("admin").password(encodedPassword).roles("user").build());
           //manager.createUser(User.withUsername("admin").roles("user").build());

  return manager;
}

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

I tried to remove the password from manager.createUser but this doesn't work.

Basic authentication is made of user:password in base64 encoded form. So your user must have a password equal to empty string for Basic Authentication to work. You can also get rid of BCryptPasswordEncoder and use NoOpPasswordEncoder since you don't use the password value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM