2017-11-21 6 views
0

角度からの私のdjangoバックエンドへのリクエストの送信は、401の権限を返します。ここには、ログアウト機能に関するhttp要求があります。Django Rest JWTでの角度付きHTTPリクエスト

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()   
    } 
} 

ただし、私はカールで送信するとリクエストが許可されます。

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

ログアウトビューは私のDjangoのバックエンドである:それは大丈夫働いているかのように

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

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

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

Everytingらしいです。プリフライト要求は200を返しますが、要求自体は許可されていません。ここで

Request Headers

CORS設定が残り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, 
} 

は、私が唯一の問題は、角度やCORSであると仮定することができます。

1)ヘッダーは正しく設定されていますか? 2)これは問題になりますか?

答えて

0

問題は、ヘッダーが設定されていないことでした。なぜこれが当てはまるのか分かりませんが、私はHttpインターセプタを作成してこれを解決しました。これはHTTP要求をインターセプトし、各HTTP要求のヘッダーにJWTトークンを追加します。この記事では、インターセプタを本当にうまく活用する方法について説明します。ここ

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

インターセプター・コードも同様です。

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; 
    } 
関連する問題