2017-11-21 2 views
0

Senden einer Anfrage an meine Django-Backend von Winkel zurückgibt eine 401 nicht autorisiert. Hier ist eine HTTP-Anfrage für eine Logout-Funktion.Angular http Anfrage mit Django Rest JWT

import { Injectable } from '@angular/core'; 
import { HttpClient,HttpHeaders } from '@angular/common/http'; 
import { RequestOptions } from '@angular/http'; 
import { authLoginUrl,authLogoutUrl } from '../../../../config/endpoints'; 
import 'rxjs/add/operator/map'; 
import { AlertService } from '../../../../../core/services/alert.service'; 
@Injectable() 
export class LoginService{ 
    public token: string; 

    constructor(private http: HttpClient) { 
     // set token if saved in local storage 
     var currentUser = JSON.parse(localStorage.getItem('currentUser')); 
     this.token = currentUser && currentUser.token; 
    } 

    logout(): void { 
     // notify backend of user logout 
     //authLogoutUrl = "http://127.0.0.1:8000/api/auth/logout/" 
     this.http.post(authLogoutUrl,{ 
      headers: new HttpHeaders().set('Authorization', 'JWT ' + this.token) 
      }) 
      .subscribe()   
    } 
} 

Anfrage ist jedoch zulässig, wenn ich es durch curl sende.

curl -X POST -H "Authorization: JWT <the_token>" http://localhost:8000/api/auth/logout/ 

Die Logout-Ansicht ist in meinem django Backend:

class LogoutView(views.APIView): 
    permission_classes = (permissions.IsAuthenticated,) 

    def post(self, request, format=None): 
     logout(request) 

     return Response({}, status=status.HTTP_204_NO_CONTENT) 

Every scheint, als ob es in Ordnung funktioniert. Die Preflight-Anforderung gibt 200 zurück, aber die Anforderung selbst ist nicht autorisiert. Hier ist der Request-Header

Request Headers

Cors Einstellungen Rest django:

CORS_ORIGIN_ALLOW_ALL = True 
CORS_ALLOW_HEADERS = (
    'accept', 
    'accept-encoding', 
    'authorization', 
    'content-type', 
    'dnt', 
    'origin', 
    'user-agent', 
    'x-csrftoken', 
    'x-requested-with', 
) 

#Rest Framework 
REST_FRAMEWORK = { 
    'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',), 
    'DEFAULT_AUTHENTICATION_CLASSES': (
     'rest_framework.authentication.BasicAuthentication', 
     'rest_framework.authentication.SessionAuthentication', 
     'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 
    ), 
    'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',), 
    'DEFAULT_PAGINATION_CLASS': 
    'rest_framework.pagination.LimitOffsetPagination', 
    'PAGE_SIZE':100, 
} 

Da es mit Curl und die Preflight-Anfrage funktioniert genehmigt wird, kann ich nur annehmen, dass das Problem mit Winkel- oder cors ist.

1) Sind die Header richtig eingestellt? 2) Ist das ein Korsoproblem?

Antwort

0

Das Problem war, dass die Kopfzeile nicht festgelegt wurde. Ich bin mir nicht sicher, warum das der Fall war, aber ich habe das gelöst, indem ich einen HTTP Interceptor erstellt habe. Es fängt HTTP-Anfragen ab und fügt das JWT-Token den Überschriften für jede HTTP-Anfrage hinzu. Dieser Artikel beschreibt einen Interceptor sehr gut.

https://theinfogrid.com/tech/developers/angular/building-http-interceptor-angular-5/

Hier ist das auch Interceptor-Code.

import { Injectable, Injector } from '@angular/core'; 
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http'; 

import { Observable } from 'rxjs/Rx'; 
import 'rxjs/add/observable/throw' 
import 'rxjs/add/operator/catch'; 
@Injectable() 
export class AuthInterceptor implements HttpInterceptor { 
    private token: string; 
    constructor() { } 

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

     this.getToken(); 

     console.log("intercepted request ... "); 

     // Clone the request to add the new header. 
     var authReq; 
     if (this.token){ 
      authReq = req.clone({ headers: req.headers.set("Authorization", "JWT " + this.token)}); 
      console.log("Sending request with new header now ..."); 
     } else { 
      authReq = req; 
     } 
     //send the newly created request 
     return next.handle(authReq) 
      .catch((error, caught) => { 
      //intercept the respons error and displace it to the console 
      console.log("Error Occurred"); 
      console.log(error); 
      //return the error to the method that called it 
      return Observable.throw(error); 
     }) as any; 
    } 

    getToken() { 
     let currentUser = JSON.parse(localStorage.getItem('currentUser')); 
     this.token = currentUser && currentUser.token; 
    } 
Verwandte Themen