1

我正在尝试在 Angular 4 中实现简单的 jwt 身份验证

这是我的服务器端 web api 身份验证代码

public class BasicAuthMessageHandler : DelegatingHandler {
        private const string BasicAuthResponseHeader = "WWW-Authenticate";
        private const string BasicAuthResponseHeaderValue = "Basic";

        public adminPrincipalProvider PrincipalProvider = new adminPrincipalProvider();

        protected override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,CancellationToken cancellationToken) {
            AuthenticationHeaderValue authValue = request.Headers.Authorization;
            if (authValue != null && authValue.Parameter != "undefined" && !String.IsNullOrWhiteSpace(authValue.Parameter)) {
                string email = authValue.Parameter;
                var session = HttpContext.Current.Session;
                if (session == null || session["userToken"] == null || string.IsNullOrEmpty(session["userToken"].ToString())) {
                    session["userToken"] = email;
                } else {
                    email = HttpContext.Current.Session["userToken"].ToString();
                }

                if (!string.IsNullOrEmpty(email)) {
                    IPrincipal principalObj = PrincipalProvider.createPrincipal(email, "Admin");
                    Thread.CurrentPrincipal = principalObj;
                    HttpContext.Current.User = principalObj;
                }
            }
            return base.SendAsync(request, cancellationToken)
               .ContinueWith(task => {
                   var response = task.Result;
                   if (response.StatusCode == HttpStatusCode.Unauthorized && !response.Headers.Contains(BasicAuthResponseHeader)) {
                       response.Headers.Add(BasicAuthResponseHeader,BasicAuthResponseHeaderValue);
                   }
                   return response;
               });
        }
    }

    public class adminPrincipalProvider {
        public IPrincipal createPrincipal(string userName, string role) {
            if (!string.IsNullOrEmpty(userName)) {
                var identity = new GenericIdentity(userName);
                IPrincipal principal = new GenericPrincipal(identity, new[] { role });
                return principal;
            } else { return null; }
        }
    }

这是我设置标头的 Angular 4 http 扩展器

import { Injectable } from "@angular/core";
import { Http, Headers, RequestOptionsArgs, Request, Response, ConnectionBackend, RequestOptions } from "@angular/http";
import { Observable } from 'rxjs/Observable';

@Injectable()
export class HttpService extends Http {
    authToken: any;
    constructor(protected _backend: ConnectionBackend, protected _defaultOptions: RequestOptions) {

        super(_backend, _defaultOptions);
    }
    _setCustomHeaders(options?: RequestOptions): RequestOptions {
       
        if (localStorage.getItem("authToken")) {
            this.authToken = JSON.parse(localStorage.getItem('authToken'));
            let headers = new Headers({ 'Content-Type': 'application/json' });
            
            headers.append('Authorization', 'Basic ' + this.authToken.token[0].UserName);
            let options = new RequestOptions({ headers: headers });
            return options;
        }
       
    }


    request(url: string | Request, options?: RequestOptions): Observable<Response> {
        options = this._setCustomHeaders(options);
        return super.request(url, options)
    }
}

这是我实际的 httprequest 调用

 import { Injectable } from '@angular/core';
import { Headers, Http, Response, RequestOptions, URLSearchParams } from '@angular/http';
import { HttpService } from '../../../assets/scripts/services/htttpextender';
import { Observable } from 'rxjs/Observable';

// Operators
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

@Injectable()
export class CategoriesService{
    private handleError: any;
    private id: any;
    private ids: any;

    constructor(private http: HttpService) {
    }

 getCategoriesResource(): Observable<any> {
        return this.http.get(this.baseUrl + 'api/v3/categories/GetCategories')
            .map((response: Response) => response.json())
            .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
    }

我在服务器端获取标头为空,您能告诉我我缺少什么以及如何读取标头

在此处输入图像描述

在此处输入图像描述

4

0 回答 0