我读到了一些与在本地存储中存储 jwt 令牌相关的问题,这就是我尝试将令牌存储在仅 http cookie 中的原因。我正在使用以下方法。
from rest_framework.views import APIView
from rest_framework.response import Response
import jwt
from django.conf import settings
from rest_framework import status
class LoginView(APIView):
def post(self, request, format=None):
email = request.data['email']
password = request.data['password']
# dummy user authentication
if email == 'email' and password == 'password':
encoded = jwt.encode(
{'email': email}, settings.SECRET_KEY, algorithm='HS256')
response = Response()
response.set_cookie(key='token', value=encoded, httponly=True)
response.data = {
'user': email,
}
return response
else:
return Response({'error': 'wrong credentials'}, status=status.HTTP_401_UNAUTHORIZED)
Run Code Online (Sandbox Code Playgroud)
问题 1:这是使用 django Rest 框架设置 …
python authentication django cookie-httponly django-rest-framework
我正在尝试了解我的网络应用程序的身份验证系统,但我快疯了。此时我真的不知道自己在做什么,
无论如何,我正在开发 Django-React Web 应用程序并使用 JWT 令牌进行身份验证。为了安全措施,我决定不在客户端存储 JWT 令牌,这就是我的困惑开始的地方。所以我发出 axios POST 请求从 React => 登录
//LOGIN USER
export const login = (username, password) => dispatch => {
//Headers
const config = {
headers: {
"Content-type": "application/json"
}
}
//Request body
const body = JSON.stringify({ username, password })
axios.post("http://localhost:8000/auth/login/", body, config, {withCredentials: true})
.then(res => {
dispatch({
type: LOGIN_SUCCESS,
payload: res.data
})
}).catch(err => {
console.log(err)
dispatch({
type: LOGIN_FAIL
})
})
}
Run Code Online (Sandbox Code Playgroud)
和带有一些cookie的服务器响应=>
和 JSON 响应 =>
然后我想使用 access_token 进行身份验证,但由于它是 HttpOnly …
所以我有一个在 运行的 Express / TypeGraphql 后端localhost:5000,在 运行的 Next / React 应用程序localhost:3000。我决定使用 apollo-server 作为 graphql API,使用 apollo-client 作为前端。成功登录后,我将 httpOnly cookie 存储在网络浏览器中。
我想要做的是,在每个请求中获取 cookie,并在 oauth2 令牌有效的情况下向用户授权。即使请求有效,并且我收到查询,cookie 也显示为空。另外,我在控制台中没有收到任何错误。
\n这里我保存cookies =>
\napp.get('/auth/google/callback', function (req, res, next) {\n passport.authenticate('google', { session: false }, (err, user, info) => {\n if (err) return next(err);\n if (!user) return res.redirect('/');\n res.cookie('login_cookie', JSON.stringify(info), {\n secure: false,\n httpOnly: true,\n expires: dayjs().add(30, 'days').toDate(),\n sameSite: false,\n });\n return res.redirect('http://localhost:3000/home');\n })(req, res, next);\n});\nRun Code Online (Sandbox Code Playgroud)\n在这里,我在请求后将 …