首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ionic4 HTTP请求

ionic4 HTTP请求
EN

Stack Overflow用户
提问于 2017-06-14 23:32:12
回答 1查看 200关注 0票数 2

我有一个,我也试图从一个ionic4 web应用程序发送POST请求。不幸的是,我无法让登录帖子工作。当HTTP 401403200只发送飞行前选项请求时,我会收到它。

我已经在StackOverflow上检查过类似的帖子,比如,但是它们只是改变了我所得到的错误。下面是我从不同的教程中获取了一些信息后得出的结论&其他的文章。

不确定我的错误是否与Spring、SecurityConfiguration或TypeScript post请求有关。

我的Spring安全配置

代码语言:javascript
复制
@EnableWebSecurity
@Configuration
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
@EnableGlobalMethodSecurity(securedEnabled = true)
class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {

        http
            .authorizeRequests()

            .requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
            .antMatchers("/login").permitAll()
            .antMatchers(HttpMethod.OPTIONS).permitAll()
            .anyRequest().authenticated()
            .and()
            .addFilterBefore(new RestConfig().corsFilter(), CsrfFilter.class)
            .csrf().csrfTokenRepository(csrfTokenRepository()).and().addFilterAfter(csrfHeaderFilter(), CsrfFilter.class)
            .formLogin().loginProcessingUrl("/login")
            .successHandler(successHandler())
            .failureHandler(failureHandler())
            .and()
            .exceptionHandling()
            .and()
            .csrf().disable();
    }

    private AuthenticationSuccessHandler successHandler() {
        return new AuthenticationSuccessHandler() {

            @Override
            public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
                httpServletResponse.getWriter().append("OK");
                httpServletResponse.setStatus(200);
            }
        };
    }

    private AuthenticationFailureHandler failureHandler() {
        return new AuthenticationFailureHandler() {

            @Override
            public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
                httpServletResponse.getWriter().append("Authentication failure");
                httpServletResponse.setStatus(401);
            }
        };
    }

    private AccessDeniedHandler accessDeniedHandler() {
        return new AccessDeniedHandler() {

            @Override
            public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
                httpServletResponse.getWriter().append("Access denied");
                httpServletResponse.setStatus(403);
            }
        };
    }

    private AuthenticationEntryPoint authenticationEntryPoint() {
        return new AuthenticationEntryPoint() {

            @Override
            public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
                httpServletResponse.getWriter().append("Not authenticated");
                httpServletResponse.setStatus(401);
            }
        };
    }

    private Filter csrfHeaderFilter() {
        return new OncePerRequestFilter() {

            @Override
            protected void doFilterInternal(HttpServletRequest request,
                                        HttpServletResponse response, FilterChain filterChain)
                throws ServletException, IOException {
                     CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
                     if (csrf != null) {
                         Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
                        String token = csrf.getToken();
                        if (cookie == null || token != null
                        && !token.equals(cookie.getValue())) {
                            cookie = new Cookie("XSRF-TOKEN", token);
                            cookie.setPath("/");
                            response.addCookie(cookie);
                        }
                    }
                response.setHeader("Access-Control-Allow-Origin", "*");
                response.setHeader("Access-Control-Allow-Headers", "*");
                response.setHeader("Access-Control-Allow-Credentials", "*");
                response.setHeader("Access-Control-Allow-Methods", "*");
                response.setHeader("Access-Control-Max-Age", "3600");
                filterChain.doFilter(request, response);
            }
        };
    }

    private CsrfTokenRepository csrfTokenRepository() {
        HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
        repository.setHeaderName("X-XSRF-TOKEN");
        repository.setSessionAttributeName("_csrf");
        return repository;
   }

我的TypeScript帖子

代码语言:javascript
复制
onLogin(loginData: {username: string, password: string}) {
    let headers = new Headers();
    headers.append('Access-Control-Allow-Credentials', 'true');
    headers.append('Content-Type','application/x-www-form-urlencoded');
    headers.append("Authorization", "Basic " + btoa(loginData.username + ":" + loginData.password));


    let body = {
        username: loginData.username,
        password: loginData.password
    }
    this.http.post('http://localhost:5000/login', body, {headers: headers, withCredentials: true})
      .map(res => res.json())
      .subscribe(data => {
          console.log(data);
          console.log(data.status)
       });
  }
}

上面的代码出错了,我知道这不是登录的细节,因为相同的用户名和密码可以很好地工作,而不是在帖子中。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-06-17 13:25:00

我就是这样解决这个问题的。

代码语言:javascript
复制
onLogin(loginData: {username: string, password: string}) {
  let headers = new Headers();
  headers.append('Access-Control-Allow-Credentials', 'true');
  headers.append('Content-Type','application/x-www-form-urlencoded');

  let body = `username=${loginData.username}&password=${loginData.password}`;

  this.http.post('http://localhost:5000/login', body, {headers: headers})

    .map(res => res)
    .subscribe(data => {
      console.log(data.status);
      if (data.status == 200) {
        this.navCtrl.push(TabsPage);
      }
      else {
        this.showError("Invalid username or password");
      }

    });
}

更新:主要问题是URL编码 --这一行:

代码语言:javascript
复制
let body = `username=${loginData.username}&password=${loginData.password}`;

多亏了持续时间

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44556251

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档