Как войти в систему с помощью outlook / microsoft, используя webview? - PullRequest
0 голосов
/ 27 июня 2018

Существуют библиотеки, доступные для входа в Outlook с использованием браузера (особенно браузера Chrome, т.е. библиотеки MSAL android) ИЛИ ADAL, но я не хочу входить в систему с помощью Chrome, поскольку на моем устройстве Chrome недоступен (его пользовательская ОС мелькнул в андроид устройстве).
Я попытался на моем конце также, но он не работает, так как этот код дает токен доступа, но бесполезен для вызова графа API вот мой код

    package learn2crack.weboauth2;

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class MainActivity extends Activity implements View.OnClickListener {

    private static final String TAG = "MainActivity";
    //Change the Scope as you need
    WebView web;
    Button auth;
    SharedPreferences pref;
    TextView Access;
    String authCode = "";
    private Dialog auth_dialog;
    private Button authEbay;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        pref = getSharedPreferences("AppPref", MODE_PRIVATE);
        Access =(TextView)findViewById(R.id.Access);
        auth = (Button)findViewById(R.id.auth);
        auth.setOnClickListener(this);
        authEbay = (Button)findViewById(R.id.auth_ebay);
        auth.setOnClickListener(this);
        authEbay.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.auth:
                auth(Constants.OUTLOOK.USER_AGENT,
                        Constants.OUTLOOK.OAUTH_URL,
                        Constants.OUTLOOK.REDIRECT_URI,
                        Constants.OUTLOOK.CLIENT_ID,
                        Constants.OUTLOOK.OAUTH_SCOPE);
                break;
            case R.id.auth_ebay:
                    auth(Constants.EBAY.USER_AGENT,
                            Constants.EBAY.OAUTH_URL,
                            Constants.EBAY.REDIRECT_URI,
                            Constants.EBAY.CLIENT_ID,
                            Constants.EBAY.OAUTH_SCOPE);
                break;
        }
    }


    private void auth(String userAgent, String oauthUrl, String redirectUri, String clientId,
                             String oauthScope) {
        final Dialog auth_dialog;
            // TODO Auto-generated method stub
            auth_dialog = new Dialog(MainActivity.this);
            auth_dialog.setContentView(R.layout.auth_dialog);
            web = (WebView)auth_dialog.findViewById(R.id.webv);
            web.getSettings().setJavaScriptEnabled(true);
            WebSettings webSettings = web.getSettings();
            web.getSettings().setUserAgentString(userAgent);
            webSettings.setSupportMultipleWindows(true);
            web.loadUrl(oauthUrl+"?redirect_uri="+
                    redirectUri+"&response_type=code&client_id="+
                    clientId+"&scope="+ oauthScope);
            web.setWebViewClient(new WebViewClient() {
                boolean authComplete = false;
                Intent resultIntent = new Intent();
                @Override
                public void onPageStarted(WebView view, String url, Bitmap favicon){
                    super.onPageStarted(view, url, favicon);
                }

                @Override
                public void onPageFinished(WebView view, String url) {
                    super.onPageFinished(view, url);
                    if (url.contains("?code=") && authComplete != true) {
                        Uri uri = Uri.parse(url);
                        authCode = uri.getQueryParameter("code");
                        callGraphAPI(authCode);
                        Log.i("", "CODE : " + authCode);
                        authComplete = true;
                        resultIntent.putExtra("code", authCode);
                        auth_dialog.dismiss();
                        Toast.makeText(getApplicationContext(),"Authorization Code is: "
                                +authCode, Toast.LENGTH_SHORT).show();
                    }else if(url.contains("error=access_denied")){
                        Log.i("", "ACCESS_DENIED_HERE");
                        Toast.makeText(getApplicationContext(), "Error Occured",
                                Toast.LENGTH_SHORT).show();
                        auth_dialog.dismiss();
                    }
                }
            });
            auth_dialog.show();
            auth_dialog.setTitle("Authorize Learn2Crack");
            auth_dialog.setCancelable(true);
    }



    private void callGraphAPI(final String code)

    {
        Log.d(TAG, "Starting volley request to graph");

        /* Make sure we have a token to send to graph */

        RequestQueue queue = Volley.newRequestQueue(this);
        JSONObject parameters = new JSONObject();

        try {
            parameters.put("key", "value");
        } catch (Exception e) {
            Log.d(TAG, "Failed to put parameters: " + e.toString());
        }
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, Constants.OUTLOOK.MSGRAPH_URL,
                parameters,new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                /* Successfully called graph, process data and send to UI */
                Log.d(TAG, "Response: " + response.toString());

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d(TAG, "Error: " + error.toString());
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap();
                headers.put("Authorization", "Bearer " + authCode);
                return headers;
            }
        };

        Log.d(TAG, "Adding HTTP GET to Queue, Request: " + request.toString());

        request.setRetryPolicy(new DefaultRetryPolicy(
                3000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(request);
    }
}

Кто-нибудь, пожалуйста, подскажите, как получить правильный токен доступа после входа в систему через Microsoft / Outlook, используя веб-просмотр. Заранее спасибо.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...