点网核心和Angular 6中具有JWT令牌的窗口身份验证

时间:2019-02-05 10:21:00

标签: angular authentication jwt

嗨,我正在寻找使用角度为6,.net核心2.1作为后端和JWT令牌的窗口身份验证的方法。没有一个解决方案指向将JWT与窗口身份验证一起使用。

以下是startup.cs启用jwt的代码段

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                 .AddJwtBearer(options =>
                 {
                     options.TokenValidationParameters = new TokenValidationParameters
                     {
                         ValidateIssuer = true,
                         ValidateAudience = true,
                         ValidateLifetime = true,
                         ValidateIssuerSigningKey = true,
                         ValidIssuer = "EveryOne.Security.Bearer",
                         ValidAudience = "EveryOne.Security.Bearer",
                         ClockSkew = TimeSpan.FromMinutes(5),
                         IssuerSigningKey = JwtSecurityKey.Create(Configuration["SecretKey:SecretKey"])
                     };

                     options.Events = new JwtBearerEvents
                     {
                         OnAuthenticationFailed = context =>
                         {
                             Console.WriteLine("OnAuthenticationFailed: " + context.Exception.Message);
                             return Task.CompletedTask;
                         },
                         OnTokenValidated = context =>
                         {
                             Console.WriteLine("OnTokenValidated: " + context.SecurityToken);
                             return Task.CompletedTask;
                         }
                     };
                 });

            services.AddAuthorization(options =>
            {
                options.AddPolicy("Bearer",
                    policy => policy.RequireClaim("MembershipId"));

            });

用户Controller.cs

[HttpPost(“ AuthenticateUser /”)]

[AllowAnonymous]
public async Task<IActionResult> AuthenticateUser([FromBody]LoginDto user)
{}

角度分量调用:-

登录名(用户名:字符串,密码:字符串):可观察的{     返回this.httpClient.post(this.actionUrl + global.ApiMethod.AuthenticateUser,{userName:用户名,密码:密码,grantType:“密码”})

angular的呼叫通过拦截器-:

  import { Injectable, OnDestroy } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpResponse, HttpHeaders, HttpSentEvent, HttpHeaderResponse, HttpProgressEvent, HttpUserEvent } from '@angular/common/http';
import { Observable, Subscription } from 'rxjs';
import 'rxjs/add/observable/throw'
import { HttpErrorResponse } from '@angular/common/http';
import { tap } from 'rxjs/operators';
import { AuthenticationService } from '@app/login/authenticate/authenticate.service';
import _uniq from 'lodash-es/uniq';


@Injectable()

export class AuthenticationInterceptor implements HttpInterceptor, OnDestroy {

  // public count401: number;
  // public cachedRequests: HttpRequest<any>[];
  // private $refreshToken: Subscription;

  constructor(private authenticateService: AuthenticationService) { }

  // intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

  //   // request = request.clone({ headers: request.headers.set('withCredentials', 'true') });
  //   request = request.clone({ withCredentials: true });

  //   // console.log("request with interceptor with http" + request.url);
  //   return next.handle(request);
  // }


  public $refreshToken;
  public cachedRequests: Array<HttpRequest<any>> = [];
  public isTokenRefresh: boolean = false;
  public timer: any;
  public count401: number = 0;

  addToken(req: HttpRequest<any>, token: string): HttpRequest<any> {
    let request = req.clone({ withCredentials: true });
    request = request.clone({ headers: request.headers.set('Authorization', 'Bearer ' + token) })
    return request;
  }
  public collectFailedRequest(request): void {
    this.cachedRequests.push(request);
  }
  public retryFailedRequests(token): void {
    this.count401 = 0;
    const uniqCachedRequests = _uniq(this.cachedRequests);
    // retry the requests. this method can
    // be called after the token is refreshed 
    uniqCachedRequests.forEach(request => {
       request = request.clone({ setHeaders: { Authorization: `Bearer ${token}` } });
      //??What to do here
    });
    this.cachedRequests = [];
  }
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpSentEvent | HttpHeaderResponse | HttpProgressEvent | HttpResponse<any> | HttpUserEvent<any> | HttpEvent<any>> {

    const currentUser = JSON.parse(localStorage.getItem('currentUser'));
    const token = currentUser != null ? currentUser.token : "";

    if (this.count401 >= 1 && !req.url.includes('AuthenticateUser')) {
      this.count401++;
      this.collectFailedRequest(req);
      next.handle(req).subscribe().unsubscribe();
    }

    return next.handle(this.addToken(req, token)).pipe(tap((event: HttpEvent<any>) => {
      if (event instanceof HttpResponse) {
        // do stuff with response if you want
      }
    }, (err: any) => {
      if (err instanceof HttpErrorResponse) {
        // do error handling here
        switch (err.status) {
          case 401:
            this.count401++;
            this.collectFailedRequest(req)
            if (this.count401 === 1) {
              this.$refreshToken = this.authenticateService.refreshToken(currentUser).subscribe(result => {
                if (!result) {
                  this.count401 = 0;
                  this.authenticateService.logout();
                }
                else {
                  const currentUser = JSON.parse(localStorage.getItem('currentUser'));
                  this.retryFailedRequests(currentUser.token);
                }
              }, error => {
                if (error.status === 404) {
                  this.count401 = 0;
                  this.authenticateService.logout();
                }
              });
            }
            return this.$refreshToken;
        }

      }
    }));

  }
  ngOnDestroy() {`enter code here`
     this.$refreshToken.unsubscribe();
  }
}

0 个答案:

没有答案