How to prevent browser to invoke basic auth popup and handle 401 error using Jquery?

后端 未结 11 1230
隐瞒了意图╮
隐瞒了意图╮ 2020-11-27 12:18

I need to send authorization request using basic auth. I have successfully implemented this using jquery. However when I get 401 error basic auth browser popup is opened and

11条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-27 12:59

    From back side with Spring Boot I've used custom BasicAuthenticationEntryPoint:

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().authorizeRequests()
                ...
                .antMatchers(PUBLIC_AUTH).permitAll()
                .and().httpBasic()
    //    https://www.baeldung.com/spring-security-basic-authentication
                .authenticationEntryPoint(authBasicAuthenticationEntryPoint())
                ...
    
    @Bean
    public BasicAuthenticationEntryPoint authBasicAuthenticationEntryPoint() {
        return new BasicAuthenticationEntryPoint() {
            {
                setRealmName("pirsApp");
            }
    
            @Override
            public void commence
                    (HttpServletRequest request, HttpServletResponse response, AuthenticationException authEx)
                    throws IOException, ServletException {
                if (request.getRequestURI().equals(PUBLIC_AUTH)) {
                    response.sendError(HttpStatus.PRECONDITION_FAILED.value(), "Wrong credentials");
                } else {
                    super.commence(request, response, authEx);
                }
            }
        };
    }
    

提交回复
热议问题