Android 使用 WebView setHttpAuthUsernamePassword?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2585055/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 06:25:41  来源:igfitidea点击:

Using WebView setHttpAuthUsernamePassword?

android

提问by user246114

I'm trying to do basic authentication to view a protected url. I want to access the protected url which looks like this:

我正在尝试进行基本身份验证以查看受保护的 url。我想访问如下所示的受保护 url:

http://api.test.com/userinfo/vid?=1234

So I do the following with a WebView:

因此,我使用 WebView 执行以下操作:

mWebView.setHttpAuthUsernamePassword("api.test.com", "", "[email protected]", "mypassword");
mWebView.loadUrl("http://api.test.com/userinfo/user?uid=53461");

but the authentication doesn't seem to work, I'm just getting an output error page. Am I using the WebView method correctly here?

但身份验证似乎不起作用,我只是收到一个输出错误页面。我在这里正确使用 WebView 方法吗?

Update: Trying with curl:

更新:尝试卷曲:

curl -u [email protected]:mypassword http://api.test.com/userinfo/user?uid=53461

and it pulls the page fine. I tried every combination of the host parameter, the owners of the api don't know what I mean by 'realm' though (and neither do I) - what info could I give them to help this along?

它可以很好地拉动页面。我尝试了主机参数的所有组合,但 api 的所有者不知道我所说的“领域”是什么意思(我也不知道) - 我可以给他们什么信息来帮助他们?

Thanks

谢谢

回答by dparnas

Another option is to use a WebViewClient;

另一种选择是使用 WebViewClient;

webview.setWebViewClient(new MyWebViewClient ());

private class MyWebViewClient extends WebViewClient {
@Override
public void onReceivedHttpAuthRequest(WebView view,
        HttpAuthHandler handler, String host, String realm) {

    handler.proceed("[email protected]", "mypassword");

}
}

回答by Dmitry

webview.setWebViewClient(new WebViewClient () {

    public void onReceivedHttpAuthRequest(WebView view,
            HttpAuthHandler handler, String host, String realm) {

        handler.proceed("login", "pass");
    }
});

回答by user1825382

The default behavior of a WebView is to discard all authentication requests. Even if setHttpAuthUsernamePassword.

WebView 的默认行为是丢弃所有身份验证请求。即使 setHttpAuthUsernamePassword。

You have to set a WebViewClient and Override the method onReceivedHttpAuthRequest

您必须设置一个 WebViewClient 并覆盖 onReceivedHttpAuthRequest 方法

回答by Fabi

If you do not mind writing your username and password into the url, then it is not necessary to change your webview client.

如果您不介意将您的用户名和密码写入 url,则无需更改您的 webview 客户端。

Just open the following url in the webview:

只需在 webview 中打开以下网址:

http://username:[email protected]/userinfo/vid?=1234

回答by Pentium10

In this example realm is By Invitation Only

在这个例子中,领域是 By Invitation Only

AuthType Basic
AuthName "By Invitation Only"
AuthUserFile /usr/local/apache/passwd/passwords
Require user rbowen sungo

回答by EpicPandaForce

This is so silly. I hacked something together that worked for me, I hope it'll work for you too.

这太愚蠢了。我一起破解了一些对我有用的东西,我希望它也对你有用。

public class AuthRequestDialogFragment extends DialogFragment
{
    @InjectView(R.id.dauth_userinput)
    public EditText userinput;

    @InjectView(R.id.dauth_passinput)
    public EditText passinput;

    @OnClick(R.id.dauth_login)
    public void login(View view) {
        ((Callback) getTargetFragment()).login(userinput.getText().toString(), passinput.getText().toString());
        this.dismiss();
    }

    @OnClick(R.id.dauth_cancel)
    public void cancel(View view) {
        ((Callback) getTargetFragment()).cancel();
        this.dismiss();
    }

    public static interface Callback
    {
        public void login(String username, String password);
        public void cancel();
    }

    @Override
    public void onStart() {
        super.onStart();
        WindowManager wm = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        int width = display.getWidth();
        int height = display.getHeight();

        getDialog().getWindow().setLayout(width*2/3, height/5*2);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        View view = inflater.inflate(R.layout.dialog_authrequest, container);
        ButterKnife.inject(this, view);
        getDialog().setTitle("Authorization required");
        return view;
    }
}

