簡體   English   中英

如何在Django Rest框架中從電子郵件和密碼獲取身份驗證令牌?

[英]How to get auth token from email and password in django rest framework?

我有一個django rest api作為我的android應用程序的后端。 我希望我的應用程序用戶能夠登錄並注冊我的應用程序。 當用戶注冊時,或將新用戶添加到用戶表時,應為該用戶生成身份驗證令牌。 我使用用戶模型中的以下代碼來執行此操作:

# This code is triggered whenever a new user has been created and saved to the database
@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
    if created:
        Token.objects.create(user=instance)

現在,當我嘗試以新創建的用戶身份登錄時,在使用令牌身份驗證時,我要做的就是在該用戶的請求正文中發布電子郵件和密碼。 我這樣使用改造2:

public interface UserService {
    @POST("users/api-token-auth/")
    Call<String> loginInToken(@Body LoginCredentials loginCredentials);
}

LoginCredentials類如下所示:

public class LoginCredentials {

    private String email;
    private String password;

    public LoginCredentials() { }

    public LoginCredentials(String email, String password) {
        this.email = email;
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public String getPassword() {
        return password;
    }
}

然后在我的應用程序中,使用UserService包含的以下接口方法對django rest api進行以下調用:

@Override
public void loginEmailUser(LoginCredentials loginCredentials) {
    Call<String> call = userServiceApi.loginInToken(loginCredentials);
    call.enqueue(new Callback<String>() {
        @Override
        public void onResponse(Call<String> call, Response<String> response) {
            Log.d("USER_REPOSITORY", response.toString());
        }

        @Override
        public void onFailure(Call<String> call, Throwable t) {
            Log.d("USER_REPOSITORY", t.toString());
        }
    });
}

如果成功,則電子郵件和密碼已經過帳到后端,以換取相應用戶的身份驗證令牌,因此,我應該通過發出此請求來接收令牌。 但是,當調用此端點api-token-auth時,將使用以下throwable調用onFailure方法:

USER_REPOSITORY: Response{protocol=http/1.0, code=400, message=Bad Request, url=http://XXX.YYY.Z.AAA:8000/users/api-token-auth/}

這是我的django urls.py文件,它對應於android客戶端調用的url:

from django.conf.urls import url
from users import views as user_views
from rest_framework.authtoken import views as auth_views

urlpatterns = [
    url(r'^api-token-auth/', auth_views.obtain_auth_token),
    url(r'^create/', user_views.UserCreate.as_view(), name="create"),
    url(r'^$', user_views.UserList.as_view(), name="users_list"),
    url(r'^(?P<pk>[0-9]+)/$', user_views.UserDetail.as_view(), name="user_detail"),
]

django rest文檔說,用電子郵件和密碼POSTed調用api-token-auth url應該導致返回令牌和狀態碼200。

當我似乎按照成功請求的指示進行操作時,為什么收到錯誤的請求和狀態代碼400?

我正在使用OAUth添加示例 LOGIN類。我正在使用Volley庫

public class Login extends AppCompatActivity implements View.OnClickListener {

    EditText userName, Password;
    Button login;
    public static final String LOGIN_URL = "http://192.168.100.5:84/Token";
    public static final String KEY_USERNAME = "UserName";
    public static final String KEY_PASSWORD = "Password";
    String username, password;
    String accesstoken, tokentype, expiresin, masterid, name, access, issue, expires, masterid1;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        userName = (EditText) findViewById(R.id.login_name);
        Password = (EditText) findViewById(R.id.login_password);
        userName.setHint(Html.fromHtml("<font color='#008b8b' style='italic'>Username</font>"));
        Password.setHint(Html.fromHtml("<font color='#008b8b'>Password</font>"));
        login = (Button) findViewById(R.id.login);
        login.setOnClickListener(this);
    }

    private void UserLogin() {

        username = userName.getText().toString().trim();
        password = Password.getText().toString().trim();
        StringRequest stringRequest = new StringRequest(Request.Method.POST, LOGIN_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            accesstoken = jsonObject.getString("access_token");
                            tokentype = jsonObject.getString("token_type");
                            expiresin = jsonObject.getString("expires_in");
                            username = jsonObject.getString("userName");
                            masterid = jsonObject.getString("MasterID");
                            masterid = masterid.replaceAll("[^\\.0123456789]", "");

                            masterid1 = jsonObject.getString("MasterID");

                            name = jsonObject.getString("Name");
                            access = jsonObject.getString("Access");
                            issue = jsonObject.getString(".issued");
                            expires = jsonObject.getString(".expires");
                            SessionManagement session = new SessionManagement(Login.this);
                            session.createLoginSession(accesstoken, tokentype, expiresin, username, masterid, name, access, issue, expires);
                            // session.createLoginSession(masterid1);
                            openProfile();

                        } catch (JSONException e) {
                            Toast.makeText(getApplicationContext(), "Fetch failed!", Toast.LENGTH_SHORT).show();
                            e.printStackTrace();
                        }

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // Toast.makeText(Login.this, error.toString(), Toast.LENGTH_LONG).show();
                        Toast.makeText(Login.this, "Please enter valid username and Password", Toast.LENGTH_SHORT).show();
                    }
                }) {


            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();
                //params.put("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
                return params;
            }

            @Override
            protected Map<String, String> getParams() {
                Map<String, String> map = new HashMap<String, String>();
                map.put(KEY_USERNAME, username);
                map.put(KEY_PASSWORD, password);
                //map.put("access_token", accesstoken);
                map.put("grant_type", "password");
                return map;
            }
        };
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(
                60000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));


        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }


    private void openProfile() {
        Intent intent = new Intent(this, Home.class);
        intent.putExtra(KEY_USERNAME, username);
        startActivity(intent);


        startActivity(intent);

    }

    @Override
    public void onClick(View v) {
        UserLogin();
    }


}

這是Sample。請根據需要進行轉換

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM