简体   繁体   中英

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

I have a django rest api as the backend for my android application. I want my app users to be able to sign in and sign up for my app. When users sign up, or when a new user is added to the user table, an authentication token for that user should be generated. I do this with the following code in the user model:

# 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)

Now when I try to sign in as the newly created user, when using Token Authentication, all I need to do is POST the email and password in the body of the request for the user. I do this like so using retrofit 2:

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

The LoginCredentials class looks like this:

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;
    }
}

In my app I then make the following call to the django rest api using this interface method contained in UserService :

@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());
        }
    });
}

If successful, the email and password have been POSTed to the backend in exchange for the corresponding user's authentication token, hence I should receive a token by making this request. However when this endpoint api-token-auth is called the onFailure method is called with the following throwable:

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

Here is my django urls.py file which corresponds to the called url from the android client:

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"),
]

The django rest docs say that calling the api-token-auth url with the email and password POSTed should result in the token being returned and a status code 200.

Why am I getting a bad request and status code 400 when I seem to be doing as instructed for a successful request?

I am Addding Sample LOGIN Class Using OAUth .I am using Volley library

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();
    }


}

this is Sample .please transform it as your requirement

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM