• 如何添加JWT生成的token在请求头中


    前言

    在我们使用JWT来做用户的验证时,我们登陆生成对应的token,并加入到请求的参数中发送到后台提供相关的权限校验。这个时候我们需要使用到传递请求头参数传递的问题,下面是两种方式。

    1.ajax提交方式

    1).方法一:

    $.ajax({
    type: "GET",
    url: "/access/logout/" + userCode,
    headers: {'Authorization': token}
    });
    上面的方法一是我提交的方式

    请求成功后


    2).方法二:

    $.ajax({
    type: "GET",
    url: "/access/logout/" + userCode,
    beforeSend: function(request) {
    request.setRequestHeader("Authorization", token);
    },
    success: function(result) {
    }
    });
    2.anjular添加token到header中的方式

    1.自定义Http方法,全局使用自动添加Token到Header中,或者使用拦截器,方法类似。

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

    const mergeToken = (options: RequestOptionsArgs = {}) => {
    const newOptions = new RequestOptions({}).merge(options);
    const newHeaders = new Headers(newOptions.headers);
    const jwt = localStorage.getItem('jwt');
    if (jwt) {
    newHeaders.set('Authorization', jwt);
    }
    newOptions.headers = newHeaders;
    return newOptions;
    };

    @Injectable()
    export class MyHttp {

    constructor(private http: Http) {
    }

    get(url: string, options?: RequestOptionsArgs): Observable<Response> {
    return this.http.get(url, mergeToken(options));
    }

    post(url: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
    return this.http.post(url, body, mergeToken(options));
    }

    put(url: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
    return this.http.put(url, body, mergeToken(options));
    }

    delete(url: string, options?: RequestOptionsArgs): Observable<Response> {
    return this.http.delete(url, mergeToken(options));
    }

    patch(url: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
    return this.http.patch(url, body, mergeToken(options));
    }

    head(url: string, options?: RequestOptionsArgs): Observable<Response> {
    return this.http.head(url, mergeToken(options));
    }

    }

  • 相关阅读:
    第二周作业
    十二周
    十一周
    第十周
    第九周
    第八周
    第七周
    第六周
    实验报告三
    第四周课程总结&试验报告(二)
  • 原文地址:https://www.cnblogs.com/jfaith/p/11124030.html
Copyright © 2020-2023  润新知