2016-09-29 84 views
2

我試圖從使用Spring Security的Angular2表單驗證我的用戶,但它不工作。我看過所有網站上,但似乎沒有找到正確的答案吧,可能有人指出我要去的地方錯了 -Angular2的Spring Security

下面是從我的彈簧security.xml文件片段 -

<security:form-login login-page="/" 
         authentication-failure-url="/security/login" 
         default-target-url="/"/> 

    <security:access-denied-handler error-page="/security/denied"/> 
    <security:logout invalidate-session="true" 
        logout-success-url="/security/logout/success" 
        logout-url="/security/logout"/>    

這裏是我的angular2形式 -

<form (ngSubmit)="onLogin(f.value)" class="form-horizontal" role="form" #f="ngForm"> 
        <div class="form-group"> 
         <label class="col-sm-3 control-label" for="j_username">Username:</label> 
         <div class="col-sm-8"> 
          <input type="text" class="form-control" placeholder="Username" name="j_username" [(ngModel)]="user.userName" 
            maxlength="50" id="j_username" required > 
         </div> 
        </div> 
        <div class="form-group"> 
         <label class="col-sm-3 control-label" for="j_password">Password:</label> 
         <div class="col-sm-8"> 
          <input type="password" class="form-control" placeholder="Password" name="j_password" [(ngModel)]="user.password" 
            maxlength="50" id="j_password" required> 
         </div> 
        </div> 
        <div class="form-group"> 
         <div class="col-sm-offset-8 col-sm-10"> 
          <input type="submit" class="btn btn-default" value="Login"> 
         </div> 
        </div> 
       </form> 

而這裏的組件代碼 -

onLogin(f) { 
    this.userService.makeHttpCall(f); 
} 

和FIN盟友的服務,稱爲春季安全 -

makeHttpCall(f): void { 
    let userName = f['j_username']; 
    let password = f['j_password']; 
    let data = 'j_username='+userName+'&j_password='+password; 
    console.log(data); 
    let headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded'}); 
    let options = new RequestOptions({headers: headers} 
       ); 
    this.http.post('/j_spring_security_check', data, options) 
     .map(this.extractData) 
     .catch(this.handleError); 


} 

有人可以指出我要去哪裏錯了嗎?這個http調用並沒有讓我的spring安全配置中定義的AuthenticationManager。

回答

3

在Angular2中,只要您訂閱了它們,就會觸發HTTP調用。像這樣調整代碼:

this.http.post('/j_spring_security_check', data, options) 
    .map(this.extractData) 
    .catch(this.handleError). 
    .subscribe(data => { 
     // do something here with the response 
    }) 
+0

謝謝馬特!它確實有用!我的第一個不好,我有調試器放在服務器端的代碼,它永遠不會讓這個調用返回任何東西。 – Pratik

+0

不客氣。我的問題聽起來很熟悉:) – Matt