Search in sources :

Example 6 with OAuth2Strategy

use of com.microsoft.identity.common.internal.providers.oauth2.OAuth2Strategy in project microsoft-authentication-library-common-for-android by AzureAD.

the class EmbeddedWebViewAuthorizationStrategy method completeAuthorization.

@Override
public void completeAuthorization(int requestCode, int resultCode, Intent data) {
    if (requestCode == AuthenticationConstants.UIRequest.BROWSER_FLOW) {
        if (mOAuth2Strategy != null && mAuthorizationResultFuture != null) {
            // Suppressing unchecked warnings due to method createAuthorizationResult being a member of the raw type AuthorizationResultFactory
            @SuppressWarnings(WarningType.unchecked_warning) final AuthorizationResult result = mOAuth2Strategy.getAuthorizationResultFactory().createAuthorizationResult(resultCode, data, mAuthorizationRequest);
            mAuthorizationResultFuture.setResult(result);
        } else {
            Logger.warn(TAG, "SDK Cancel triggering before request is sent out. " + "Potentially due to an stale activity state, " + "oAuth2Strategy null ? [" + (mOAuth2Strategy == null) + "]" + "mAuthorizationResultFuture ? [" + (mAuthorizationResultFuture == null) + "]");
        }
    } else {
        Logger.warnPII(TAG, "Unknown request code " + requestCode);
    }
}
Also used : AuthorizationResult(com.microsoft.identity.common.internal.providers.oauth2.AuthorizationResult)

Example 7 with OAuth2Strategy

use of com.microsoft.identity.common.internal.providers.oauth2.OAuth2Strategy in project ddd by EricFoxz.

the class Oauth2Controller method renderAuth.

@RequestMapping("/login/jai")
@SneakyThrows
public ModelAndView renderAuth(HttpServletRequest request, HttpServletResponse response) {
    Oauth2Strategy oauth2Strategy = new Oauth2Strategy(applicationOauth2Service, new JapConfig());
    OAuthConfig config = new OAuthConfig();
    config.setPlatform("jai").setState(IdUtil.fastSimpleUUID()).setClientId("xx").setClientSecret("xx").setCallbackUrl("http://sso.jap.com:8443/oauth2/login/jai").setAuthorizationUrl("xx").setTokenUrl("xx").setUserinfoUrl("xx").setScopes(new String[] { "read", "write" }).setResponseType(Oauth2ResponseType.CODE).setGrantType(Oauth2GrantType.AUTHORIZATION_CODE);
    JapResponse japResponse = oauth2Strategy.authenticate(config, new JakartaRequestAdapter(request), new JakartaResponseAdapter(response));
    if (!japResponse.isSuccess()) {
        return new ModelAndView(new RedirectView("/?error=" + URLUtil.encode(japResponse.getMessage())));
    }
    if (japResponse.isRedirectUrl()) {
        return new ModelAndView(new RedirectView((String) japResponse.getData()));
    } else {
        // 登录成功,需要对用户数据进行处理
        // ...
        System.out.println(japResponse.getData());
        return new ModelAndView(new RedirectView("/"));
    }
}
Also used : JapConfig(com.fujieid.jap.core.config.JapConfig) ModelAndView(org.springframework.web.servlet.ModelAndView) RedirectView(org.springframework.web.servlet.view.RedirectView) JakartaRequestAdapter(com.fujieid.jap.http.adapter.jakarta.JakartaRequestAdapter) Oauth2Strategy(com.fujieid.jap.oauth2.Oauth2Strategy) JapResponse(com.fujieid.jap.core.result.JapResponse) OAuthConfig(com.fujieid.jap.oauth2.OAuthConfig) JakartaResponseAdapter(com.fujieid.jap.http.adapter.jakarta.JakartaResponseAdapter) SneakyThrows(lombok.SneakyThrows) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 8 with OAuth2Strategy

use of com.microsoft.identity.common.internal.providers.oauth2.OAuth2Strategy in project microsoft-authentication-library-common-for-android by AzureAD.

the class BaseController method performSilentTokenRequest.

