让每个Http请求都自动带上token | 您所在的位置:网站首页 › get请求带token › 让每个Http请求都自动带上token |
目录 2.将token放到某个http请求的header中 3.使用哪种方式更好呢? 1.将token放到cookie中这样每个http请求就都可以带上token信息了。 access_token="eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJhWExsdzZEM1pJNWtkSDc2UUdGdVVtc0h1ckFKRTJXeGlZMDF3QmVKYTMwIn0......"; document.cookie = "keycloakToken=" + access_token;下面以Django的中间件为例,看看后端是怎样从request中得到token信息。 if not request.META.get('HTTP_COOKIE'): #判断有没有cookie信息。 print("Debug: can't get the cookie keycloak token"); return JsonResponse({"detail": NotAuthenticated.default_detail}, status=NotAuthenticated.status_code) else: if "keycloakToken" in request.COOKIES: # request.COOKIES是字典类型,判断其中是否有keycloakToken这个key accessToken =request.COOKIES["keycloakToken"]; #从cookie中取得token信息。 print("Debug: the request token in cookie is: " + accessToken); else: return JsonResponse({"res": "1", "resMsg": "No Token Provided"},status=401) 2.将token放到某个http请求的header中 var token="eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJhWExsdzZEM1pJNWtkSDc2UUdGdVVtc0h1ckFKRTJXeGlZMDF3QmVKYTMwIn0........"; prepareHeaders() { return new Headers({ 'Content-Type': 'application/json; charset=UTF-8', 'Authorization': 'Bearer ' + token }); } addProduct(body: any): Observable { return this.http.post(`${this.backendUrl}/api/project/`, body, { headers: this.prepareHeaders() }).map(this.extractData); }下面同样以Django的中间件为例,看看后端是怎样从request中得到token信息。 #使用key HTTP_AUTHORIZATION从header中获取token信息。 auth_header = request.META.get('HTTP_AUTHORIZATION').split() accessToken = auth_header[1] if len(auth_header) == 2 else auth_header[0]以上只是以token为例,当然了,除了token,可以带上任何你想带的信息。 3.使用哪种方式更好呢?为了避开CSRF(跨站请求伪造)攻击,请使用第二种方式,发送请求的时候不要将Token放到cookie这个header里,而应该放到自定义的header里。 |
CopyRight 2018-2019 实验室设备网 版权所有 |