在本地存储jwt令牌后,如何授权用户



settings.py

"""
Django settings for auth project.
Generated by 'django-admin startproject' using Django 4.1.5.
For more information on this file, see
https://docs.djangoproject.com/en/4.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.1/ref/settings/
"""
from datetime import timedelta
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-iogl-doj_#_npx4ss#7mn4!x0zn$gjn!&o7a1=m!u_vf#$_9fi'
# 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',
'corsheaders',
'rest_framework',
'djoser',
'authorize',
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'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',
]
ROOT_URLCONF = 'auth.urls'
CORS_ORIGIN_ALLOW_ALL = True
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 = 'auth.wsgi.application'
AUTH_USER_MODEL = 'authorize.User'

# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'authdb',
'USER': 'postgres',
'PASSWORD': '1234',
'HOST': 'localhost',
}
}

# Password validation
# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators
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
# https://docs.djangoproject.com/en/4.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/
STATIC_URL = 'static/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
REST_FRAMEWORK = {
'COERCE_DECIMAL_TO_STRING': False,
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
),
}
SIMPLE_JWT = {
'AUTH_HEADER_TYPES': ('JWT',),
'ACCESS_TOKEN_LIFETIME': timedelta(days=2)
}
DJOSER = {
'SERIALIZERS': {
'user_create': 'authorize.serializers.UserCreateSerializer',
'current_user': 'authorize.serializers.UserSerializer',
}
}

urls.py

from django.contrib import admin
from django.urls import path, include
from rest_framework_simplejwt import views as jwt_views
urlpatterns = [
path('admin/', admin.site.urls),
path('/', include('authorize.urls')),
path('auth/', include('djoser.urls')),
path('auth/', include('djoser.urls.jwt')),
]

authorize/serializers.py

from .models import User
from rest_framework import serializers
from django.contrib.auth import authenticate
from djoser.serializers import UserSerializer as BaseUserSerializer, UserCreateSerializer as BaseUserCreateSerializer
class UserCreateSerializer(BaseUserCreateSerializer):
class Meta(BaseUserCreateSerializer.Meta):
fields = ['id', 'username', 'password',
'email', 'first_name', 'last_name']
class UserSerializer(BaseUserSerializer):
class Meta(BaseUserSerializer.Meta):
fields = ['id', 'username', 'email', 'first_name', 'last_name']
class UserLoginSerializer(serializers.Serializer):
email = serializers.EmailField(required=True)
password = serializers.CharField(required=True, write_only=True)
def validate(self, attrs):
user = authenticate(username=attrs['email'], password=attrs['password'])
if not user:
raise serializers.ValidationError("Invalid email or password")
if not user.is_active:
raise serializers.ValidationError("User account is disabled.")
return user

App.js

import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import LoginPage from './LoginPage';
function App() {
return (
<Router>
<Routes>
<Route exact path="/" element={<LoginPage />} />
</Routes>
</Router>
);
}
export default App;

登录页面.jsx

import React, { useState } from 'react';
import axios from 'axios';
function LoginPage() {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const handleSubmit = async (e) => {
e.preventDefault();
try {
const response = await axios.post('http://127.0.0.1:8000/auth/jwt/create/', {
username: username,
password: password
});
localStorage.setItem('token', response.data.token);
const token = response.data.token;
axios.defaults.headers.common["Authorization"] = `Bearer ${token}`;
setError('');
} catch (error) {
setError('Invalid email or password');
}
}
return (
<div>
<h2>Login</h2>
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="username">Email:</label>
<input type="text" id="username" value={username} onChange={(e) => setUsername(e.target.value)} />
</div>
<div>
<label htmlFor="password">Password:</label>
<input type="password" id="password" value={password} onChange={(e) => setPassword(e.target.value)} />
</div>
<div>
<button type="submit">Login</button>
</div>
{error && <p>{error}</p>}
</form>
</div>
);
}
export default LoginPage;

即使输入了正确的用户名和密码,我仍然无法登录。当我转到url"时;http://127.0.0.1:8000/auth/users/me/"上面写着";未经授权";。我哪里错了?请帮忙。我已经连续试了5个小时了。

使用`Token ${token}`;这个Bearer ${token}

最新更新