protected TokenResult performSilentTokenRequest(@SuppressWarnings(WarningType.rawtype_warning) @NonNull final OAuth2Strategy strategy, @NonNull final RefreshTokenRecord refreshToken, @NonNull final SilentTokenCommandParameters parameters) throws ClientException, IOException {
    final String methodName = ":performSilentTokenRequest";
    Logger.info(TAG + methodName, "Requesting tokens...");
    HttpWebRequest.throwIfNetworkNotAvailable(parameters.getAndroidApplicationContext(), parameters.isPowerOptCheckEnabled());
    // Check that the authority is known
    final Authority.KnownAuthorityResult authorityResult = Authority.getKnownAuthorityResult(parameters.getAuthority());
    if (!authorityResult.getKnown()) {
        throw authorityResult.getClientException();
    }
    final TokenRequest refreshTokenRequest = strategy.createRefreshTokenRequest(parameters.getAuthenticationScheme());
    refreshTokenRequest.setClientId(parameters.getClientId());
    refreshTokenRequest.setScope(TextUtils.join(" ", parameters.getScopes()));
    refreshTokenRequest.setRefreshToken(refreshToken.getSecret());
    if (refreshTokenRequest instanceof MicrosoftTokenRequest) {
        ((MicrosoftTokenRequest) refreshTokenRequest).setClaims(parameters.getClaimsRequestJson());
        ((MicrosoftTokenRequest) refreshTokenRequest).setClientAppName(parameters.getApplicationName());
        ((MicrosoftTokenRequest) refreshTokenRequest).setClientAppVersion(parameters.getApplicationVersion());
    }
    // NOTE: this should be moved to the strategy; however requires a larger refactor
    if (parameters.getSdkType() == SdkType.ADAL) {
        ((MicrosoftTokenRequest) refreshTokenRequest).setIdTokenVersion("1");
    }
    // Set Broker version to Token Request if it's a brokered request.
    if (parameters instanceof BrokerSilentTokenCommandParameters) {
        ((MicrosoftTokenRequest) refreshTokenRequest).setBrokerVersion(((BrokerSilentTokenCommandParameters) parameters).getBrokerVersion());
    }
    if (!StringExtensions.isNullOrBlank(refreshTokenRequest.getScope())) {
        Logger.infoPII(TAG + methodName, "Scopes: [" + refreshTokenRequest.getScope() + "]");
    }
    return strategyRequestToken(strategy, refreshTokenRequest);
}
Also used : BrokerSilentTokenCommandParameters(com.microsoft.identity.common.internal.commands.parameters.BrokerSilentTokenCommandParameters) AzureActiveDirectoryAuthority(com.microsoft.identity.common.internal.authorities.AzureActiveDirectoryAuthority) Authority(com.microsoft.identity.common.internal.authorities.Authority) MicrosoftTokenRequest(com.microsoft.identity.common.internal.providers.microsoft.MicrosoftTokenRequest) TokenRequest(com.microsoft.identity.common.internal.providers.oauth2.TokenRequest) MicrosoftTokenRequest(com.microsoft.identity.common.internal.providers.microsoft.MicrosoftTokenRequest)

Example 9 with OAuth2Strategy

use of com.microsoft.identity.common.internal.providers.oauth2.OAuth2Strategy in project microsoft-authentication-library-common-for-android by AzureAD.

the class BaseController method performTokenRequest.

