none
안드로이드] Token request failed with error 토큰 받아오기 오류

    질문

  • Application Registraion Portal 에 있는 Sample 을 그대로 따라했는데요 

    https://apps.dev.microsoft.com/#/appList

    코드는

    public class MainActivity extends AppCompatActivity {
    final static String CLIENT_ID = "6c3d5581-2ee6-4848-a73c-49724b6d5f52";
    final static String SCOPES [] = {"https://graph.microsoft.com/User.Read"};
    final static String MSGRAPH_URL = "https://graph.microsoft.com/v1.0/me";

    /* UI & Debugging Variables */
    private static final String TAG = MainActivity.class.getSimpleName();
    Button callGraphButton;
    Button signOutButton;

    /* Azure AD Variables */
    private PublicClientApplication sampleApp;
    private AuthenticationResult authResult;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    callGraphButton = (Button) findViewById(R.id.callGraph);
    signOutButton = (Button) findViewById(R.id.clearCache);

    callGraphButton.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
    onCallGraphClicked();
    }
    });

    signOutButton.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
    onSignOutClicked();
    }
    });

    /* Configure your sample app and save state for this activity */
    sampleApp = null;
    if (sampleApp == null) {
    sampleApp = new PublicClientApplication(
    this.getApplicationContext(),
    CLIENT_ID);
    }

    /* Attempt to get a user and acquireTokenSilent
    * If this fails we do an interactive request
    */
    List<User> users = null;

    try {
    users = sampleApp.getUsers();

    if (users != null && users.size() == 1) {
    /* We have 1 user */

    sampleApp.acquireTokenSilentAsync(SCOPES, users.get(0), getAuthSilentCallback());
    } else {
    /* We have no user */

    /* Let's do an interactive request */
    sampleApp.acquireToken(this, SCOPES, getAuthInteractiveCallback());
    }
    } catch (MsalClientException e) {
    Log.d(TAG, "MSAL Exception Generated while getting users: " + e.toString());

    } catch (IndexOutOfBoundsException e) {
    Log.d(TAG, "User at this position does not exist: " + e.toString());
    }

    }

    //
    // App callbacks for MSAL
    // ======================
    // getActivity() - returns activity so we can acquireToken within a callback
    // getAuthSilentCallback() - callback defined to handle acquireTokenSilent() case
    // getAuthInteractiveCallback() - callback defined to handle acquireToken() case
    //

    public Activity getActivity() {
    return this;
    }

    /* Callback method for acquireTokenSilent calls
    * Looks if tokens are in the cache (refreshes if necessary and if we don't forceRefresh)
    * else errors that we need to do an interactive request.
    */
    private AuthenticationCallback getAuthSilentCallback() {
    return new AuthenticationCallback() {
    @Override
    public void onSuccess(AuthenticationResult authenticationResult) {
    /* Successfully got a token, call Graph now */
    Log.d(TAG, "Successfully authenticated");

    /* Store the authResult */
    authResult = authenticationResult;

    /* call graph */
    callGraphAPI();

    /* update the UI to post call Graph state */
    updateSuccessUI();
    }

    @Override
    public void onError(MsalException exception) {
    /* Failed to acquireToken */
    Log.d(TAG, "Authentication failed: " + exception.toString());

    if (exception instanceof MsalClientException) {
    /* Exception inside MSAL, more info inside MsalError.java */
    } else if (exception instanceof MsalServiceException) {
    /* Exception when communicating with the STS, likely config issue */
    } else if (exception instanceof MsalUiRequiredException) {
    /* Tokens expired or no session, retry with interactive */
    }
    }

    @Override
    public void onCancel() {
    /* User canceled the authentication */
    Log.d(TAG, "User cancelled login.");
    }
    };
    }


    /* Callback used for interactive request. If succeeds we use the access
    * token to call the Microsoft Graph. Does not check cache
    */
    private AuthenticationCallback getAuthInteractiveCallback() {
    return new AuthenticationCallback() {
    @Override
    public void onSuccess(AuthenticationResult authenticationResult) {

    /* Successfully got a token, call graph now */
    Log.d(TAG, "Successfully authenticated");
    Log.d(TAG, "ID Token: " + authenticationResult.getIdToken());

    /* Store the auth result */
    authResult = authenticationResult;

    /* call Graph */
    callGraphAPI();

    /* update the UI to post call Graph state */
    updateSuccessUI();
    }

    @Override
    public void onError(MsalException exception) {
    /* Failed to acquireToken */

    Log.d("인증","실패");
    Log.d(TAG, "Authentication failed: " + exception.toString());

    if (exception instanceof MsalClientException) {
    /* Exception inside MSAL, more info inside MsalError.java */
    } else if (exception instanceof MsalServiceException) {
    /* Exception when communicating with the STS, likely config issue */
    }
    }

    @Override
    public void onCancel() {
    /* User canceled the authentication */
    Log.d(TAG, "User cancelled login.");
    }
    };
    }

    /* Set the UI for successful token acquisition data */
    private void updateSuccessUI() {

    Log.d("updateSuccessUI","왔따");
    callGraphButton.setVisibility(View.INVISIBLE);
    signOutButton.setVisibility(View.VISIBLE);
    findViewById(R.id.welcome).setVisibility(View.VISIBLE);
    ((TextView) findViewById(R.id.welcome)).setText("Welcome, " +
    authResult.getUser().getName());
    findViewById(R.id.graphData).setVisibility(View.VISIBLE);
    }

    /* Use MSAL to acquireToken for the end-user
    * Callback will call Graph api w/ access token & update UI
    */
    private void onCallGraphClicked() {
    sampleApp.acquireToken(getActivity(), SCOPES, getAuthInteractiveCallback());
    }

    /* Handles the redirect from the System Browser */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    Log.d("Result","왔따");
    sampleApp.handleInteractiveRequestRedirect(requestCode, resultCode, data);
    Log.d("Result","끝");
    }

    /* Use Volley to make an HTTP request to the /me endpoint from MS Graph using an access token */
    private void callGraphAPI() {
    Log.d(TAG, "Starting volley request to graph");

    /* Make sure we have a token to send to graph */
    if (authResult.getAccessToken() == null) {return;}

    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, 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());

    updateGraphUI(response);
    }
    }, 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 " + authResult.getAccessToken());
    return headers;
    }
    };

    Log.d(TAG, "Adding HTTP GET to Queue, Request: " + request.toString());
    Log.d("리퀘스트 하고있네","ㅇㅇ");
    request.setRetryPolicy(new DefaultRetryPolicy(
    3000,
    DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
    DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    queue.add(request);
    }

    /* Sets the Graph response */
    private void updateGraphUI(JSONObject graphResponse) {
    Log.d("updateGraphUI","왔따");
    TextView graphText = (TextView) findViewById(R.id.graphData);
    graphText.setText(graphResponse.toString());
    }

    /* Clears a user's tokens from the cache.
    * Logically similar to "sign out" but only signs out of this app.
    */
    private void onSignOutClicked() {

    /* Attempt to get a user and remove their cookies from cache */
    List<User> users = null;

    try {
    users = sampleApp.getUsers();

    if (users == null) {
    /* We have no users */

    } else if (users.size() == 1) {
    /* We have 1 user */
    /* Remove from token cache */
    sampleApp.remove(users.get(0));
    updateSignedOutUI();

    }
    else {
    /* We have multiple users */
    for (int i = 0; i < users.size(); i++) {
    sampleApp.remove(users.get(i));
    }
    }

    Toast.makeText(getBaseContext(), "Signed Out!", Toast.LENGTH_SHORT)
    .show();

    } catch (MsalClientException e) {
    Log.d(TAG, "MSAL Exception Generated while getting users: " + e.toString());

    } catch (IndexOutOfBoundsException e) {
    Log.d(TAG, "User at this position does not exist: " + e.toString());
    }
    }

    /* Set the UI for signed-out user */
    private void updateSignedOutUI() {
    callGraphButton.setVisibility(View.VISIBLE);
    signOutButton.setVisibility(View.INVISIBLE);
    findViewById(R.id.welcome).setVisibility(View.INVISIBLE);
    findViewById(R.id.graphData).setVisibility(View.INVISIBLE);
    ((TextView) findViewById(R.id.graphData)).setText("No Data");
    }

    }

    요기서 Token request failed with error 이에러가 뜨네요

    private AuthenticationCallback getAuthInteractiveCallback()

    클래스의

    onError 메소드로 빠져서 토큰 인증이안되고있어요

    어떻게 해결해야하나요?

    혹시 앱 설정에 있는 플랫폼 추가해서 네이티브응용프로그램 에 있는 리디렉션 URL 이 필요한가요?



    2017년 9월 7일 목요일 오전 6:46