Angular2的Spring安全性

时间:2016-09-29 09:15:35

标签: spring spring-mvc angular spring-security

我尝试使用Spring Security从Angular2表单验证我的用户,但它无法正常工作。我已经浏览了整个网络,但似乎找不到合适的答案,有人可以指出我出错的地方 -

这是我的spring-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);
}

最后是调用spring security的服务 -

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。

1 个答案:

答案 0 :(得分:3)

在Angular2中,只要您订阅HTTP调用,就会触发HTTP调用。像这样调整代码:

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