在Angular2 / 4/5中,如何基于基于令牌的身份验证安全地调用WebAPI操作

时间:2018-03-16 09:18:14

标签: angular authentication asp.net-web-api ionic-framework

我需要知道,如何在Angular FrontEnd中获取令牌后安全地调用WebAPI操作方法。下面是我的登录组件代码,在发送用户名和密码后,我将usertoken设置为localstorage。然后我导航到主页。此处使用的所有代码均基于this video tutorial。由于我在HTML中也使用了Ionic代码,因此也有轻微的修改

login.ts

constructor(private userService : UserService, public navCtrl: NavController) { } 
OnSubmit(userName,password){
         this.userService.userAuthentication(userName,password).subscribe((data : any)=>{
          localStorage.setItem('userToken',data.access_token);
          //this.router.navigate(['/home']);
          this.navCtrl.push(HomeComponent);
        },
        (err : HttpErrorResponse)=>{
          this.isLoginError = true;
        });
      }

在下面显示的代码中,我根据上面给出的用户名和密码获取用户详细信息。请关注以下组件的 OnSubmit()方法。 这是基于usertoken提交其他形式的Home组件的方法/事件,我需要您的帮助

home.ts

constructor(public navCtrl: NavController, private userService: UserService) { }    
ngOnInit() {
    this.resetForm();
    this.userService.getUserClaims().subscribe((data: any) => {
    this.userClaims = data;    
    });        
  }
OnSubmit(form: NgForm) {
this.userService.UserForm(form.value)
  .subscribe((data: any) => {
    localStorage.getItem('userToken');

    if (data.Succeeded == true) {
     // this.resetForm(form);
     return "hello";
    }

  });      
}

请关注以下服务的 UserForm 方法,我需要您的帮助。

user.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { UIHelperClass } from '../UIHelperClasses/UIHelperClass';
import { Person } from './person.model'; 

@Injectable()
export class UserService {
UserForm(person:Person){
    const body: Person = {
      FirstName: person.FirstName,
      LastName: person.LastName
    }
       //var reqHeader = new HttpHeaders({'No-Auth':'True'});
    var reqHeader = new HttpHeaders({'No-Auth':'False'});
       //return this.http.post(this.rootUrl + '/api/User/Register', body,{headers : reqHeader});
    return this.http.post(this.uihelper.CallWebAPIUrl("/api/User/AddUser"), body,{headers : reqHeader});        
  }

  userAuthentication(userName, password) {
    var data = "username=" + userName + "&password=" + password + "&grant_type=password";
    var reqHeader = new HttpHeaders({ 'Content-Type': 'application/x-www-urlencoded','No-Auth':'True' });
        //return this.http.post(this.rootUrl + '/token', data, { headers: reqHeader });
    return this.http.post(this.uihelper.CallWebAPIUrl("/token"), data, { headers: reqHeader });           
  }

  getUserClaims(){
       //return  this.http.get(this.rootUrl+'/api/GetUserClaims');
   return  this.http.get(this.uihelper.CallWebAPIUrl("/api/GetUserClaims"));

  }
}

如何使用,以上UserForm服务方法中的代码类型。我需要保护我的请求/ WebAPI(基于此令牌,我需要调用Web API。它可能是获取发布请求)。我已将this tutorial的EmpService.js引用到以下代码

user.service.ts

xxx=localStorage.getItem('userToken');
  authHeaders: any[] = [];
  if (xxx) {
    this.authHeaders.Authorization = 'Bearer ' + xxx;
}

1 个答案:

答案 0 :(得分:0)

你可以使用angular2-jwt,它在angular 5和httpClient中完美运行,在给出你的令牌源(localStorage或redux store)后,令牌将自动添加到所有Http请求中:

export function tokenGetter() {
  return localStorage.getItem('access_token');
}

@NgModule({
  bootstrap: [AppComponent],
  imports: [
  HttpClientModule,
  JwtModule.forRoot({
   config: {
     tokenGetter: tokenGetter,
     whitelistedDomains: ['localhost:3001'] // token will be sent to these domains only 
   }
 })
 ]
})

您可以添加一个http拦截器,以便在登录调用时删除令牌,例如