package com.microsoft.aad.adal; import android.net.Uri; import android.os.Build; import android.util.Base64; import com.microsoft.aad.adal.AuthenticationConstants; import com.umeng.analytics.pro.ak; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URL; import java.net.URLEncoder; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.UUID; import org.json.JSONException; import org.json.JSONObject; /* access modifiers changed from: package-private */ public class Oauth2 { private static final String DEFAULT_AUTHORIZE_ENDPOINT = "/oauth2/authorize"; private static final String DEFAULT_TOKEN_ENDPOINT = "/oauth2/token"; private static final String JSON_PARSING_ERROR = "It failed to parse response as json"; private static final String TAG = "Oauth"; private IJWSBuilder mJWSBuilder = new JWSBuilder(); private AuthenticationRequest mRequest; private IWebRequestHandler mWebRequestHandler; Oauth2(AuthenticationRequest authenticationRequest) { this.mRequest = authenticationRequest; this.mWebRequestHandler = null; this.mJWSBuilder = null; } public Oauth2(AuthenticationRequest authenticationRequest, IWebRequestHandler iWebRequestHandler) { this.mRequest = authenticationRequest; this.mWebRequestHandler = iWebRequestHandler; this.mJWSBuilder = null; } public Oauth2(AuthenticationRequest authenticationRequest, IWebRequestHandler iWebRequestHandler, IJWSBuilder iJWSBuilder) { this.mRequest = authenticationRequest; this.mWebRequestHandler = iWebRequestHandler; this.mJWSBuilder = iJWSBuilder; } public static String decodeProtocolState(String str) { if (!StringExtensions.IsNullOrBlank(str)) { return new String(Base64.decode(str, 9)); } return null; } private static void extractJsonObjects(HashMap<String, String> hashMap, String str) throws JSONException { JSONObject jSONObject = new JSONObject(str); Iterator<String> keys = jSONObject.keys(); while (keys.hasNext()) { String next = keys.next(); hashMap.put(next, jSONObject.getString(next)); } } private HashMap<String, String> getRequestHeaders() { HashMap<String, String> hashMap = new HashMap<>(); hashMap.put("Accept", "application/json"); return hashMap; } private static IdToken parseIdToken(String str) { try { int indexOf = str.indexOf("."); int i10 = indexOf + 1; int indexOf2 = str.indexOf(".", i10); if (str.indexOf(".", indexOf2 + 1) == -1 && indexOf > 0 && indexOf2 > 0) { String str2 = new String(Base64.decode(str.substring(i10, indexOf2), 8), "UTF-8"); HashMap hashMap = new HashMap(); extractJsonObjects(hashMap, str2); if (!hashMap.isEmpty()) { IdToken idToken = new IdToken(); idToken.mSubject = (String) hashMap.get("sub"); idToken.mTenantId = (String) hashMap.get("tid"); idToken.mUpn = (String) hashMap.get("upn"); idToken.mEmail = (String) hashMap.get("email"); idToken.mGivenName = (String) hashMap.get("given_name"); idToken.mFamilyName = (String) hashMap.get("family_name"); idToken.mIdentityProvider = (String) hashMap.get("idp"); idToken.mObjectId = (String) hashMap.get("oid"); String str3 = (String) hashMap.get("pwd_exp"); if (!StringExtensions.IsNullOrBlank(str3)) { idToken.mPasswordExpiration = Long.parseLong(str3); } idToken.mPasswordChangeUrl = (String) hashMap.get("pwd_url"); Logger.v(TAG, "IdToken is extracted from token response"); return idToken; } } } catch (UnsupportedEncodingException | JSONException e10) { Logger.e(TAG, "Error in parsing user id token", null, ADALError.IDTOKEN_PARSING_FAILURE, e10); } return null; } private AuthenticationResult parseJsonResponse(byte[] bArr) throws JSONException { HashMap hashMap = new HashMap(); extractJsonObjects(hashMap, new String(bArr)); return processUIResponseParams(hashMap); } private AuthenticationResult postMessage(String str, HashMap<String, String> hashMap) throws IOException, AuthenticationException { AuthenticationResult authenticationResult; String str2; URL url = StringExtensions.getUrl(getTokenEndpoint()); if (url != null) { try { this.mWebRequestHandler.setRequestCorrelationId(this.mRequest.getCorrelationId()); ClientMetrics clientMetrics = ClientMetrics.INSTANCE; clientMetrics.beginClientMetricsRecord(url, this.mRequest.getCorrelationId(), hashMap); HttpWebResponse sendPost = this.mWebRequestHandler.sendPost(url, hashMap, str.getBytes("UTF_8"), "application/x-www-form-urlencoded"); boolean z10 = false; if (sendPost.getStatusCode() == 401) { if (sendPost.getResponseHeaders() == null || !sendPost.getResponseHeaders().containsKey("WWW-Authenticate")) { Logger.v(TAG, "401 http status code is returned without authorization header"); } else { String str3 = sendPost.getResponseHeaders().get("WWW-Authenticate").get(0); Logger.v(TAG, "Device certificate challenge request:" + str3); if (StringExtensions.IsNullOrBlank(str3)) { throw new AuthenticationException(ADALError.DEVICE_CERTIFICATE_REQUEST_INVALID, "Challenge header is empty"); } else if (StringExtensions.hasPrefixInHeader(str3, AuthenticationConstants.Broker.CHALLENGE_RESPONSE_TYPE)) { Logger.v(TAG, "Challenge is related to device certificate"); ChallengeResponseBuilder challengeResponseBuilder = new ChallengeResponseBuilder(this.mJWSBuilder); Logger.v(TAG, "Processing device challenge"); hashMap.put("Authorization", challengeResponseBuilder.getChallengeResponseFromHeader(str3, url.toString()).mAuthorizationHeaderValue); Logger.v(TAG, "Sending request with challenge response"); sendPost = this.mWebRequestHandler.sendPost(url, hashMap, str.getBytes("UTF_8"), "application/x-www-form-urlencoded"); } } } byte[] body = sendPost.getBody(); if (body == null || body.length == 0) { z10 = true; } if (!z10) { Logger.v(TAG, "Token request does not have exception"); authenticationResult = processTokenResponse(sendPost); clientMetrics.setLastError(null); } else { authenticationResult = null; } if (authenticationResult == null) { if (z10) { str2 = "Status code:" + sendPost.getStatusCode(); } else { str2 = new String(body); } ADALError aDALError = ADALError.SERVER_ERROR; Logger.e(TAG, "Server error message", str2, aDALError); if (sendPost.getResponseException() != null) { throw sendPost.getResponseException(); } throw new AuthenticationException(aDALError, str2); } clientMetrics.setLastErrorCodes(authenticationResult.getErrorCodes()); clientMetrics.endClientMetricsRecord(ClientMetricsEndpointType.TOKEN, this.mRequest.getCorrelationId()); return authenticationResult; } catch (UnsupportedEncodingException e10) { ClientMetrics.INSTANCE.setLastError(null); Logger.e(TAG, e10.getMessage(), "", ADALError.ENCODING_IS_NOT_SUPPORTED, e10); throw e10; } catch (IOException e11) { ClientMetrics.INSTANCE.setLastError(null); Logger.e(TAG, e11.getMessage(), "", ADALError.SERVER_ERROR, e11); throw e11; } catch (Throwable th) { ClientMetrics.INSTANCE.endClientMetricsRecord(ClientMetricsEndpointType.TOKEN, this.mRequest.getCorrelationId()); throw th; } } else { throw new AuthenticationException(ADALError.DEVELOPER_AUTHORITY_IS_NOT_VALID_URL); } } private AuthenticationResult processTokenResponse(HttpWebResponse httpWebResponse) { AuthenticationResult authenticationResult; List<String> list; String str = (httpWebResponse.getResponseHeaders() == null || !httpWebResponse.getResponseHeaders().containsKey(AuthenticationConstants.AAD.CLIENT_REQUEST_ID) || (list = httpWebResponse.getResponseHeaders().get(AuthenticationConstants.AAD.CLIENT_REQUEST_ID)) == null || list.size() <= 0) ? null : list.get(0); int statusCode = httpWebResponse.getStatusCode(); if (statusCode == 200 || statusCode == 400 || statusCode == 401) { try { authenticationResult = parseJsonResponse(httpWebResponse.getBody()); } catch (JSONException e10) { Logger.e(TAG, e10.getMessage(), "", ADALError.SERVER_INVALID_JSON_RESPONSE, e10); authenticationResult = new AuthenticationResult(JSON_PARSING_ERROR, e10.getMessage(), null); } } else { String str2 = new String(httpWebResponse.getBody()); Logger.e(TAG, "Server response", str2, ADALError.SERVER_ERROR); authenticationResult = new AuthenticationResult(String.valueOf(httpWebResponse.getStatusCode()), str2, null); } if (str != null && !str.isEmpty()) { try { if (!UUID.fromString(str).equals(this.mRequest.getCorrelationId())) { Logger.w(TAG, "CorrelationId is not matching", "", ADALError.CORRELATION_ID_NOT_MATCHING_REQUEST_RESPONSE); } Logger.v(TAG, "Response correlationId:" + str); } catch (IllegalArgumentException e11) { Logger.e(TAG, "Wrong format of the correlation ID:" + str, "", ADALError.CORRELATION_ID_FORMAT, e11); } } return authenticationResult; } public static AuthenticationResult processUIResponseParams(HashMap<String, String> hashMap) { String str; String str2; UserInfo userInfo; AuthenticationResult authenticationResult; UserInfo userInfo2; String str3; String str4 = null; if (hashMap.containsKey("error")) { String str5 = hashMap.get(AuthenticationConstants.AAD.CORRELATION_ID); if (!StringExtensions.IsNullOrBlank(str5)) { try { Logger.setCorrelationId(UUID.fromString(str5)); } catch (IllegalArgumentException unused) { Logger.e(TAG, "CorrelationId is malformed: " + str5, "", ADALError.CORRELATION_ID_FORMAT); } } Logger.v(TAG, "OAuth2 error:" + hashMap.get("error") + " Description:" + hashMap.get("error_description")); authenticationResult = new AuthenticationResult(hashMap.get("error"), hashMap.get("error_description"), hashMap.get(AuthenticationConstants.OAuth2.ERROR_CODES)); } else if (hashMap.containsKey("code")) { return new AuthenticationResult(hashMap.get("code")); } else { if (!hashMap.containsKey("access_token")) { return null; } String str6 = hashMap.get("expires_in"); GregorianCalendar gregorianCalendar = new GregorianCalendar(); gregorianCalendar.add(13, (str6 == null || str6.isEmpty()) ? AuthenticationConstants.DEFAULT_EXPIRATION_TIME_SEC : Integer.parseInt(str6)); boolean containsKey = hashMap.containsKey(AuthenticationConstants.AAD.RESOURCE); if (hashMap.containsKey("id_token")) { String str7 = hashMap.get("id_token"); if (!StringExtensions.IsNullOrBlank(str7)) { IdToken parseIdToken = parseIdToken(str7); if (parseIdToken != null) { str3 = parseIdToken.mTenantId; userInfo2 = new UserInfo(parseIdToken); } else { str3 = null; userInfo2 = null; } str = str7; str2 = str3; userInfo = userInfo2; } else { Logger.v(TAG, "IdToken is not provided"); str = str7; userInfo = null; str2 = null; } } else { userInfo = null; str2 = null; str = null; } if (hashMap.containsKey("foci")) { str4 = hashMap.get("foci"); } authenticationResult = new AuthenticationResult(hashMap.get("access_token"), hashMap.get("refresh_token"), gregorianCalendar.getTime(), containsKey, userInfo, str2, str); authenticationResult.setFamilyClientId(str4); } return authenticationResult; } public String buildRefreshTokenRequestMessage(String str) throws UnsupportedEncodingException { String format = String.format("%s=%s&%s=%s&%s=%s", "grant_type", StringExtensions.URLFormEncode("refresh_token"), "refresh_token", StringExtensions.URLFormEncode(str), "client_id", StringExtensions.URLFormEncode(this.mRequest.getClientId())); if (StringExtensions.IsNullOrBlank(this.mRequest.getResource())) { return format; } return String.format("%s&%s=%s", format, AuthenticationConstants.AAD.RESOURCE, StringExtensions.URLFormEncode(this.mRequest.getResource())); } public String buildTokenRequestMessage(String str) throws UnsupportedEncodingException { return String.format("%s=%s&%s=%s&%s=%s&%s=%s", "grant_type", StringExtensions.URLFormEncode(AuthenticationConstants.OAuth2.AUTHORIZATION_CODE), "code", StringExtensions.URLFormEncode(str), "client_id", StringExtensions.URLFormEncode(this.mRequest.getClientId()), "redirect_uri", StringExtensions.URLFormEncode(this.mRequest.getRedirectUri())); } public String encodeProtocolState() { return Base64.encodeToString(String.format("a=%s&r=%s", this.mRequest.getAuthority(), this.mRequest.getResource()).getBytes(), 9); } public String getAuthorizationEndpoint() { return this.mRequest.getAuthority() + DEFAULT_AUTHORIZE_ENDPOINT; } public String getAuthorizationEndpointQueryParameters() throws UnsupportedEncodingException { String format = String.format("response_type=%s&client_id=%s&resource=%s&redirect_uri=%s&state=%s", "code", URLEncoder.encode(this.mRequest.getClientId(), "UTF_8"), URLEncoder.encode(this.mRequest.getResource(), "UTF_8"), URLEncoder.encode(this.mRequest.getRedirectUri(), "UTF_8"), encodeProtocolState()); if (this.mRequest.getLoginHint() != null && !this.mRequest.getLoginHint().isEmpty()) { format = String.format("%s&%s=%s", format, "login_hint", URLEncoder.encode(this.mRequest.getLoginHint(), "UTF_8")); } String format2 = String.format("%s&%s=%s", String.format("%s&%s=%s", String.format("%s&%s=%s", String.format("%s&%s=%s", format, AuthenticationConstants.AAD.ADAL_ID_PLATFORM, "Android"), AuthenticationConstants.AAD.ADAL_ID_VERSION, URLEncoder.encode(AuthenticationContext.getVersionName(), "UTF_8")), AuthenticationConstants.AAD.ADAL_ID_OS_VER, URLEncoder.encode("" + Build.VERSION.SDK_INT, "UTF_8")), AuthenticationConstants.AAD.ADAL_ID_DM, URLEncoder.encode("" + Build.MODEL, "UTF_8")); if (this.mRequest.getCorrelationId() != null) { format2 = String.format("%s&%s=%s", format2, AuthenticationConstants.AAD.CLIENT_REQUEST_ID, URLEncoder.encode(this.mRequest.getCorrelationId().toString(), "UTF_8")); } if (this.mRequest.getPrompt() == PromptBehavior.Always) { format2 = String.format("%s&%s=%s", format2, AuthenticationConstants.AAD.QUERY_PROMPT, URLEncoder.encode("login", "UTF_8")); } else if (this.mRequest.getPrompt() == PromptBehavior.REFRESH_SESSION) { format2 = String.format("%s&%s=%s", format2, AuthenticationConstants.AAD.QUERY_PROMPT, URLEncoder.encode(AuthenticationConstants.AAD.QUERY_PROMPT_REFRESH_SESSION_VALUE, "UTF_8")); } if (StringExtensions.IsNullOrBlank(this.mRequest.getExtraQueryParamsAuthentication())) { return format2; } String extraQueryParamsAuthentication = this.mRequest.getExtraQueryParamsAuthentication(); if (!extraQueryParamsAuthentication.startsWith("&")) { extraQueryParamsAuthentication = "&" + extraQueryParamsAuthentication; } return format2 + extraQueryParamsAuthentication; } public String getCodeRequestUrl() throws UnsupportedEncodingException { return String.format("%s?%s", getAuthorizationEndpoint(), getAuthorizationEndpointQueryParameters()); } public AuthenticationResult getToken(String str) throws IOException, AuthenticationServerProtocolException, AuthenticationException { if (!StringExtensions.IsNullOrBlank(str)) { HashMap<String, String> urlParameters = StringExtensions.getUrlParameters(str); String decodeProtocolState = decodeProtocolState(urlParameters.get("state")); if (!StringExtensions.IsNullOrBlank(decodeProtocolState)) { Uri parse = Uri.parse("http://state/path?" + decodeProtocolState); String queryParameter = parse.getQueryParameter(ak.av); String queryParameter2 = parse.getQueryParameter("r"); if (StringExtensions.IsNullOrBlank(queryParameter) || StringExtensions.IsNullOrBlank(queryParameter2) || !queryParameter2.equalsIgnoreCase(this.mRequest.getResource())) { throw new AuthenticationException(ADALError.AUTH_FAILED_BAD_STATE); } AuthenticationResult processUIResponseParams = processUIResponseParams(urlParameters); return (processUIResponseParams == null || processUIResponseParams.getCode() == null || processUIResponseParams.getCode().isEmpty()) ? processUIResponseParams : getTokenForCode(processUIResponseParams.getCode()); } throw new AuthenticationException(ADALError.AUTH_FAILED_NO_STATE); } throw new IllegalArgumentException("authorizationUrl"); } public String getTokenEndpoint() { return this.mRequest.getAuthority() + DEFAULT_TOKEN_ENDPOINT; } public AuthenticationResult getTokenForCode(String str) throws IOException, AuthenticationException { if (this.mWebRequestHandler != null) { try { return postMessage(buildTokenRequestMessage(str), getRequestHeaders()); } catch (UnsupportedEncodingException e10) { Logger.e(TAG, e10.getMessage(), "", ADALError.ENCODING_IS_NOT_SUPPORTED, e10); return null; } } else { throw new IllegalArgumentException("webRequestHandler"); } } public AuthenticationResult refreshToken(String str) throws IOException, AuthenticationException { if (this.mWebRequestHandler != null) { try { String buildRefreshTokenRequestMessage = buildRefreshTokenRequestMessage(str); HashMap<String, String> requestHeaders = getRequestHeaders(); requestHeaders.put(AuthenticationConstants.Broker.CHALLENGE_TLS_INCAPABLE, "1.0"); return postMessage(buildRefreshTokenRequestMessage, requestHeaders); } catch (UnsupportedEncodingException e10) { Logger.e(TAG, e10.getMessage(), "", ADALError.ENCODING_IS_NOT_SUPPORTED, e10); return null; } } else { Logger.v(TAG, "Web request is not set correctly"); throw new IllegalArgumentException("webRequestHandler is null."); } } }