9 authentication android login http
嘿伙计们,我有一些关于在Android中实现登录功能的问题.
1. Does android have anything like sessions or cookies?我应该如何"记住"用户被淹没?显然我不希望每次使用我的应用程序时都要求输入密码!
2. Should I hash the password before sending it to the server?我的数据库中有一个表,其中包含用户和密码列.当我想检查登录时,是否应该将密码哈希发送到服务器login.php?u=sled&p=34819d7beeabb9260a5c854bc85b3e44,或者只是将纯文本发送到服务器login.php?u=sled&p=mypassword上并在执行身份验证之前将其哈希?
android有会话或cookie吗?
是.有两种选择.
选项1:
您可以CookieManager用来设置cookie.
选项#2:
另一种选择(我在我的一个应用程序中使用此替代方法)是在您将用户名和密码发送到服务器后(例如通过HttpPost或HttpGet)获取cookie .在您的问题中,您正在使用$_GET登录身份验证的样式,因此我将使用示例代码HttpGet.
示例代码使用HttpGet:
HttpParams httpParams = new BasicHttpParams();
// It's always good to set how long they should try to connect. In this
// this example, five seconds.
HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
HttpConnectionParams.setSoTimeout(httpParams, 5000);
DefaultHttpClient postClient = new DefaultHttpClient(httpParams);
// Your url using $_GET style.
final String url = "www.yourwebsite.com/login.php?u=myusername&p=mypassword";
HttpGet httpGet = new HttpGet(url);
HttpResponse response;
try {
// Execute your HttpGet against the server and catch the response to our
// HttpResponse.
response = postClient.execute(httpGet);
// Check if everything went well.
if(response.getStatusLine().getStatusCode() == 200) {
// If so, grab the entity.
HttpEntity entity = response.getEntity();
// If entity isn't null, grab the CookieStore from the response.
if (entity != null) {
CookieStore cookies = postClient.getCookieStore();
// Do some more stuff, this should probably be a method where you're
// returning the CookieStore.
}
}
} catch (Exception e) {
}
Run Code Online (Sandbox Code Playgroud)
现在当你拥有你的CookieStore; 从中获取Cookie列表,之后您可以使用它Cookie来确定名称,域名,值等...
下次您尝试访问您网站的"锁定"内容时; HttpURLConnection根据您的Cookie信息为您设置Cookie :
URL url = new URL("www.yourwebsite.com/lockedcontent.php");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setInstanceFollowRedirects(false);
// "Host" and "Cookie" are fields in the HTTP response. Use WireShark
// via your computer to determine correct header names.
httpURLConnection.setRequestProperty("Host", domainOfYourCookie);
httpURLConnection.setRequestProperty("Cookie", valueOfYourCookie);
final int responseCode = httpURLConnection.getResponseCode();
// And get the content...
Run Code Online (Sandbox Code Playgroud)
我应该在将密码发送到服务器之前对其进行散列吗?
取决于您的系统的设计方式.将信息发送到服务器时,您必须拥有正确的信息.这还取决于您如何在.php文件中对信息进行哈希处理.
我应该如何"记住"用户被淹没?
将信息存储在某个SharedPreferences或类似的东西中.就像我之前说的那样,如果您的登录系统设计正确,您可以哈希它 - 这取决于您在.php文件中如何对其进行哈希处理.