BaDr Amer
BaDr Amer

Reputation: 910

jQuery Ajax doesn't hit spring boot API

I want to call a web service on the server using jQuery Ajax from a web page, it returns 302 (redirect the request to access-denied page). I am adding my code below:

jQuery Code:

$.ajax({
        type: "POST",
        contentType: "application/json",
        url: "/posts",
        data: JSON.stringify(obj),
        success: function (data) {

        },
        error: function (e) {

        }
    });

WebSecurityConfigurerAdapter Code

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/", 
                        "/css/**",
                        "/js/**").permitAll()
                    .antMatchers("/user/**").hasRole("ROLE_ADMIN")
                    .anyRequest().authenticated()
                .and()
                    .exceptionHandling().accessDeniedHandler(accessDeniedHandler);
    }

and my accessDeniedHandler looks like this:

@Component
public class LoggingAccessDeniedHandler implements AccessDeniedHandler {   
    @Override
    public void handle(HttpServletRequest request,
                       HttpServletResponse response,
                       AccessDeniedException ex) throws IOException, ServletException {

        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        // auth has a value
        if (auth != null) {
           // log
        } 
        response.sendRedirect(request.getContextPath() + "/access-denied"); 
    }
}

I don't know what I'm doing wrong, Why is my Ajax request goes to AccessDeniedHandler?

Upvotes: 0

Views: 197

Answers (1)

Alien
Alien

Reputation: 15878

Try disabling the csrf token in protected void configure(HttpSecurity http) this method like below.

http.csrf().disable()

You can refer this thread for more clarification.

Upvotes: 1

Related Questions