我想在后端使用 Django 和 Django-REST 框架来对本机 android 应用程序上的用户进行身份验证。我目前正在使用基于令牌的身份验证系统。(更多细节)
我已经实施了指南中列出的完全相同的过程来设置令牌身份验证。
现在我希望我的用户能够获取令牌以换取凭据。我使用以下代码发出 POST 请求:
JSONObject cred = new JSONObject();
try {
cred.put("password",mPassword);
cred.put("username",mEmail);
} catch (JSONException e) {
e.printStackTrace();
}
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(Common.getServerUrl()+"/api-token-auth/");
StringEntity credentials = new StringEntity( cred.toString());
credentials.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
httpPost.setEntity(credentials);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
// Read content & Log
inputStream = httpEntity.getContent();
Log.i("Asynctask", cred .toString());
...
Run Code Online (Sandbox Code Playgroud)
但是,当我将其发布到“views.obtain_auth_token”的 django 后端时,我总是出现此错误:
在服务器上:
"POST …Run Code Online (Sandbox Code Playgroud) 为 Django 编写的两个 JWT 包都给我带来了文档不佳的问题,所以我尝试了 DRF-auth_token 包。这是我遵循的一个很好的例子,Django Rest Framework Token Authentication。理论上你应该能够去
localhost:8000/api-token-auth/
网址.py:
from django.conf.urls import url, include
from django.contrib import admin
from django.contrib.auth.models import User
from rest_framework.authtoken import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/', include('api.urls', namespace='api')),
url(r'^orders/', include('orders.urls', namespace='orders')),
url(r'^api-token-auth/', views.obtain_auth_token, name='auth-token'),
]
Run Code Online (Sandbox Code Playgroud)
为用户获取令牌不起作用,所以我自己重写了它以使其工作:
@api_view(['POST'])
def customer_login(request):
"""
Try to login a customer (food orderer)
"""
data = request.data
try:
username = data['username']
password = data['password']
except:
return Response(status=status.HTTP_400_BAD_REQUEST)
try:
user = User.objects.get(username=username, password=password)
except:
return …Run Code Online (Sandbox Code Playgroud) python django django-rest-framework django-rest-auth django-1.10