Spring-security 不存在 AJAX 请求(302 错误)

Spring-security does not exists AJAX requests (302 error)

提问人:Dmitry Anokhin 提问时间:7/26/2023 更新时间:7/26/2023 访问量:33

问:

我正在尝试通过电子邮件检查唯一性。该请求通过 AJAX 发送。我收到 302 错误(我可以在浏览器中看到此错误)。我认为我的 Spring-security 不允许请求并尝试重定向到登录页面(当我授权时,我收到相同的错误 302)。如果我允许此请求 checkUserEmail,为什么会出现 302 错误?

这里是 AJAX 请求

$("#userLogin").click(function (event)
    {       
        event.preventDefault(); 
            
        var inputValue = document.getElementById("userLogin");
        
        inputValue.addEventListener("input", function (e)
        {
            var request = 
            {
                query: inputValue.value
            };  
                
            $.ajax(
            {
                type: "POST",
                contentType: "application/json",
                url: "checkUserEmail",
                data: JSON.stringify(request),
                dataType: 'json',
                cache: false,
                timeout: 600000,
                success: function(response)
                {                   
                    if (!response)
                    {           
                        alert("This email '" + inputValue.value + "' is already in use.");
                        
                        inputValue.value = "";                  
                    }
                },
                error: function(err)
                {
                    console.log(err);
                }
            });
        })      
    });

这里是弹簧控制器

@RequestMapping(value = { "/checkUserEmail" }, method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<Object> checkUserEmail(@RequestBody AjaxRequest request)
    {
        AD_User currentUser = userService.getCurrentAuthorizeUser();

        String  userEmail   = request.getQuery().toLowerCase();
        boolean result      = true;

        if (userEmail != null && !userEmail.isEmpty())
        {
            if (currentUser == null || !userEmail.equals(currentUser.getEmail()))
            {
                result = userService.getUserByEmail(userEmail).isEmpty();
            }
        }

        return new ResponseEntity<Object>(result, HttpStatus.OK);
    }

这里是 Spring 安全性(在此代码中,我正在尝试禁用 csrf,但它不起作用

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter
{
    private final UserDetailsService userDetailsService;

    @Autowired
    public SecurityConfig(@Qualifier("userDetailsServiceImpl") UserDetailsService userDetailsService)
    {
        this.userDetailsService = userDetailsService;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception
    {
        http
        .authorizeRequests()
        .antMatchers("/",
                "/about",
                "/getEventsByCity",
                "/sortEvents",
                "/buyService",
                "/checkUserPhone",
                "/getAllTags",
                "/getAllSpecialisations",
                "/checkUserEmail",
                "/forgotPassword",
                "/restorePassword",
                "/404",
                "/filterSearchEvents",
                "/500",
                "/about",
                "/eventCatalog",
                "/createEvent",
                "/eventStatic/**",
                "/activateAccount/**",
                "/events/**/**",
                "**/checkUserPhone",
                "/serviceCatalog",
                "/service/**/**",
                "/createService**",
                "/createService",
                "/robots.txt",
                "/error",
                "/authorized")
        .permitAll()
        .antMatchers("/resources/**", "/ts/**",  "/fonts/**", "/img/**", "/json/**", "/text/**", "/video/**", "/static/**", "/home/dru/uploads/**",
            "data:image/**", "/images/**", "/php/**",
            "/sections/**", "/css/**", "/js/**", "/static/error/**", "/", "C:/home/phantomjs-2.1.1-windows/bin/**")
        .permitAll()
        .anyRequest()
        .authenticated()
        .and()
        .formLogin()
        .loginPage("/authorized").permitAll()
        .failureUrl("/failure")
        .and()
        .logout()
        .logoutRequestMatcher(new AntPathRequestMatcher("/logout", HttpMethod.GET.name()))
        .invalidateHttpSession(true)
        .clearAuthentication(true)
        .deleteCookies("JSESSIONID")
        .and()
        .csrf().disable().cors();       
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception
    {
        auth.authenticationProvider(daoAuthenticationProvider());
    }

    @Bean
    protected DaoAuthenticationProvider daoAuthenticationProvider()
    {
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setPasswordEncoder(SecurityMechanism.passwordEncoder());
        daoAuthenticationProvider.setUserDetailsService(userDetailsService);
        daoAuthenticationProvider.setHideUserNotFoundExceptions(false);
        
        return daoAuthenticationProvider;
    }
    
}

这里是我的application.properties(我通过“*”隐藏了此文件中的密码和一些设置)

spring.datasource.url=jdbc:postgresql://localhost:5432/attraction
spring.datasource.username=***
spring.datasource.password=***
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=false
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQL81Dialect

spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=***
spring.mail.password=***
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true

hostname=***

upload.path=***

server.error.whitelabel.enable=true
spring.mvn.throw-exception-if-no-handler-found=true

在这个镜头下,当我尝试发送AJAX请求时,这是我的错误(在Java中我没有出现任何错误)。如您所见,首先我收到 302 错误

这是我的异常控制器

@Controller
public class ExceptionController
{
    private static final Logger LOG = LoggerFactory.getLogger(ExceptionController.class);
    
    @Autowired
    private UserService userService;
    
    @GetMapping("/failure")
    public ModelAndView getFailurePage(HttpServletRequest servletRequest, HttpServletResponse servletResponse, ModelMap model)
    {
        userService.getCurrentAuthorizeUser();
        
        HttpSession httpSession = servletRequest.getSession(false);
        
        if (httpSession != null)
        {
            AuthenticationException ex = (AuthenticationException) httpSession.getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);            
            
            if (ex != null)
            {
                model.addAttribute("showLoginForm", "login");
                model.addAttribute("exceptionMessage", "Bad credentials");
                        
                return new ModelAndView("authorized", model);
            }
        }

        return new ModelAndView("redirect:/error/" + ErrorPages.INTERNAL_SERVER_ERROR_500, model);          
    }
    
    @GetMapping("/error")
    public RedirectView getErrorPage(RedirectAttributes attr, HttpServletResponse servletResponse)
    {
        AD_User currentUser = userService.getCurrentAuthorizeUser();
        
        attr.addFlashAttribute("flashAttribute", currentUser);
        
        if (servletResponse.getStatus() == 404)
        {
            return new RedirectView("/error/" + ErrorPages.NOT_FOUND_PAGE_404);
        }
        
        return new RedirectView("/error/" + ErrorPages.INTERNAL_SERVER_ERROR_500);
    }
    
}

这是我的异常处理程序

@ControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
public class ExceptionHandlerFilter extends GenericFilterBean
{

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException
    {
        try
        {
            chain.doFilter(req, res);
        }
        catch (RequestRejectedException e)
        {
            HttpServletRequest  request  = (HttpServletRequest) req;
            HttpServletResponse response = (HttpServletResponse) res;

            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }

    }
}

是什么阻止我发送 AJAX 请求?

我尝试禁用 csrf,但没有帮助。我还尝试启用 sef 以在 AJAX 请求标头中使用 _csrf.token 请求进行传输,但出现 403 错误。

ajax spring-mvc spring-security https http-status-code-302

评论


答: 暂无答案