2016-11-07 116 views
-1

我們試圖通過角度2和彈簧安全來實現簡單的用戶登錄。但是,我們得到一個403個狀態回來的響應:無法驗證CSRF令牌! Angular 2和彈簧安全

{「時間戳」:1478525053048,「狀態」:403,「錯誤」:「禁止」,「消息」:「無法驗證所提供的CSRF令牌,因爲您的會話沒有被發現 「」 路徑 「:」/登錄「}

的login.html:

<form> 
<div class="form-group"> 
    <hr> 
    <label>Username:</label> 
    <input class="form-control input-sm" id="user" type="text" name="user" [(ngModel)]="loginData.user" required><br> 
</div> 
<div class="form-group"> 
    <label>Passwort:</label> 
    <input class="form-control input-sm" id="password" type="password" name="password" [(ngModel)]="loginData.passwordLogin" required> 
</div> 
<!--<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}" />--> 
<input type="submit" value="Login" class="btn btn-default" (click)="login()"> 

HTTP-service.ts:

login(username, pwd){ 
    console.log(username, pwd); 
    var json = JSON.stringify({'password':pwd,'username':username}); 
    var headers = new Headers(); 
    headers.append('Content-Type','application/json'); 
    headers.append('authorization', 'Basic'); 
    return this._http.post('http://localhost:8080/login', json, { 
     headers: headers 
    }).map(res => res.json()); 
} 

SecurityConfiguration.java:

@EnableWebSecurity 
@Configuration 
// @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER) 
public class SecurityConfiguration extends WebSecurityConfigurerAdapter { 

@Override 
protected void configure(HttpSecurity http) throws Exception { 
    System.out.println("loaded config"); 
    http.httpBasic() // 
      .and() // 
      .authorizeRequests() // 
      .antMatchers("/login").permitAll() // 
      .anyRequest().authenticated() // 
      .and().formLogin().loginPage("http://localhost:3000/login")// 
      .loginProcessingUrl("/login")// 
      .successHandler(successHandler()).failureHandler(failureHandler()).and()// 
      .addFilterAfter(new CsrfHeaderFilter(), CsrfFilter.class).csrf()// 
      .csrfTokenRepository(csrfTokenRepository());// 
} 

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

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); 
     } 

    }; 
} 

CsrfHeaderFilter.java:

public class CsrfHeaderFilter extends OncePerRequestFilter { 
@Override 
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) 
     throws ServletException, IOException { 
    final CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName()); 
    if (csrf != null) { 
     Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN"); 
     final String token = csrf.getToken(); 
     if (cookie == null || token != null && !token.equals(cookie.getValue())) { 
      cookie = new Cookie("XSRF-TOKEN", token); 
      cookie.setPath("/"); 
      response.addCookie(cookie); 
     } 
    } 
    filterChain.doFilter(request, response); 
} 

} 

召喚: Headers etc.

loadOfLogin

回答

0

如果你將您的項目轉化爲可由Javascript Web服務器託管的前端項目(AngularJS)以及後端(Spring/Java)項目,

您應該開始考慮使用OAuth2安全性,而不是常規的Spring安全性。

的OAuth2會給你的前端根據授權規則與其他服務安全通信的能力。代表您的最終用戶。

這也將離開僅前端AngularJS側的CSRF保護,而不需要做交叉的Java春天。