Add token to the request header header

Source: Internet
Author: User
Tags export class
Overview

To ensure security, when using the JSON Web token as a single sign-on authentication medium, it is recommended that the JWT information be stored in the HTTP request header and encrypted with HTTPS for the request link, as shown in the following illustration:
problem

1. As the project is separated from the front and the back, it is unavoidable that a cross-domain problem arises, causing authorization to always be unable to add to the request header, and the request appears as follows:
 
 
reason: theory see this article: (Point here), in short, when making cross-domain requests, as in the case of a custom request header, such as adding a authorization field, the HTTP request will issue a pre-check request, the options request, Whether the access server allows the request, and if the browser does not make Cross-domain settings, the error shown in the illustration above appears.

Workaround: browser settings Cross-domain processing, here's the easiest way to do this
1. Referencing a jar package that is processed across domains

    <dependency>
        <groupId>com.thetransactioncompany</groupId>
        <artifactId> Cors-filter</artifactid>
    </dependency>

2. Add the following configuration to the Web.xml:
Note To add the custom Request header field to the location of the following figure: Authorization

 <filter> <filter-name>CORS</filter-name> <filter-class>com.thetransactioncompany. Cors. Corsfilter</filter-class> <init-param> &LT;PARAM-NAME&GT;CORS.ALLOWORIGIN&LT;/PARAM-NAME&G
            T <param-value>*</param-value> </init-param> <init-param> <param-name >cors.supportedMethods</param-name> <param-value>get, POST, head, put, DELETE&LT;/PARAM-VALUE&G
        T
            </init-param> <init-param> <param-name>cors.supportedHeaders</param-name> 
        <param-value>authorization,accept, Origin,x-requested-with, Content-type, last-modified</param-value> </init-param> <init-param> &LT;PARAM-NAME&GT;CORS.EXPOSEDHEADERS&LT;/PARAM-NAME&G
            T <param-value>Set-Cookie</param-value> </init-param> <init-param&Gt
        <param-name>cors.supportsCredentials</param-name> <param-value>true</param-value> 
        </init-param> </filter> <filter-mapping> <filter-name>CORS</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>

This allows the browser to respond successfully to a pre-test request, as shown in the following figure:
Application How Ajax adds token to header

1. Method One:

$.ajax ({
    type: "Get",
    URL: "/access/logout/" + Usercode,
    headers: {' Authorization ': token}
});

2. Method Two:

    $.ajax ({
        type: "Get",
        URL: "/access/logout/" + Usercode,
        beforesend:function (request) {
            Request.setrequestheader ("Authorization", token);
        },
        success:function (Result) {
        }
    });
anjular Add token to header

1. Customize the HTTP method, use the global to automatically add token to header, or use interceptors, similar methods.

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?: Requestoptions
  Args): observable<response> {return this.http.get (URL, Mergetoken (options)); Post (url:string, Body:any, options?: Requestoptionsargs): observable<response> {return this.http.post (ur
  L, Body, Mergetoken (options)); Put (url:string, Body:any, options?: Requestoptionsargs): observable<response>This.http.put (URL, Body, Mergetoken (options)); } Delete (url:string, options?: Requestoptionsargs): observable<response> {return this.http.delete (URL, Merg
  Etoken (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, mergetok
  En (options)); }

}

2. Refer to the method of this link, have not tested, need to test.

http://blog.csdn.net/magiclr/article/details/49643277

Summary: Sometimes the problem is not unresolved, but the need to understand more knowledge, from a number of perspectives to think about the problem, which is the problem for a long time.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.