And

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">
    <TextView
        android:id="@+id/dauth_requsertext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="The server requires a username and password."
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_marginLeft="15dp"
        android:layout_marginStart="15dp"
        android:layout_marginTop="15dp"/>


    <RelativeLayout
        android:id="@+id/dauth_centercontainer"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true">
        <TextView
            android:id="@+id/dauth_usertext"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Username"
            android:layout_alignParentTop="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentLeft="true"
            android:layout_marginLeft="15dp"
            android:layout_marginStart="15dp"
            android:layout_marginTop="15dp"/>
        <TextView
            android:id="@+id/dauth_passtext"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:text="Password"
            android:layout_below="@+id/dauth_usertext"
            android:layout_alignLeft="@+id/dauth_usertext"
            android:layout_alignStart="@+id/dauth_usertext"/>
        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/dauth_userinput"
            android:ems="12"
            android:layout_alignBottom="@+id/dauth_usertext"
            android:layout_toRightOf="@id/dauth_usertext"
            android:layout_toEndOf="@id/dauth_usertext"/>
        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/dauth_passinput"
            android:layout_marginTop="20dp"
            android:inputType="textPassword"
            android:ems="12"
            android:layout_alignBottom="@+id/dauth_passtext"
            android:layout_toRightOf="@id/dauth_passtext"
            android:layout_toEndOf="@id/dauth_passtext"
            android:layout_alignLeft="@id/dauth_userinput"
            android:layout_alignStart="@id/dauth_userinput"/>

    </RelativeLayout>

    <Button
        android:id="@+id/dauth_cancel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Cancel"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_marginBottom="15dp"
        android:layout_marginRight="15dp"
        android:layout_marginEnd="15dp"/>


    <Button
        android:id="@+id/dauth_login"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Log In"
        android:layout_alignTop="@+id/dauth_cancel"
        android:layout_marginRight="15dp"
        android:layout_marginEnd="15dp"
        android:layout_toLeftOf="@+id/dauth_cancel"/>



</RelativeLayout>

And

public class WebViewFragment extends Fragment implements AuthRequestDialogFragment.Callback {

    @Override
    public void login(String username, String password) {
        Log.d(this.getClass().getName(), "Login");
        myWebViewClient.login(username, password);
    }

    @Override
    public void cancel() {
        Log.d(this.getClass().getName(), "Cancel");
        myWebViewClient.cancel();
    }

And the most important:

而最重要的是:

private class MyWebViewClient extends WebViewClient {
    private WebView myView;
    private HttpAuthHandler httpAuthHandler;
    private String host;
    private String realm;

    @Override
    public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
        AuthRequestDialogFragment authRequestDialogFragment = new AuthRequestDialogFragment();
        FragmentManager fragmentManager = ((getActivity()).getSupportFragmentManager());
        authRequestDialogFragment.setTargetFragment(WebViewFragment.this, 0);
        authRequestDialogFragment.show(fragmentManager, "dialog");
        this.httpAuthHandler = handler;
        this.myView = view;
        this.host = host;
        this.realm = realm;
    }

    public void login(String username, String password) {
        httpAuthHandler.proceed(username, password);
        myView = null;
        httpAuthHandler = null;
        host = null;
        realm = null;
    }

    public void cancel() {
        super.onReceivedHttpAuthRequest(myView, httpAuthHandler, host, realm);
        myView = null;
        httpAuthHandler = null;
        host = null;
        realm = null;
    }
}

Uses dependency:

使用依赖:

compile 'com.jakewharton:butterknife:6.0.0'

回答by CommonsWare

You may need something other than ""for the second parameter. Contact the developer of the Web site and find out what an appropriate realm should be. Or, use tools like curlto find out what the realm should be.

您可能需要除""第二个参数之外的其他内容。联系网站的开发人员并找出合适的领域应该是什么。或者,使用诸如curl找出领域应该是什么之类的工具。

回答by jettero

I never did get setHttpAuthUsernamePassword to work with phonegap's FileTransfer.download (since it doesn't use the webview), but I DIDget this to work with phonegap. It's worth noting if any other phonegap people end up on this thread.

我从来没有得到setHttpAuthUsernamePassword与PhoneGap的的FileTransfer.download工作(因为它不使用web视图),但我DID得到这个与PhoneGap的工作。值得注意的是,是否有任何其他 phonegap 人最终出现在此线程上。

    Authenticator.setDefault(new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(user, pass.toCharArray());
        }
    });