简体   繁体   中英

spring security Rest API error -403 forbidden

Im using Spring security on a spring boot project, and Im trying to use a endpoint of my controller, but when i make the call from my js, I get the error: 403 forbidden.

My SecurityConfig:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .authorizeRequests()
            .antMatchers("/resources/**").permitAll()
            .anyRequest().authenticated()
            .and()
            .formLogin()
            .loginPage("/login/")
            .defaultSuccessUrl("/inicio/")
            .usernameParameter("username").passwordParameter("password")
            .permitAll()
            .and()
            .logout().logoutSuccessUrl("/login/")
            .permitAll();
}

  @Override
  public void configure(AuthenticationManagerBuilder auth) throws    Exception   {
      auth
          .userDetailsService(userDetailsService)
          .passwordEncoder(new BCryptPasswordEncoder());

}

My controller endpoint:

 @RequestMapping( value="/getUsuarios")
 @ResponseBody
public UsuarioTo getUsuarios( Model model) throws Exception {
    UsuarioTo to = getTo();

    try
    {
        to.setListaUsuario(usuarioRepository.findAll());
    }catch (Exception e)
    {
        throw new  Exception("Error al obtener los usuarios "+e.getMessage() );
    }


    return to;
}

My Ajax call:

function getUsers(callback)
 {

  var posting = $.post( Endpoint +'getUsuarios', function(data) {

   if (callback)callback(data.listaUsuario);
})
  .done(function() {

  })
  .fail(function(ex) {
    message("error","ocurrio un error al obtener los usuarios:"    +ex.status+ ex.statusText+ ex.responseJSON.error);

  })
  .always(function() {
  });

  posting.always(function() {
  });
 }

You need to either send the csrf token along with your request ( https://docs.spring.io/spring-security/site/docs/current/reference/html/csrf.html#csrf-include-csrf-token-ajax ) or disable csrf for this request.

As you did not configure csrf, the default setting is used so that the csrf token is required for every post.

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