簡體   English   中英

Angular 2 Spring Security CSRF 令牌

[英]Angular 2 Spring Security CSRF Token

大家好 我在為我的應用程序設置安全解決方案時遇到問題!! 所以我有一個 REST API 后端,它在http://localhost:51030 上運行並使用 Spring Framework 開發,對於前端,我有一個 Angular 2 應用程序(最新版本 AKA Angular 4),它在http://localhost 上運行:4200 我在后端設置了 CORS 配置,如下所示:

public class CORSFilter implements Filter
{
// The list of domains allowed to access the server
private final List<String> allowedOrigins = Arrays.asList("http://localhost:4200", "http://127.0.0.1:4200");

public void destroy()
{

}

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException
{   
    // Lets make sure that we are working with HTTP (that is, against HttpServletRequest and HttpServletResponse objects)
    if (req instanceof HttpServletRequest && res instanceof HttpServletResponse)
    {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        // Access-Control-Allow-Origin
        String origin = request.getHeader("Origin");
        response.setHeader("Access-Control-Allow-Origin", allowedOrigins.contains(origin) ? origin : "");
        response.setHeader("Vary", "Origin");

        // Access-Control-Max-Age
        response.setHeader("Access-Control-Max-Age", "3600");

        // Access-Control-Allow-Credentials
        response.setHeader("Access-Control-Allow-Credentials", "true");

        // Access-Control-Allow-Methods
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");

        // Access-Control-Allow-Headers
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, " + CSRF.REQUEST_HEADER_NAME); // + CSRF.REQUEST_HEADER_NAME
    }
    chain.doFilter(req, res);
}


public void init(FilterConfig filterConfig)
{

}
}

使用此配置只能正常工作,我可以執行從 angular 應用程序到回彈的請求並獲得響應並執行任何操作。 但是當我嘗試設置 CSRF 安全解決方案時,沒有任何效果。 這是在后端設置的 CSRF 和 Security 配置:

public class CSRF
{

     /**
     * The name of the cookie with the CSRF token sent by the server as a response.
     */
     public static final String RESPONSE_COOKIE_NAME = "XSRF-TOKEN"; //CSRF-TOKEN

     /**
      * The name of the header carrying the CSRF token, expected in CSRF-protected requests to the server.
      */
    public static final String REQUEST_HEADER_NAME = "X-XSRF-TOKEN"; //X-CSRF-TOKEN

    // In Angular the CookieXSRFStrategy looks for a cookie called XSRF-TOKEN 
    // and sets a header named X-XSRF-TOKEN with the value of that cookie.

    // The server must do its part by setting the initial XSRF-TOKEN cookie 
    // and confirming that each subsequent state-modifying request includes 
    // a matching XSRF-TOKEN cookie and X-XSRF-TOKEN header.

}

public class CSRFTokenResponseCookieBindingFilter extends OncePerRequestFilter
{

    protected static final String REQUEST_ATTRIBUTE_NAME = "_csrf";

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
    throws ServletException, IOException
    {
        CsrfToken token = (CsrfToken) request.getAttribute(REQUEST_ATTRIBUTE_NAME);

        Cookie cookie = new Cookie(CSRF.RESPONSE_COOKIE_NAME, token.getToken());
        cookie.setPath("/");

        response.addCookie(cookie);

        filterChain.doFilter(request, response);
    }
}

