I am going through a spring security tutorial where I am trying to configure a basic security using the spring-boot-starter-security using the class like below
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/","/api/*").permitAll()
.anyRequest().authenticated().and().formLogin().loginPage("/login").permitAll()
.and().logout().permitAll();
}
@Autowired
public void ConfigureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().passwordEncoder(NoOpPasswordEncoder.getInstance())
.withUser("user").password("password").roles("USER");
}
}
But when I try to use the page localhost:8080 or localhost:8080/api/hello?name=test, it's not asking for login and directly showing the requested page. please help me with the issue.
CodePudding user response:
Code allows access without authentication for / and /api/*
http.authorizeRequests().antMatchers("/","/api/*").permitAll()
It restricts access without authentication to any requests which are not matched with above url
.anyRequest().authenticated()