Angular 4无法在标头中设置CSRF-TOKEN [英] Angular 4 can't set CSRF-TOKEN in header

查看:187
本文介绍了Angular 4无法在标头中设置CSRF-TOKEN的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个配置了Spring安全性的Spring引导RESTful服务,

I've got a Spring boot RESTful service with Spring security configured like so:

protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.cors().and()
                /*.formLogin().loginPage("/auth")
                .permitAll().and()
                .authorizeRequests()
                .anyRequest()
                .authenticated()
                .and().httpBasic().and()*/
                .csrf()
                .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
                .and()
                .addFilterAfter(new CsrfHeaderFilter(), CsrfFilter.class);
    }

&

public class CsrfHeaderFilter extends OncePerRequestFilter {

private static final String CSRF_COOKIE_NAME = "XSRF-TOKEN";

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
        throws ServletException, IOException {

    CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
    if (csrf != null) {
        response.addHeader("X-CSRF-TOKEN", csrf.getToken());
        Cookie cookie = WebUtils.getCookie(request, CSRF_COOKIE_NAME);
        String token = csrf.getToken();

        if (cookie == null || token != null && !token.equals(cookie.getValue())) {
            cookie = new Cookie(CSRF_COOKIE_NAME, token);
            cookie.setPath("/");
            response.addCookie(cookie);
        }
    }

    filterChain.doFilter(request, response);
}

}

我正在使用Angular 4(最新版本)调用RESTful服务.它正在发布一个帖子,要求投诉并抛出403 Forbidden由于找不到您的会话,因此无法验证提供的CSRF令牌".这是可以预期的,因为我在发送发布请求时未设置X-CSRF-TOKEN标头,但此标头确实存在:- Set-Cookie:XSRF-TOKEN =;路径=/

I'm invoking the RESTful service using Angular 4 (latest version). It's doing a post request an complaining and throwing a 403 Forbidden "Could not verify the provided CSRF token because your session was not found." Which is expected because I when sending the post request the X-CSRF-TOKEN header is not being set but this header does exist:- Set-Cookie:XSRF-TOKEN=; Path=/

角度:

auth.service.ts:

auth.service.ts:

const body = 'SOMERANDOMKEY1111';

const headers = new HttpHeaders().set('Content-Type', 'application/json').set('withCredentials', 'true');

    return this._http.post(this.endpoint + this.auth, body, {
      headers: headers
    });

app.module.ts(注意:使用HttpClient进行发布请求)

app.module.ts (note: using HttpClient for post request):

providers: [ ...
{
    provide: XSRFStrategy, useFactory: xsrfFactory
}...]
export function xsrfFactory() {
  return new CookieXSRFStrategy('XSRF-TOKEN', 'XSRF-TOKEN');
}

我已遵循,并阅读了文档但似乎无法正常工作.

I've followed this and read up on the docs but can't seem to get this working.

推荐答案

当我开始使用Spring和angular5时,我遇到了同样的问题:

i had same issue when i was started working with Spring and angular5 :

问:如何在每个由angular发出的请求上设置X-CSRF令牌?

Q: how to set up X-CSRF token on each request made from angular ?

Sol: 服务器端:

Sol : server side:

  • 首先,您需要在服务器端配置csrf安全性

  • first you need to configure csrf security on server side

在服务器端,您需要编写一个在浏览器上设置cookie的api(cookie内的X-CSRF令牌),并且此api没有任何证券就被击中(禁用此api的csrf,假设api名称为/info)

on server side you need to write one api which set up cookies on browser (X-CSRF token inside cookies) and this api is hitting without any securities(disable csrf on this api, assume api name /info)

注意:/info该API仅在首次加载angular应用时被调用一次(您需要在要加载到angular应用中的第一页中添加此信息)

NOTE : /info this api is called only once when angular app first time loaded (you need to add this is in first page which is to be loaded in angular app)

角侧:

  • 当应用程序加载到angular的第一页/组件上时,在oninit内,您需要将此路由称为"/info"(您需要在angular中创建服务并在此处调用此api) 我在我的layout/navbar组件上进行了设置,因为在加载应用程序时,该组件是第一个加载的组件

  • when application is loaded on first page/component of angular , inside oninit you need to call this route "/info" (you need to create service in angular and call this api there) i set this on my layout/navbar component because when app is loaded this component was first one which loaded

然后在app.module.ts内部,我们需要导入

then on inside app.module.ts we need to import

从'@ angular/common/http'导入{HttpClientModule};

import { HttpClientModule } from '@angular/common/http';

并将此模块添加到导入数组中:

and addd this module inside imports array as :

@NgModule({   imports: [
                     HttpClientXsrfModule.withOptions({
                     cookieName: 'XSRF-TOKEN',
                     headerName: 'X-XSRF-TOKEN',
         })]

-然后在服务内部,您需要按以下方式更改请求:user.service.ts

-then inside services you need to change the request as follows: user.service.ts

 registeruser(data) {
    console.log(data)
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers, withCredentials: true });
    return this.http.post(this.url + '/avssymbuaa/api/register', data, options).map(res => res.json());
  }

  • 注意:您需要在服务上导入它
  • import {Http,标头,RequestOptions,响应,URLSearchParams} 来自"@ angular/http";

    import { Http, Headers, RequestOptions, Response, URLSearchParams } from '@angular/http';

    也许这可以帮助您,谢谢

    may be this one helps you, thanks

    这篇关于Angular 4无法在标头中设置CSRF-TOKEN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