如何在Android中使用摘要式身份验证? [英] how to use Digest authentication in android?

查看:126
本文介绍了如何在Android中使用摘要式身份验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建一个Android应用程序在那里,我通过server.Initially服务器验证用户名/密码正在实施基本的认证,所以我的code的工作正常,但现在服务器已更改为摘要的认证,所以我的老code是行不通的。

哪些变化应该做让使用摘要认证?

我的code是如下:

 私人布尔authenticateUser的()

{

   尝试
   {
        字符串url_str =htt​​p://serverweb.com/checkauthentication.php;

        HttpPost后=新HttpPost(url_str);

        Log.v(认证URL =,url_str);
        post.addHeader(授权,基本+ getCredentials());
        ResponseHandler的<字符串> ResponseHandler的=新BasicResponseHandler();
        字符串response_body = client.execute(后,ResponseHandler所);

        Log.v(服务器响应DATA =,response_body);

        XMLDataParser.parseXML(XMLDataParser.USER_INFORMATION_PARSER_ code,response_body);

        名单<饼干>饼干= client.getCookieStore()的getCookies()。
        如果(!cookies.isEmpty())
        {
         的for(int i = 0; I< cookies.size();我++)
         {
           XMLData.cookie = cookies.get(ⅰ);
         }
        }

        返回true;
    }
    赶上(MalformedURLException的MUE)
    {
      Log.i(MalformedURLException的,+ mue.getMessage());
      displayDialog(用户不存在);
      返回false;
    }
    赶上(IOException异常IOE)
    {
       Log.i(IOException异常,+ ioe.getMessage());
       displayDialog(用户不存在);
       返回false;
    }
    赶上(例外五)
    {
       Log.i(异常,+ e.getMessage());
       displayDialog(错误);
       返回false;
    }
}
私人字符串getCredentials()
{
    。字符串U = edit_username.getText()的toString();
    。串P = edit_password.getText()的toString();

    Log.v(用户名=,U);
    Log.v(密码=页);
    返程(Base64.en codeBytes((U +:+ P).getBytes()));
}
 

解决方案

您需要创建一个 HttpHost 的HttpContext 对象所需的凭据,并给它以执行方法。

这是一个简单的code,你的身份验证是独立的后端身份验证的。机器人的HTTP客户端将其转换为相应格式的照顾。勾选此示例code,这只是供您参考,并不能直接在code使用。 :)

这code为您的活动:

  @覆盖
公共无效onResume(){
    super.onResume();
    AsyncTask的<字符串,太虚,太虚> httpTask =新TestHttpThread();
    httpTask.execute(test_url,test_user,test_password);
}
 

样品 AsyncActivity

 私有类TestHttpThread扩展的AsyncTask<字符串,太虚,太虚> {

    @覆盖
    保护无效doInBackground(字符串... PARAMS){
       如果(params.length大于0){
            字符串URL = PARAMS [0];
            字符串username = PARAMS [1];
            字符串password = PARAMS [2];

            尝试 {
                AndroidHttpClient的HttpClient = AndroidHttpClient.newInstance(测试用户代理);

                URL urlObj =新的网址(URL);
                HttpHost主机=新HttpHost(urlObj.getHost(),urlObj.getPort(),urlObj.getProtocol());
                AuthScope范围=新AuthScope(urlObj.getHost(),urlObj.getPort());
                UsernamePasswordCredentials creds =新UsernamePasswordCredentials(用户名,密码);

                CredentialsProvider CP =新BasicCredentialsProvider();
                cp.setCredentials(范围,creds);
                HttpContext的credContext =新BasicHttpContext();
                credContext.setAttribute(ClientContext.CREDS_PROVIDER,CP);

                HTTPGET工作=新HTTPGET(URL);
                HTT presponse响应= httpClient.execute(主机,工作,credContext);
                状态行状态= response.getStatusLine();
                Log.d(TestActivity.TEST_TAG,status.toString());
                httpClient.close();
            }
            赶上(例外五){
                e.printStackTrace();
            }

        }
        返回null;
    }
}
 

I am creating an Android app where I am authenticating username/password through a server.Initially server was implementing Basic authentication so my code was working fine but now server has changed to Digest authentication so my old code is not working.

What changes should do make for using Digest authentication?

My code is as follows:

private boolean authenticateUser() 

{

   try 
   {
        String url_str = "http://serverweb.com/checkauthentication.php"; 

        HttpPost post = new HttpPost(url_str);

        Log.v("AUTHENTICATION URL = ", url_str);
        post.addHeader("Authorization","Basic "+getCredentials());
        ResponseHandler<String> responseHandler=new BasicResponseHandler();
        String response_body = client.execute(post, responseHandler);

        Log.v("SERVER RESPONSE DATA = ", response_body);

        XMLDataParser.parseXML(XMLDataParser.USER_INFORMATION_PARSER_CODE, response_body);

        List<Cookie> cookies = client.getCookieStore().getCookies();
        if (!cookies.isEmpty()) 
        {
         for (int i = 0; i < cookies.size(); i++) 
         {
           XMLData.cookie = cookies.get(i);
         }
        }

        return true;
    }
    catch (MalformedURLException mue) 
    { 
      Log.i("MalformedURLException", " "+mue.getMessage());
      displayDialog("User Does Not exist");
      return false;
    } 
    catch (IOException ioe) 
    { 
       Log.i("IOException", " "+ioe.getMessage());
       displayDialog("User Does Not exist");
       return false;
    }
    catch (Exception e) 
    { 
       Log.i("Exception", " "+e.getMessage());
       displayDialog("Error");
       return false;
    }
}
private String getCredentials()
{
    String u=edit_username.getText().toString();
    String p=edit_password.getText().toString();

    Log.v("USER NAME = ",u);
    Log.v("PASSWORD = ",p);
    return(Base64.encodeBytes((u+":"+p).getBytes()));
}

解决方案

You need to create a HttpHost and HttpContext object with required credentials and give it to execute method.

This is a sample code where your authentication is independent of backend auth. http client of android will take care of converting it to appropriate format. Check this sample code, this is only for your reference and not to be used directly in your code. :)

This code is in your activity:

@Override
public void onResume(){
    super.onResume();
    AsyncTask<String, Void, Void> httpTask = new TestHttpThread();
    httpTask.execute("test_url","test_user","test_password");
}

Sample AsyncActivity:

private class TestHttpThread extends AsyncTask<String, Void, Void>{

    @Override
    protected Void doInBackground(String... params) {
       if(params.length > 0){
            String url = params[0];
            String username = params[1];
            String password = params[2];

            try {
                AndroidHttpClient httpClient = AndroidHttpClient.newInstance("test user agent");

                URL urlObj = new URL(url);
                HttpHost host = new HttpHost(urlObj.getHost(), urlObj.getPort(), urlObj.getProtocol());
                AuthScope scope = new AuthScope(urlObj.getHost(), urlObj.getPort());
                UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);

                CredentialsProvider cp = new BasicCredentialsProvider();
                cp.setCredentials(scope, creds);
                HttpContext credContext = new BasicHttpContext();
                credContext.setAttribute(ClientContext.CREDS_PROVIDER, cp);

                HttpGet job = new HttpGet(url);
                HttpResponse response = httpClient.execute(host,job,credContext);
                StatusLine status = response.getStatusLine();
                Log.d(TestActivity.TEST_TAG, status.toString());
                httpClient.close();
            }
            catch(Exception e){
                e.printStackTrace();
            }

        }
        return null;
    }
}

这篇关于如何在Android中使用摘要式身份验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