[英]Django REST authentication not working with React
实际上我想要:如果用户经过身份验证:然后使用用户创建/获取购物车,否则:使用 session 密钥创建/获取购物车。 但起初,身份验证发生了问题。
起初我尝试注册用户并将密钥(从 drf 获得)保存在本地存储中。
在 Reactjs 中:
signupHandler=()=>{
fetch('http://127.0.0.1:8000/api/rest-auth/registration/', {
method: 'POST',
headers:{
'content-type':'application/json',
},
body:JSON.stringify({
'username':this.state.username,
'email': this.state.email,
'password1': this.state.pass1,
'password2': this.state.pass2
})
})
.then((response)=>{
response.json().then((result)=>{
if (result.key !== undefined){
localStorage.setItem('login', JSON.stringify({login: true,token:result.key}))
this.setState({registered: true})
}
})
})
}
我认为这里没有问题。 如果我 console.log() the key ,它会成功打印密钥。
现在看看我的views.py 。 我认为问题就在这里。
@api_view(['GET'])
#@permission_classes((IsAuthenticated,))<<< if i comment out this line, and try to call this function, it shows >>>Forbidden: /addToCart/21/
def addToCart(request, pk):
print(request.user)#>>>AnonymousUser
product = get_object_or_404(Product, pk=pk)
if request.user.is_authenticated:
print('authenticated')#>>> nothing prints
mycart, __ = Cart.objects.get_or_create(user=request.user)
mycart.product.add(product)
else:
print('session')#>>>session
if not request.session.exists(request.session.session_key):
request.session.create()
mycart, __ = Cart.objects.get_or_create(session_key=request.session.session_key)
mycart.product.add(product)
return Response({'response':'ok'})
现在我做了一个按钮,如果我点击,这个 function 调用
reactjs:
addToCart=()=>{
var id = this.props.id
let store = JSON.parse(localStorage.getItem('login'))
console.log(store.token);//successfully print the key
var url = 'http://127.0.0.1:8000/addToCart/'+id+'/'
fetch(url,{
method:'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Token '+store.token
}
}).then(res=>res.json().then(result=>{
if(result.response === 'ok'){
this.props.dispatch({
type: 'itemInCart',
})
this.setState({addedToCart: true})
}
}))
}
所以我的问题是:
*如果我注释掉@permission_classes((IsAuthenticated,))
行,为什么它显示Forbidden虽然我不想要这一行。 因为我也想要,用户可以使用 session 添加项目。
*(在views.py中)当我打印request.user
时它显示>>>AnonymousUser。 如何打印真实用户?
您需要在 settings.py 中添加DEFAULT_AUTHENTICATION_CLASSES
或将装饰器@authentication_classes([TokenAuthentication])
添加到 api_view(如果尚未完成)。
由于您需要 API 也可供未经身份验证的用户访问,因此不需要@permission_classes
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.