我想使用jQuery Ajax从网页上调用服务器上的Web服务,它返回302(将请求重定向到拒绝访问的页面)。我在下面添加我的代码:
jQuery代码:
$.ajax({
type: "POST",
contentType: "application/json",
url: "/posts",
data: JSON.stringify(obj),
success: function (data) {
},
error: function (e) {
}
});
WebSecurityConfigurerAdapter代码
@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);
}
和我的 accessDeniedHandler 如下:
@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");
}
}
我不知道我在做什么错,为什么我的Ajax请求转到AccessDeniedHandler?
答案 0 :(得分:1)
尝试像下面这样在protected void configure(HttpSecurity http)
中禁用csrf令牌。
http.csrf().disable()
您可以参考this主题以获取更多说明。