如何解决在我的code中的密码/用户名认证? [英] How Do I fix the password/ username authentication in my code?

查看:152
本文介绍了如何解决在我的code中的密码/用户名认证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序中,我登录时使用自己的用户名和密码,然后我切换到一个网页,其中包含一个web视图。 web视图认识到这一点的用户名和密码,并加载内容(直通共享preferences),但问题是,它加载只有一次,当我浏览到我的应用程序的其它部分再回来,它显示了一个空白的屏幕,最终加载页面不能被显示终端; ayed在web视图。反正有没有解决这个问题,让web视图识别的用户名,并通过每次ü导航到该页面并加载content.Here的的$ C $下是相同的: 包含web视图页面:

I have an app in which I log in using my username and password and then I switch to a page which contains a webview. The webview recognizes this username and password and loads the content (thru sharedpreferences) , but the issue is, it loads ONLY ONCE and when i navigate to some other part of my app and come back, it shows a blank screen which eventually loads page cant be displ;ayed in the webview. Is there anyway to fix this, to keep the webview recognize the username and pass everytime u navigate to the page and load the content.Here's the code for the same: The page containing the webview :

public class AnswersFragmentWebView extends Fragment implements  MainActivity.BackPressListener<Fragment>  {

    private static final String SYMBOL = "symbol";
    private static final String SYMBOL_TYPE = "symbol_type";
    public  static final String CONTAINER_ID = "container_id";
    public static final String TAG_QUOTES_FRAGMENT_WEBVIEW = "AnswersFragmentWebView";
    public static void removeInstance(final FragmentManager manager) {
        final AnswersFragmentWebView fragment = (AnswersFragmentWebView) manager.findFragmentByTag(TAG_QUOTES_FRAGMENT_WEBVIEW);
        if (fragment == null) {
            return;
        }

        final FragmentStackManager stackManager = FragmentStackManager.getInstance();
        if (stackManager.getTopFragment() instanceof AnswersFragmentWebView) {
            stackManager.popTopFragment();
        }
    }

    private boolean goingBack = false;
    private boolean onBackPressClearStack = true;
    private WebView webView;
    private final static String URL = "https://amers1.mobile13.cp.justice.com/msf1.0/fwd/answers/answers/service/v1/?q=ibm%20revenue&ui.theme=dark&uuid=PADACT-002&userAgent=iphone";
    //private final static String URL = "https://www.google.com";
    SharedPreferencesManager manager = SharedPreferencesManager.getInstance();
    private final  String USERNAME =manager.getLoginUsername(); 
    private final  String PASSWORD = manager.getDecryptedLoginPassword();
    private final static String HOST = "https://amers1.mobile13.cp.justice.com/msf1.0/fwd/answers/answers/service/v1/?q=ibm%20revenue&ui.theme=novadark&uuid=PADACT-002&userAgent=iphone";
    private final static String REALM = "Users Only";

    public void setOnBackPressClearStack(boolean b){
        onBackPressClearStack = b;
    }
    public boolean webViewSteppedBack() {
        if (webView != null && webView.canGoBack()) {
            webView.goBack();

            return true;
        }
        return false;
    }

    @Override
    public boolean backPressed(final MainActivity mainActivity) {
        if (webViewSteppedBack()) {
            return true;
        }

        if (onBackPressClearStack) {
            goingBack = true;
            FragmentUtils.onBackPressedKnockFragsOffStack(mainActivity, this);
        }
        return false;
    }

    private static AnswersFragmentWebView __newInstance(final AnswersFragmentWebView fragment, final FragmentManager manager,
            final String searchAutoSuggestSymbol, final String symbolType, int containerViewId, final int inAnimation, final int outAnimation, final int popInAnimation, final int popOutAnimation) {
        final Bundle bundle = new Bundle();
        bundle.putString(AnswersFragmentWebView.SYMBOL, searchAutoSuggestSymbol);
        bundle.putString(AnswersFragmentWebView.SYMBOL_TYPE, symbolType);
        bundle.putInt(AnswersFragmentWebView.CONTAINER_ID, containerViewId);
        fragment.setArguments(bundle);

        FragmentInfo fragmentInfo = new FragmentInfo(TransactionMethods.ADD, containerViewId);
        fragmentInfo.setAnimation(inAnimation, outAnimation);
        fragmentInfo.setPopAnimation(popInAnimation, popOutAnimation);
        fragmentInfo.setFragmentTag(TAG_QUOTES_FRAGMENT_WEBVIEW);
        fragmentInfo.setActionBarTitle(Application.getAppResources().getString(R.string.nav_option_quotes));
        FragmentStackManager.getInstance().transitionFragment(manager, fragment, fragmentInfo);

        return fragment;
    }

