Asp.Net Web Api(OAuth2)令牌认证在Angular 5中的实现文档咨询
在Angular 5中实现ASP.NET Web API OAuth2 Bearer令牌认证的步骤
我来帮你梳理下在Angular 5里对接ASP.NET Web API OAuth2 Bearer认证的具体步骤——既然你已经能用Postman拿到令牌了,那咱们直接上手Angular端的实现:
1. 创建认证服务(AuthService)
首先要做的是封装一个专门处理令牌逻辑的服务,用来负责令牌的获取、存储、读取和清除,这样代码更模块化也更易维护:
import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; @Injectable() export class AuthService { // 替换成你的API令牌请求端点,比如 "/token" private tokenUrl = '你的API令牌地址'; private tokenStorageKey = 'auth_bearer_token'; constructor(private http: HttpClient) { } // 向API请求令牌 getToken(username: string, password: string): Observable<any> { // OAuth2密码模式需要提交的表单数据 const requestBody = new FormData(); requestBody.append('grant_type', 'password'); requestBody.append('username', username); requestBody.append('password', password); // 如果你的API要求client_id和client_secret,记得加上这两行 // requestBody.append('client_id', '你的客户端ID'); // requestBody.append('client_secret', '你的客户端密钥'); return this.http.post(this.tokenUrl, requestBody); } // 将令牌存储到localStorage storeToken(token: string): void { localStorage.setItem(this.tokenStorageKey, token); } // 获取存储的令牌 getStoredToken(): string | null { return localStorage.getItem(this.tokenStorageKey); } // 清除令牌(登出时用) clearToken(): void { localStorage.removeItem(this.tokenStorageKey); } // 判断用户是否已认证 isAuthenticated(): boolean { const token = this.getStoredToken(); // 这里可以简单判断令牌是否存在,也可以解析JWT检查过期时间 return token !== null; } }
2. 实现HTTP拦截器自动添加Bearer令牌
手动给每个请求加Authorization头太麻烦,Angular 5提供了HttpInterceptor,可以自动给所有API请求注入令牌:
import { Injectable } from '@angular/core'; import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; import { AuthService } from './auth.service'; @Injectable() export class TokenInterceptor implements HttpInterceptor { constructor(private authService: AuthService) {} intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { const token = this.authService.getStoredToken(); if (token) { // 克隆请求并添加Authorization头(注意Bearer后面有空格) request = request.clone({ setHeaders: { Authorization: `Bearer ${token}` } }); } return next.handle(request); } }
然后要在AppModule里注册这个拦截器,让它生效:
import { HTTP_INTERCEPTORS } from '@angular/common/http'; import { TokenInterceptor } from './token.interceptor'; import { AuthService } from './auth.service'; @NgModule({ ... providers: [ AuthService, { provide: HTTP_INTERCEPTORS, useClass: TokenInterceptor, multi: true } ], ... }) export class AppModule { }
3. 登录组件调用认证服务
在登录页面里,用户输入账号密码后,调用AuthService获取并存储令牌:
import { Component } from '@angular/core'; import { AuthService } from '../auth.service'; import { Router } from '@angular/router'; @Component({ selector: 'app-login', templateUrl: './login.component.html' }) export class LoginComponent { username: string; password: string; constructor(private authService: AuthService, private router: Router) { } onLogin(): void { this.authService.getToken(this.username, this.password) .subscribe( (response) => { // API返回的令牌字段通常是access_token,根据你的实际返回调整 this.authService.storeToken(response.access_token); // 登录成功后跳转到需要认证的页面,比如首页 this.router.navigate(['/dashboard']); }, (error) => { console.error('登录失败:', error); // 这里可以给用户提示错误信息,比如账号密码错误 } ); } }
4. 用路由守卫保护私密路由
如果有些页面需要登录才能访问,可以用CanActivate守卫来拦截未认证的访问:
import { Injectable } from '@angular/core'; import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; import { AuthService } from './auth.service'; @Injectable() export class AuthGuard implements CanActivate { constructor(private authService: AuthService, private router: Router) {} canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { if (this.authService.isAuthenticated()) { return true; } // 未认证则跳转到登录页,同时记录当前路由,方便登录后跳转回来 this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } }); return false; } }
然后在路由配置里给需要保护的路由添加守卫:
import { AuthGuard } from './auth.guard'; import { DashboardComponent } from './dashboard/dashboard.component'; import { LoginComponent } from './login/login.component'; const routes: Routes = [ { path: 'login', component: LoginComponent }, { path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] }, // 其他需要保护的路由同理 ];
额外注意事项
- 令牌过期处理:如果你的令牌是JWT格式,可以解析令牌的payload获取过期时间,在拦截器或路由守卫里检查是否过期,过期则自动跳转到登录页。
- 跨域配置:确保你的ASP.NET Web API已经开启了CORS,并且允许Angular应用的域名访问,同时允许携带
Authorization请求头。 - 安全问题:用
localStorage存储令牌存在XSS风险,如果对安全性要求极高,可以考虑和后端配合使用HttpOnly Cookie存储令牌。
内容的提问来源于stack exchange,提问作者achrafbenalaya
相关产品推荐
相关产品推荐