protected TokenResult performTokenRequest(@SuppressWarnings(WarningType.rawtype_warning) @NonNull final OAuth2Strategy strategy, @SuppressWarnings(WarningType.rawtype_warning) @NonNull final AuthorizationRequest request, @NonNull final AuthorizationResponse response, @NonNull final InteractiveTokenCommandParameters parameters) throws IOException, ClientException {
    final String methodName = ":performTokenRequest";
    HttpWebRequest.throwIfNetworkNotAvailable(parameters.getAndroidApplicationContext(), parameters.isPowerOptCheckEnabled());
    // Suppressing unchecked warnings due to casting of type AuthorizationRequest to GenericAuthorizationRequest and AuthorizationResponse to GenericAuthorizationResponse in arguments of method call to createTokenRequest
    @SuppressWarnings(WarningType.unchecked_warning) final TokenRequest tokenRequest = strategy.createTokenRequest(request, response, parameters.getAuthenticationScheme());
    if (tokenRequest instanceof MicrosoftTokenRequest) {
        ((MicrosoftTokenRequest) tokenRequest).setClientAppName(parameters.getApplicationName());
        ((MicrosoftTokenRequest) tokenRequest).setClientAppVersion(parameters.getApplicationVersion());
    }
    if (tokenRequest instanceof IHasExtraParameters && parameters instanceof IHasExtraParameters) {
        ((IHasExtraParameters) tokenRequest).setExtraParameters(((IHasExtraParameters) parameters).getExtraParameters());
    }
    logExposedFieldsOfObject(TAG + methodName, tokenRequest);
    // Suppressing unchecked warnings due to casting of type TokenRequest to GenericTokenRequest in argument of method call to requestToken
    @SuppressWarnings(WarningType.unchecked_warning) final TokenResult tokenResult = strategy.requestToken(tokenRequest);
    logResult(TAG, tokenResult);
    return tokenResult;
}
Also used : TokenResult(com.microsoft.identity.common.internal.providers.oauth2.TokenResult) AcquireTokenResult(com.microsoft.identity.common.internal.result.AcquireTokenResult) MicrosoftTokenRequest(com.microsoft.identity.common.internal.providers.microsoft.MicrosoftTokenRequest) TokenRequest(com.microsoft.identity.common.internal.providers.oauth2.TokenRequest) MicrosoftTokenRequest(com.microsoft.identity.common.internal.providers.microsoft.MicrosoftTokenRequest) IHasExtraParameters(com.microsoft.identity.common.internal.commands.parameters.IHasExtraParameters)

Example 10 with OAuth2Strategy

use of com.microsoft.identity.common.internal.providers.oauth2.OAuth2Strategy in project microsoft-authentication-library-common-for-android by AzureAD.

the class LocalMSALController method acquireToken.

@Override
public AcquireTokenResult acquireToken(@NonNull final InteractiveTokenCommandParameters parameters) throws ExecutionException, InterruptedException, ClientException, IOException, ArgumentException {
    final String methodName = ":acquireToken";
    Logger.verbose(TAG + methodName, "Acquiring token...");
    Telemetry.emit(new ApiStartEvent().putProperties(parameters).putApiId(TelemetryEventStrings.Api.LOCAL_ACQUIRE_TOKEN_INTERACTIVE));
    final AcquireTokenResult acquireTokenResult = new AcquireTokenResult();
    // 00) Validate MSAL Parameters
    parameters.validate();
    // Add default scopes
    final Set<String> mergedScopes = addDefaultScopes(parameters);
    final InteractiveTokenCommandParameters parametersWithScopes = parameters.toBuilder().scopes(mergedScopes).build();
    logParameters(TAG, parametersWithScopes);
    // 0) Get known authority result
    throwIfNetworkNotAvailable(parametersWithScopes.getAndroidApplicationContext(), parametersWithScopes.isPowerOptCheckEnabled());
    Authority.KnownAuthorityResult authorityResult = Authority.getKnownAuthorityResult(parametersWithScopes.getAuthority());
    // 0.1 If not known throw resulting exception
    if (!authorityResult.getKnown()) {
        Telemetry.emit(new ApiEndEvent().putException(authorityResult.getClientException()).putApiId(TelemetryEventStrings.Api.LOCAL_ACQUIRE_TOKEN_INTERACTIVE));
        throw authorityResult.getClientException();
    }
    // Build up params for Strategy construction
    final OAuth2StrategyParameters strategyParameters = new OAuth2StrategyParameters();
    strategyParameters.setContext(parametersWithScopes.getAndroidApplicationContext());
    // 1) Get oAuth2Strategy for Authority Type
    @SuppressWarnings(WarningType.rawtype_warning) final OAuth2Strategy oAuth2Strategy = parametersWithScopes.getAuthority().createOAuth2Strategy(strategyParameters);
    // 2) Request authorization interactively
    @SuppressWarnings(WarningType.rawtype_warning) final AuthorizationResult result = performAuthorizationRequest(oAuth2Strategy, parametersWithScopes.getAndroidApplicationContext(), parametersWithScopes);
    acquireTokenResult.setAuthorizationResult(result);
    logResult(TAG, result);
    if (result.getAuthorizationStatus().equals(AuthorizationStatus.SUCCESS)) {
        // 3) Exchange authorization code for token
        final TokenResult tokenResult = performTokenRequest(oAuth2Strategy, mAuthorizationRequest, result.getAuthorizationResponse(), parametersWithScopes);
        acquireTokenResult.setTokenResult(tokenResult);
        if (tokenResult != null && tokenResult.getSuccess()) {
            // 4) Save tokens in token cache
            final List<ICacheRecord> records = saveTokens(oAuth2Strategy, mAuthorizationRequest, tokenResult.getTokenResponse(), parametersWithScopes.getOAuth2TokenCache());
            // The first element in the returned list is the item we *just* saved, the rest of
            // the elements are necessary to construct the full IAccount + TenantProfile
            final ICacheRecord newestRecord = records.get(0);
            acquireTokenResult.setLocalAuthenticationResult(new LocalAuthenticationResult(finalizeCacheRecordForResult(newestRecord, parametersWithScopes.getAuthenticationScheme()), records, SdkType.MSAL, false));
        }
    }
    Telemetry.emit(new ApiEndEvent().putResult(acquireTokenResult).putApiId(TelemetryEventStrings.Api.LOCAL_ACQUIRE_TOKEN_INTERACTIVE));
    return acquireTokenResult;
}
Also used : AcquireTokenResult(com.microsoft.identity.common.internal.result.AcquireTokenResult) ICacheRecord(com.microsoft.identity.common.internal.cache.ICacheRecord) Authority(com.microsoft.identity.common.internal.authorities.Authority) TokenResult(com.microsoft.identity.common.internal.providers.oauth2.TokenResult) AcquireTokenResult(com.microsoft.identity.common.internal.result.AcquireTokenResult) OAuth2StrategyParameters(com.microsoft.identity.common.internal.providers.oauth2.OAuth2StrategyParameters) InteractiveTokenCommandParameters(com.microsoft.identity.common.internal.commands.parameters.InteractiveTokenCommandParameters) OAuth2Strategy(com.microsoft.identity.common.internal.providers.oauth2.OAuth2Strategy) AuthorizationResult(com.microsoft.identity.common.internal.providers.oauth2.AuthorizationResult) ApiEndEvent(com.microsoft.identity.common.internal.telemetry.events.ApiEndEvent) ApiStartEvent(com.microsoft.identity.common.internal.telemetry.events.ApiStartEvent) LocalAuthenticationResult(com.microsoft.identity.common.internal.result.LocalAuthenticationResult)

