2016-10-17 4 views
0

내 Django보기에서 나는 self.request.user을 사용하여 REST Framework API 호출 사용자를 식별합니다. Django 프로젝트가 랩탑의 서버에서 실행 중일 때 코드가 올바르게 작동합니다.Django 세션은 로컬 서버에서 작동하지만 AWS 서버에서는 작동하지 않습니다.

이제 Django 프로젝트를 AWS EB에서 실행하려고하는데 self.request.user이 더 이상 사용자를 식별하지 못하는 문제가 있습니다. API 호출을하는 앱 코드는 Django 서버 코드와 똑같습니다.

어떤 식 으로든 서버 설정을 조정해야합니까?

'DEFAULT_AUTHENTICATION_CLASSES': (
     'rest_framework.authentication.SessionAuthentication', 
     'rest_framework.authentication.TokenAuthentication', 
    ) 

가 당신의 settings.py 파일에이 줄을 추가

하면 다음 코드 코드로 나머지 프레임 워크의 기본 인증을 대체 :

import os 

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 

SECRET_KEY = '9-s0gj3$)(--+mgc^3qhy=iva#[email protected]=' 

DEBUG = True 

ALLOWED_HOSTS = [] 

INSTALLED_APPS = [ 
    'grappelli', 
    'django.contrib.admin', 
    'django.contrib.auth', 
    'django.contrib.contenttypes', 
    'django.contrib.sessions', 
    'django.contrib.messages', 
    'django.contrib.staticfiles', 
    'django.contrib.sites', 
    'allauth', 
    'allauth.account', 
    'allauth.socialaccount', 
    'allauth.socialaccount.providers.facebook', 
    'allauth.socialaccount.providers.google', 
    'allauth.socialaccount.providers.linkedin', 
    'allauth.socialaccount.providers.twitter', 
    'corsheaders', 
    'rest_framework', 
    'rest_framework.authtoken', 
    'rest_auth', 
    'imagekit', 
    #'blog', 
    'storages', 
    'items', 
    'userprofile', 
    'dashboard', 
    'twip', 
    'django.contrib.gis' 
] 

SITE_ID = 1 

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

ROOT_URLCONF = 'mysite.urls' 

TEMPLATES = [ 
    { 
     'BACKEND': 'django.template.backends.django.DjangoTemplates', 
     'DIRS': [os.path.join(BASE_DIR, 'templates')], 
     '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', 
       "django.core.context_processors.request", 
      ], 
     }, 
    }, 
] 

AUTHENTICATION_BACKENDS = (
    'django.contrib.auth.backends.ModelBackend', 
    'allauth.account.auth_backends.AuthenticationBackend', 
    ) 

LOGIN_REDIRECT_URL = '/' 

SOCIALACCOUNT_QUERY_EMAIL = True 

SOCIALACCOUNT_PROVIDERS = { 
    'facebook': { 
     'SCOPE': ['email', 'publish_stream'], 
     'METHOD': 'js_sdk' # instead of 'oauth2' 
    } 
} 

# :TO DO: Remove this when we test proper email confirmation on the EB server. This sends confirmation email to the console 
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' 

WSGI_APPLICATION = 'mysite.wsgi.application' 

# Postgresql database on AWS server 
DATABASES = { 
    'default': { 
     'ENGINE': 'django.db.backends.postgresql_psycopg2', 
     'NAME': '', 
     'USER' : '', 
     'PASSWORD' : '', 
     'HOST': '', 
     'PORT': '5432', 
    } 
} 

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 = 'Europe/Berlin' 

USE_I18N = True 

USE_L10N = True 

USE_TZ = True 


# STORE STATIC AND MEDIA FILES 
AWS_STORAGE_BUCKET_NAME = 'yhistory' 
AWS_ACCESS_KEY_ID = 'AKAAAA6AAAAYQ5JODCEA' 
AWS_SECRET_ACCESS_KEY = 'AAAATtVeCZLaAAAAQQxZ9g5biTJnAAAA7PP8YrlC' 
AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME 

# Location of static files 
STATICFILES_LOCATION = 'static' 
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) 
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static') 
STATIC_URL = '/static/' 
STATICFILES_DIRS = (os.path.join('static'),) 

# Location of media files (photos etc.) 
MEDIAFILES_LOCATION = 'media' 
MEDIA_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION) 
DEFAULT_FILE_STORAGE = 'custom_storages.MediaStorage' 


REST_FRAMEWORK = { 
    'DEFAULT_AUTHENTICATION_CLASSES': ['rest_framework.authentication.TokenAuthentication'], 
    'DEFAULT_PERMISSION_CLASSES': [], 
    'PAGE_SIZE': 1000, # Max number of results returned from a list API call 
    'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',), 
    # Use JSONRender so the Web API interface is not shown. This is needed when testing the app on the same server 
    'DEFAULT_RENDERER_CLASSES': (
     'rest_framework.renderers.JSONRenderer', 
    ) 
} 

CORS_ORIGIN_ALLOW_ALL = True # :PRODUCTION: Change this! If set to False the CORS whitelist is used 
CORS_ORIGIN_WHITELIST =() 
""" 
CORS_ORIGIN_WHITELIST = (
    'twip.co', 
    '127.0.0.1' 
) 
""" 
CORS_ORIGIN_REGEX_WHITELIST =() 
CORS_URLS_REGEX = '^.*$' 
CORS_ALLOW_METHODS = (
    'GET', 
    'POST', 
    'PUT', 
    'PATCH', 
    'DELETE', 
    'UPDATE', 
    'OPTIONS' 
) 
CORS_ALLOW_HEADERS = (
    'x-requested-with', 
    'content-type', 
    'accept', 
    'origin', 
    'authorization', 
    'x-csrftoken' 
) 
CORS_EXPOSE_HEADERS =() 
CORS_ALLOW_CREDENTIALS = False 

GRAPPELLI_ADMIN_TITLE = "The World Image Archive Admin Panel" 
+0

loc의 세션 쿠키를 삭제하면 어떻게됩니까? 알host? 사용자가 로컬에서는 인증되었지만 AWS에서는 인증되지 않은 것 같습니다. –

+0

API 호출은 iOS 앱에서 가져옵니다. 앱을 삭제하고 다시 설치했습니다. –

+0

iOS에 익숙하지 않습니다. 앱을 다시 설치하면 쿠키 저장소가 지워지시겠습니까? 당신은 시도하고 응용 프로그램과 서버 사이의 HTTP 트래픽을 캡처하고 둘 사이에 교환 HTTP 헤더에서 볼 수있는 것을 볼 수 있습니다. 또는 dev 에뮬레이터에서 응용 프로그램을 실행하십시오. –

답변

1

가능한 해결 옵션을 : 내 settings.py은 다음과 같습니다 세부 정보 click here

WSGIPassAuthorization On 
+0

감사합니다 아미르. 내 응용 프로그램은 Django 코드가 랩톱에서 실행될 때 제대로 작동하는 토큰 인증을 사용합니다. 이전에 세션 인증 설정을했는데 작동하려면이 파일을 제거해야했습니다. WSGIPassAuthorization On이란 무엇입니까? 이걸 어디에 넣어야합니까? –

+0

"WSGIPassAuthorization On"을 settings.py 파일에 넣고 세부 링크를 제공한다고 말씀 드렸습니다. 덕분에 – Amir

+0

감사합니다 아미르 문제를 해결했습니다. –

관련 문제