I read a lot of things about authentication, but I don't know what's the best way to proceed.
How to create a token ? Should I use OAuth2 ? Can I store this token in SharedPreference to keep session alive when the user closes/reopens the app and when he uses the app ? Is it secured ?
I'm a bit lost.
Thanks a lot.
In general it is a good idea to store token instead of passwords and usernames. So you can authenticate against a system and do that things you need to do. For more background why storing passwords is a bad idea: Passwords are often used on multiple platforms so if an attacker get one password the user has a big damage, while token expire and can been renewed often without any user interaction.
Typically you get tokens with OAuth sometimes also with a initial credentials authentification. In the end you have a token which you to send to each request so the server will know who you are.
You can safely store those tokens. I hope that helps.
How to create a token ?
About this, you can refer to my answer at How to use security (Authentication & Authorization) in ASP Web Api
Sample code for getting access token from remote web service (for example, Asp.Net Web API):
public static Object getAccessToken(String address, String grant_type, String username, String password) throws Exception {
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("grant_type", grant_type));
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
// Making HTTP request
httpResponse = makeHTTPRequest(address, params);
if (httpResponse != null) {
statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_BAD_REQUEST) {
return httpResponse.getStatusLine().toString();
}
// Get JSON String (jsonString) from Input Stream (is)
getJSONFromInputStream();
if (jsonString.isEmpty()) {
return null;
}
// Parse the JSON String to a JSON Object
jObj = new JSONObject(jsonString);
}
return jObj;
}
Inside makeHTTPRequest, for request access token:
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
httpPost.setEntity(new UrlEncodedFormEntity(parameters));
Hope this provides you with some information you need.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With