Aggregations

OAuth2StrategyParameters (com.microsoft.identity.common.internal.providers.oauth2.OAuth2StrategyParameters)7 TokenResult (com.microsoft.identity.common.internal.providers.oauth2.TokenResult)7 ClientException (com.microsoft.identity.common.exception.ClientException)6 OAuth2Strategy (com.microsoft.identity.common.internal.providers.oauth2.OAuth2Strategy)6 AuthorizationResult (com.microsoft.identity.common.internal.providers.oauth2.AuthorizationResult)5 AcquireTokenResult (com.microsoft.identity.common.internal.result.AcquireTokenResult)5 ICacheRecord (com.microsoft.identity.common.internal.cache.ICacheRecord)4 TokenRequest (com.microsoft.identity.common.internal.providers.oauth2.TokenRequest)4 LocalAuthenticationResult (com.microsoft.identity.common.internal.result.LocalAuthenticationResult)4 ApiEndEvent (com.microsoft.identity.common.internal.telemetry.events.ApiEndEvent)4 ApiStartEvent (com.microsoft.identity.common.internal.telemetry.events.ApiStartEvent)4 Authority (com.microsoft.identity.common.internal.authorities.Authority)3 OAuth2TokenCache (com.microsoft.identity.common.internal.providers.oauth2.OAuth2TokenCache)3 ArgumentException (com.microsoft.identity.common.exception.ArgumentException)2 ServiceException (com.microsoft.identity.common.exception.ServiceException)2 AzureActiveDirectoryAuthority (com.microsoft.identity.common.internal.authorities.AzureActiveDirectoryAuthority)2 CertificateCredential (com.microsoft.identity.common.internal.providers.keys.CertificateCredential)2 ClientCertificateMetadata (com.microsoft.identity.common.internal.providers.keys.ClientCertificateMetadata)2 KeyStoreConfiguration (com.microsoft.identity.common.internal.providers.keys.KeyStoreConfiguration)2 MicrosoftClientAssertion (com.microsoft.identity.common.internal.providers.microsoft.MicrosoftClientAssertion)2