请求中缺少授权标头(Angular4和Django)

时间:2017-08-04 06:24:47

标签: python django angular oauth-2.0

我正在为客户端使用Django for RESTful API和Angular4。 我在Django中有CORS设置。来自 Postman 一切正常。 同样的请求不适用于Angular。身份验证正在运行获得令牌后,我收到401 Unauthorized作为对每个请求的响应。 即使我明确地设置了此请求,也会在请求中缺少授权标头。

你能帮助我找出我的方法有什么问题吗?

这里我设置了角色的授权标题,

Angular Code:

public setUserData(){
      var search = new URLSearchParams();
      let headersObj = this.getAuthHeaders() as any;
      let requestOptions = new RequestOptions({ headers: headersObj });
      let responseData = this.http.get(apiConfig.tokenValidateUrl 
                       ,requestOptions)
                        .map(this.handleData)
                        .catch(this.handleError);
      responseData.subscribe(
                       response => {
                        localStorage.setItem('user', response);
                       },
                       error => {
                         console.log(error)
                       }
                      );
  }


public getAuthHeaders():Headers{
      let headers = new Headers();
      headers.append('Content-Type', 'application/json');
      headers.append('Accept', 'application/json');
      headers.append('Authorization', 'Bearer '+localStorage.getItem('token'));
      return headers;
 }

以下是Django中的CORS设置,

settings.py

"""
Django settings for referalsite project.

Generated by 'django-admin startproject' using Django 1.11.3.


import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'k2!@nx$see*%c#@u%jn1__8b6=$5ll-_93djp75@e+10%bk7v_'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'referbuddy.apps.ReferbuddyConfig',
    'rest_framework',
    'oauth2_provider',
    'corsheaders',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'corsheaders.middleware.CorsPostCsrfMiddleware',
]

CORS_ORIGIN_ALLOW_ALL = True

CORS_ORIGIN_WHITELIST = [
    'google.com',
    'hostname.example.com',
    'localhost:8000',
    '127.0.0.1:4200'
    'localhost:4200',
]

CSRF_TRUSTED_ORIGINS = [
    'google.com',
    'hostname.example.com',
    'localhost:8000',
    '127.0.0.1:4200'
    'localhost:4200',
]

CORS_ALLOW_CREDENTIALS = False

CORS_REPLACE_HTTPS_REFERER = True

CORS_ALLOW_METHODS = [
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
]

CORS_ALLOW_HEADERS = [
    'accept',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
]

CORS_EXPOSE_HEADERS =[
    'authorization',
]
ROOT_URLCONF = 'referalsite.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'referalsite.wsgi.application'


# Database

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)

STATIC_URL = '/static/'


REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
}


OAUTH2_PROVIDER = {
    # this is the list of available scopes
    'SCOPES': {'read': 'Read scope', 'write': 'Write scope', 'groups': 'Access to your groups'},
    'OAUTH2_BACKEND_CLASS': 'oauth2_provider.oauth2_backends.JSONOAuthLibCore',
}

1 个答案:

答案 0 :(得分:0)

标题不接受'授权'属性。

使用'授权'创建CustomHeaders类字段并将此自定义标头设置为RequestOptionArgs中的{headers:customHeaders}。

哪个解决了这个问题。请在此处找到更新的代码。

CustomHeaders类

export class CustomHeaders{
   Authorization: string;
   Content-Type: string;
}


public getAuthHeaders():Headers{
      let headers = new CustomHeaders();
      headers.Authorization = 'Bearer '+localStorage.getItem('token');
      headers.Content-Type = 'application/json';
      return headers;
 }