0

been trying to implement spring security to REST api but they work even without the username & password

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

private static String REALM="MY_TEST_REALM";

@Autowired
RestAuthenticationEntryPoint restAuthenticationEntryPoint;

@Autowired
public void ConfigureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication().withUser("admin").password("admin").roles("USER", "ADMIN");
}

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


@Bean
public RestAuthenticationEntryPoint gEntryPoint() {
    return new RestAuthenticationEntryPoint();
}


@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers(HttpMethod.OPTIONS, "/*");
}
}

Rest authetication entry point

public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint{


@Override
   public void commence(
     HttpServletRequest request,
     HttpServletResponse response, 
     AuthenticationException authException) throws IOException {

      response.sendError( HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized" );
   }
}

Rest Controller

@RestController
@RequestMapping(value = "/dray")
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class dray {

@RequestMapping(value = "/user", method = RequestMethod.GET)
@ResponseBody
public Auser getUser() {
    return new Auser("john", "carter");
}   
}

requests to jsp pages work fine, if user is not authenticated, he's redirected to the login form of spring security but rest api work without even asking for credentials, so how to send response 401 unauthorized if api used doesn't have the credentials?

Anshul..
  • 66
  • 1
  • 1
  • 10

0 Answers0