Create a REST API
SampleController.java
@RestController
public class SampleController {
@GetMapping("/hi")
public String hi() {
return "I want know how API works";
}
}
Add Spring Security dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
Config WebSecurityConfig.java
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.httpBasic(withDefaults())
.authorizeRequests()
.antMatchers("/", "/home", "/logout").permitAll()
.anyRequest().authenticated();
}
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.passwordEncoder(passwordEncoder())
.withUser("user")
.password(passwordEncoder().encode("user"))
.roles("USER");
}
}
Note:
httpBasic
needs to be before theauthorizeRequests
, otherwise it won’t work
Test with postman
GET localhost:8080/hi
Authorization / Basic Auth / username + password
On second time, you found it doesn’t need the auth, you need to clean the cookie
Cookies / delete all
Test with browser
localhost:8080/hi, input your username and password to get the API content