How to handle OAuth URL callbacks with Intent filters if authentication is done with webview?

后端 未结 3 944
情深已故
情深已故 2021-02-02 14:35

I am developing an app which uses OAuth for authentication but I have a little problem handling OAuth callbacks.

THE AUTHENTICATION

My app has a

3条回答
  •  猫巷女王i
    2021-02-02 14:48

    First of all in your manifest, set these properties to your activity that launches the WebView

    android:launchMode="singleInstance" 
    

    and add an intent filter to that as

    
        
        
        
        
    
    

    then in your code when the user clicks on the login button

    mReqToken = mTwitter.getOAuthRequestToken(CALLBACK_URL);
    WebView webView = new WebView(this);
    webView.requestFocus(View.FOCUS_DOWN);
    webView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                case MotionEvent.ACTION_UP:
                if (!v.hasFocus()) {
                    v.requestFocus();
                }
                break;
            }
            return false;
        }
    });
    webView.loadUrl(mReqToken.getAuthenticationURL());
    mainLayout.removeAllViews();
    mainLayout.addView(webView);
    

    Here the callback url is
    private static final String CALLBACK_URL = "oauth-testing:///";
    and you are creating a dynamic webview and displaying to the user. And after logging in the webview is closed and the code comes to the onNewIntent(). You need to implement your functionality after logging in there.

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        dealWithTwitterResponse(intent);
    }  
    private void dealWithTwitterResponse(Intent intent) {
        Uri uri = intent.getData();
        System.out.println("URI=" + uri);
        if (uri != null && uri.toString().startsWith(CALLBACK_URL)) {
            String oauthVerifier = uri.getQueryParameter("oauth_verifier");
            authoriseNewUser(oauthVerifier);
        }
    }
    

    I know I have added a lot of code snippet, some of which might not be relevant, but i hope it will help someone someday.

提交回复
热议问题