    private static AnswersFragmentWebView __newInstance(final AnswersFragmentWebView fragment, final FragmentManager manager,
            final String searchAutoSuggestSymbol, final String symbolType, int containerViewId) {
        return __newInstance(fragment, manager, searchAutoSuggestSymbol, symbolType, containerViewId, R.anim.slide_in_from_right, R.anim.slide_out_to_left, R.anim.slide_in_from_left, R.anim.slide_out_to_right);
    }


    private static void clearWebView(final FragmentManager manager) {
        final AnswersFragmentWebView fragment = (AnswersFragmentWebView) manager.findFragmentByTag(TAG_QUOTES_FRAGMENT_WEBVIEW);
        if (fragment != null && fragment instanceof AnswersFragmentWebView) {
            ((AnswersFragmentWebView)fragment).clearWebView();
        }
    }

    public static AnswersFragmentWebView newInstance(final FragmentManager manager, final String searchAutoSuggestSymbol, String symbolType) {
        clearWebView(manager);
        return __newInstance(new AnswersFragmentWebView(), manager, searchAutoSuggestSymbol, symbolType, R.id.fragment_container);
    }

    public static AnswersFragmentWebView newInstance(final FragmentManager manager, final String searchAutoSuggestSymbol, String symbolType, int containerViewId) {
        clearWebView(manager);
        return __newInstance(new AnswersFragmentWebView(), manager, searchAutoSuggestSymbol, symbolType, containerViewId);
    }

    public static AnswersFragmentWebView newInstanceNoBackPressed(final FragmentManager manager, final String searchAutoSuggestSymbol,  final String symbolType, int containerViewId) {
        AnswersFragmentWebView fragment =  __newInstance(new AnswersFragmentWebView(), manager, searchAutoSuggestSymbol, symbolType, containerViewId);
        fragment.setOnBackPressClearStack(false);
        return fragment;
    }

    public static AnswersFragmentWebView newInstanceNoBackPressed(final AnswersFragmentWebView fragment, final FragmentManager manager, final String searchAutoSuggestSymbol, final String symbolType, int containerViewId) {
        fragment.setOnBackPressClearStack(false);
        return __newInstance(fragment, manager, searchAutoSuggestSymbol, symbolType, containerViewId);
    }

    public static AnswersFragmentWebView newInstanceForSearch(final FragmentManager manager, final String searchAutoSuggestSymbol, String symbolType) {
        AnswersFragmentWebView fragment = __newInstance(new AnswersFragmentWebView(), manager, searchAutoSuggestSymbol, symbolType, R.id.fragment_container, R.anim.no_animation, R.anim.slide_out_to_right, R.anim.slide_in_from_right, R.anim.slide_out_to_right);
        return fragment;
    }

    public void clearWebView() {
        if (webView != null) {
            webView.removeAllViews();
            webView.destroy();
            webView = null;
        }
    }



    @SuppressWarnings("deprecation")
    @SuppressLint("NewApi")
    @Override
    public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (goingBack) {
            return null;
        }
        final MainActivity activity = (MainActivity) getActivity();

        activity.setBackPressListener(this);


        final View view = inflater.inflate(R.layout.fragment_search_answers, container, false);

        if (!NetworkUtils.isOnline()) {
            LayoutUtils.showNoResult(view, R.id.quotes_webview_container);
            return view;

        }

        // setup webview
        webView = (WebView) view.findViewById(R.id.webview);


        webView.setVisibility(View.VISIBLE);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebChromeClient(new WebChromeClient());
        webView.setBackgroundColor(0);
        webView.requestFocus();
        webView.reload();
        webView.getSettings().setSavePassword(true);
        webView.getSettings().setSaveFormData(true);
        webView.getSettings().getSaveFormData();
        webView.getSettings().getSavePassword();
        //WebViewDatabase.getInstance(getActivity()).clearHttpAuthUsernamePassword();
        WebViewDatabase.getInstance(getActivity()).hasHttpAuthUsernamePassword();
        webView.setHttpAuthUsernamePassword(HOST, REALM, USERNAME, PASSWORD);
        webView.setWebViewClient(new AnswersWebView(this,webView));
        webView.loadUrl(URL);



        return view;
    }

    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getArguments().getString(AnswersFragmentWebView.SYMBOL);
    }


}

web视图客户端:

The webview client:

public class AnswersWebView extends WebViewClient {

    private String loginCookie;
    private Context mContext;
    private WebView mWebView;

    public AnswersWebView(AnswersFragmentWebView answersFragmentWebView, WebView webview) {
        super();

        //mContext = answersFragmentWebView;
        mWebView = webview;
    }

    @Override
    public void onPageStarted( WebView view, String url, Bitmap favicon ) {
    }

    @Override
    public void onPageFinished( WebView view, String url ) {
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setCookie(url, loginCookie);
    }

    @Override
    public void onReceivedError( WebView view, int errorCode, String description, String failingUrl ) {
        Toast.makeText(view.getContext(), "ÉyÅ[ÉWì«Ç›çûÇ›ÉGÉâÅ[", Toast.LENGTH_LONG).show();
    }

    @Override
    public void onLoadResource( WebView view, String url ){
        CookieManager cookieManager = CookieManager.getInstance();
        loginCookie = cookieManager.getCookie(url);
    }

    @Override
    public boolean shouldOverrideUrlLoading( WebView view, String url ) {
        return false;
    }

    @Override
    public void onReceivedSslError( WebView view, SslErrorHandler handler, SslError error ) {
        handler.proceed();
    }

    @Override
    public void onReceivedHttpAuthRequest( WebView view, final HttpAuthHandler handler, final String host, final String realm ){
        SharedPreferencesManager manager = SharedPreferencesManager.getInstance();
        String userName = manager.getLoginUsername();
        String userPass = manager.getDecryptedLoginPassword();

        if (handler.useHttpAuthUsernamePassword() && view != null) {
            String[] haup = view.getHttpAuthUsernamePassword(host, realm);
            if (haup != null && haup.length == 2) {
                userName = haup[0];
                userPass = haup[1];
            }
        }

        if (userName != null && userPass != null) {
            handler.proceed(userName, userPass);
        }
        else {
            showHttpAuthDialog(handler, host, realm, null, null, null);
        }
    }

    private void showHttpAuthDialog( final HttpAuthHandler handler, final String host, final String realm, final String title, final String name, final String password ) {
        LinearLayout llayout = new LinearLayout((Activity)mContext);
        final TextView textview1 = new TextView((Activity)mContext);
        final EditText edittext1 = new EditText((Activity)mContext);
        final TextView textview2 = new TextView((Activity)mContext);
        final EditText edittext2 = new EditText((Activity)mContext);
        llayout.setOrientation(LinearLayout.VERTICAL);
        textview1.setText("username:");
        textview2.setText("password:");
        llayout.addView(textview1);
        llayout.addView(edittext1);
        llayout.addView(textview2);
        llayout.addView(edittext2);

        final Builder mHttpAuthDialog = new AlertDialog.Builder((Activity)mContext);
        mHttpAuthDialog.setTitle("Basic Authentication")
        .setView(llayout)
        .setCancelable(false)
        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                EditText etUserName = edittext1;
                String userName = etUserName.getText().toString();
                EditText etUserPass = edittext2;
                String userPass = etUserPass.getText().toString();

                mWebView.setHttpAuthUsernamePassword(host, realm, name, password);

                handler.proceed(userName, userPass);
            }
        })
        .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                handler.cancel();
            }
        })
        .create().show();
    }

}

谢谢! 贾斯汀

Thanks! Justin

推荐答案

这其中有是一个最简单的永远。 试试这个:

This one has to be the easiest one ever. Try this :

@Override
        public void onLoadResource( WebView view, String url ){
            //CookieManager cookieManager = CookieManager.getInstance();
            //loginCookie = cookieManager.getCookie(url);
        }

注释掉饼干onloadresource,将prevent它与您的身份验证冲突,并最终加载的URL,没有任何问题,如果认证是没有任何冲突正确的,你可能想通过管理来解决在弹出窗口自动登录饼干正常。

Commenting out the cookies onloadresource, will prevent it from clashing with your authentication, and eventually load the url without any issue if the authentication is correct without any clashes, you might want to fix the auto sign in popups by managing cookies properly.

这篇关于如何解决在我的code中的密码/用户名认证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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