@Configuration
public class Conf extends WebMvcConfigurerAdapter
{
    @Bean
    public CORSFilter corsFilter()
    {
        return new CORSFilter();
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry)
    {
        registry.addViewController("/login");
        registry.addViewController("/logout");
    }
}

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter
{

    @Autowired
    private RESTAuthenticationEntryPoint authenticationEntryPoint;

    @Autowired
    private RESTAuthenticationFailureHandler authenticationFailureHandler;

    @Autowired
    private RESTAuthenticationSuccessHandler authenticationSuccessHandler;

    @Autowired
    private RESTLogoutSuccessHandler logoutSuccessHandler;

    @Resource
    private CORSFilter corsFilter;

    @Autowired
    private DataSource dataSource;


    @Autowired
    public void globalConfig(AuthenticationManagerBuilder auth) throws Exception
    {
        auth.jdbcAuthentication()
            .dataSource(dataSource)
            .usersByUsernameQuery("select login as principal, password as credentials, true from user where login = ?")
            .authoritiesByUsernameQuery("select login as principal, profile as role from user where login = ?")
            .rolePrefix("ROLE_");
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception
    {
        //csrf is disabled for the moment
        //http.csrf().disable();

        //authorized requests
        http.authorizeRequests()
            .antMatchers("/api/users/**").permitAll()
            .antMatchers(HttpMethod.OPTIONS , "/*/**").permitAll()
            .antMatchers("/login").permitAll()
            .anyRequest().authenticated();

        //handling authentication exceptions
        http.exceptionHandling()
            .authenticationEntryPoint(authenticationEntryPoint);

        //login configuration
        http.formLogin()
            .loginProcessingUrl("/login")
            .successHandler(authenticationSuccessHandler);
        http.formLogin()
            .failureHandler(authenticationFailureHandler);

        //logout configuration
        http.logout()
            .logoutUrl("/logout")
            .logoutSuccessHandler(logoutSuccessHandler);

        //CORS configuration
        http.addFilterBefore(corsFilter, ChannelProcessingFilter.class);


        //CSRF configuration
        http.csrf().requireCsrfProtectionMatcher(
                new AndRequestMatcher(
                // Apply CSRF protection to all paths that do NOT match the ones below

                // We disable CSRF at login/logout, but only for OPTIONS methods to enable the browser preflight
                new NegatedRequestMatcher(new AntPathRequestMatcher("/login*/**", HttpMethod.OPTIONS.toString())),
                new NegatedRequestMatcher(new AntPathRequestMatcher("/logout*/**", HttpMethod.OPTIONS.toString())),

                new NegatedRequestMatcher(new AntPathRequestMatcher("/api*/**", HttpMethod.GET.toString())),
                new NegatedRequestMatcher(new AntPathRequestMatcher("/api*/**", HttpMethod.HEAD.toString())),
                new NegatedRequestMatcher(new AntPathRequestMatcher("/api*/**", HttpMethod.OPTIONS.toString())),
                new NegatedRequestMatcher(new AntPathRequestMatcher("/api*/**", HttpMethod.TRACE.toString()))
            )
        );

        // CSRF tokens handling
        http.addFilterAfter(new CSRFTokenResponseCookieBindingFilter(), CsrfFilter.class);

    }
}

問題出在前端和angular 4的配置上,CSRF文檔太差,網上也沒有完整的CSRF實現例子。 所以下面是我的登錄服務:

@Injectable()
export class LoginService {

    private loginUrl = 'http://localhost:51030/login';

    constructor(private http: Http) {}

    preFlight() {
        return this.http.options(this.loginUrl);
    }

    login(username: string , password: string) {

        let headers = new Headers();

        headers.append('Content-Type', 'application/x-www-form-urlencoded');

        let options = new RequestOptions({headers: headers});

        let body = "username="+username+"&password="+password;

        return this.http.post(this.loginUrl , body , options);

    }
}

在登錄組件中,我在 ngOnInit 生命周期鈎子中執行選項請求:

@Component({
    templateUrl: './login-layout.component.html'
})
export class LoginLayoutComponent implements OnInit {

    credentials = {username: '' , password: ''};

    constructor(private loginService: LoginService){}

    ngOnInit() {
        this.loginService.preFlight()
                         .subscribe();
    }

    login() {
        this.loginService.login(this.credentials.username , this.credentials.password)
                         .subscribe(
                            response=>{
                                console.log(response) ; 
                            },error=>{
                                console.log(error);
                            }
                         );
    }

}

預檢進展順利,我在選項請求上獲得了 200 OK 狀態以及臨時 JSEEIONID 和 XSRF-TOKEN Cookie。

所以在我的應用程序模塊中,我在 angular 文檔中添加了這個:

{
    provide: XSRFStrategy,
    useValue: new CookieXSRFStrategy('XSRF-TOKEN', 'X-XSRF-TOKEN')
  },

但是,當我嘗試使用憑據或任何返回的請求執行 POST 請求時,我收到 403 Forbidden:“無法驗證提供的 CSRF 令牌,因為未找到您的會話。”

所以請我如何解決這個問題,任何人都可以指出我正確的方向,因為我不知道如何進行這項工作!! 和謝謝!!!

要解決 spring security 和 angular 之間的 csrf 問題,你必須這樣做。

在 SecurityConfiguration (WebSecurityConfig) 中,替換 http.csrf().disable(); 經過

               http.csrf()
                .ignoringAntMatchers ("/login","/logout")
                .csrfTokenRepository (this.getCsrfTokenRepository());


    }
    private CsrfTokenRepository getCsrfTokenRepository() {
        CookieCsrfTokenRepository tokenRepository = CookieCsrfTokenRepository.withHttpOnlyFalse();
        tokenRepository.setCookiePath("/");
        return tokenRepository;
{

默認的 angular csrf 攔截器並不總是有效。所以你必須實現你自己的攔截器。

import {Injectable, Inject} from '@angular/core';
import {HttpInterceptor, HttpXsrfTokenExtractor, HttpRequest, HttpHandler,
  HttpEvent} from '@angular/common/http';
import {Observable} from "rxjs";


@Injectable()
export class HttpXsrfInterceptor implements HttpInterceptor {

  constructor(private tokenExtractor: HttpXsrfTokenExtractor) {
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    let requestMethod: string = req.method;
    requestMethod = requestMethod.toLowerCase();

    if (requestMethod && (requestMethod === 'post' || requestMethod === 'delete' || requestMethod === 'put')) {
      const headerName = 'X-XSRF-TOKEN';
      let token = this.tokenExtractor.getToken() as string;
      if (token !== null && !req.headers.has(headerName)) {
        req = req.clone({headers: req.headers.set(headerName, token)});
      }
    }

    return next.handle(req);
  }
}

最后將其添加到您的提供程序中(app.module.ts)

providers: [{ provide: HTTP_INTERCEPTORS, useClass: HttpXsrfInterceptor, multi: true }]

考慮放入您的進口商品。

   HttpClientXsrfModule.withOptions({
      cookieName: 'XSRF-TOKEN',
      headerName: 'X-CSRF-TOKEN'
    }),

我很驚訝你為 CSRF 和 CORS 做了這么多工作,因為 Spring Security 和 Angular 內置了支持。Spring Security 默認啟用了 CSRF。

spring 安全手冊有關於配置 csrf 的很好的文檔: https ://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#csrf

谷歌搜索“Angular 2 Spring Security csrf”給出了幾個例子(以及我如何找到你的帖子)。 這是一個:

https://medium.com/spektrakel-blog/angular2-and-spring-a-friend-in-security-need-is-a-friend-against-csrf-indeed-9f83eaa9ca2e

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM