Search in sources :

Example 1 with CodeExchangeException

use of uk.ac.cam.cl.dtg.segue.auth.exceptions.CodeExchangeException in project isaac-api by isaacphysics.

the class AuthenticationFacade method authenticationCallback.

/**
 * This is the callback url that auth providers should use to send us information about users.
 *
 * @param request
 *            - http request from user
 * @param response
 *            to tell the browser to store the session in our own segue cookie if successful.
 * @param signinProvider
 *            - requested signing provider string
 * @return Redirect response to send the user to the home page.
 */
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/{provider}/callback")
@ApiOperation(value = "SSO callback URL for a given provider.")
public final Response authenticationCallback(@Context final HttpServletRequest request, @Context final HttpServletResponse response, @PathParam("provider") final String signinProvider) {
    try {
        // TODO - review if rememberMe should default to true for SSO logins:
        RegisteredUserDTO userToReturn = userManager.authenticateCallback(request, response, signinProvider, true);
        this.getLogManager().logEvent(userToReturn, request, SegueServerLogType.LOG_IN, Maps.newHashMap());
        return Response.ok(userToReturn).build();
    } catch (IOException e) {
        SegueErrorResponse error = new SegueErrorResponse(Status.INTERNAL_SERVER_ERROR, "Exception while trying to authenticate a user" + " - during callback step.", e);
        log.error(error.getErrorMessage(), e);
        return error.toResponse();
    } catch (NoUserException e) {
        SegueErrorResponse error = new SegueErrorResponse(Status.UNAUTHORIZED, "Unable to locate user information.");
        log.error("No userID exception received. Unable to locate user.", e);
        return error.toResponse();
    } catch (AuthenticationCodeException | CrossSiteRequestForgeryException | AuthenticatorSecurityException | CodeExchangeException e) {
        SegueErrorResponse error = new SegueErrorResponse(Status.UNAUTHORIZED, e.getMessage());
        log.info("Error detected during authentication: " + e.getClass().toString());
        return error.toResponse();
    } catch (DuplicateAccountException e) {
        log.debug("Duplicate user already exists in the database.", e);
        return new SegueErrorResponse(Status.FORBIDDEN, e.getMessage()).toResponse();
    } catch (AccountAlreadyLinkedException e) {
        log.error("Internal Database error during authentication", e);
        return new SegueErrorResponse(Status.BAD_REQUEST, "The account you are trying to link is already attached to a user of this system.").toResponse();
    } catch (SegueDatabaseException e) {
        log.error("Internal Database error during authentication", e);
        return new SegueErrorResponse(Status.INTERNAL_SERVER_ERROR, "Internal database error during authentication.").toResponse();
    } catch (AuthenticationProviderMappingException e) {
        return new SegueErrorResponse(Status.BAD_REQUEST, "Unable to map to a known authenticator. The provider: " + signinProvider + " is unknown").toResponse();
    }
}
Also used : AuthenticationCodeException(uk.ac.cam.cl.dtg.segue.auth.exceptions.AuthenticationCodeException) NoUserException(uk.ac.cam.cl.dtg.segue.auth.exceptions.NoUserException) SegueDatabaseException(uk.ac.cam.cl.dtg.segue.dao.SegueDatabaseException) CrossSiteRequestForgeryException(uk.ac.cam.cl.dtg.segue.auth.exceptions.CrossSiteRequestForgeryException) IOException(java.io.IOException) DuplicateAccountException(uk.ac.cam.cl.dtg.segue.auth.exceptions.DuplicateAccountException) AccountAlreadyLinkedException(uk.ac.cam.cl.dtg.segue.auth.exceptions.AccountAlreadyLinkedException) SegueErrorResponse(uk.ac.cam.cl.dtg.segue.dto.SegueErrorResponse) RegisteredUserDTO(uk.ac.cam.cl.dtg.segue.dto.users.RegisteredUserDTO) AuthenticatorSecurityException(uk.ac.cam.cl.dtg.segue.auth.exceptions.AuthenticatorSecurityException) CodeExchangeException(uk.ac.cam.cl.dtg.segue.auth.exceptions.CodeExchangeException) AuthenticationProviderMappingException(uk.ac.cam.cl.dtg.segue.auth.exceptions.AuthenticationProviderMappingException) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation)

Example 2 with CodeExchangeException

use of uk.ac.cam.cl.dtg.segue.auth.exceptions.CodeExchangeException in project isaac-api by isaacphysics.

the class TwitterAuthenticator method exchangeCode.

@Override
public String exchangeCode(final String authorizationCode) throws CodeExchangeException {
    try {
        AccessToken accessToken = twitter.getOAuthAccessToken(authorizationCode);
        TokenResponse tokenResponse = new TokenResponse();
        tokenResponse.setAccessToken(accessToken.getToken());
        tokenResponse.setRefreshToken(accessToken.getTokenSecret());
        tokenResponse.setExpiresInSeconds(Long.MAX_VALUE);
        Builder builder = new AuthorizationCodeFlow.Builder(BearerToken.authorizationHeaderAccessMethod(), httpTransport, jsonFactory, new GenericUrl(TOKEN_EXCHANGE_URL), new ClientParametersAuthentication(clientId, clientSecret), clientId, AUTH_URL);
        AuthorizationCodeFlow flow = builder.setDataStoreFactory(MemoryDataStoreFactory.getDefaultInstance()).build();
        Credential credential = flow.createAndStoreCredential(tokenResponse, authorizationCode);
        String internalReferenceToken = UUID.randomUUID().toString();
        credentialStore.put(internalReferenceToken, credential);
        flow.getCredentialDataStore().clear();
        return internalReferenceToken;
    } catch (IOException | TwitterException | IllegalStateException e) {
        log.error("An error occurred during code exchange: " + e);
        throw new CodeExchangeException();
    }
}
Also used : Credential(com.google.api.client.auth.oauth2.Credential) ConfigurationBuilder(twitter4j.conf.ConfigurationBuilder) Builder(com.google.api.client.auth.oauth2.AuthorizationCodeFlow.Builder) GenericUrl(com.google.api.client.http.GenericUrl) IOException(java.io.IOException) AuthorizationCodeFlow(com.google.api.client.auth.oauth2.AuthorizationCodeFlow) ClientParametersAuthentication(com.google.api.client.auth.oauth2.ClientParametersAuthentication) TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) AccessToken(twitter4j.auth.AccessToken) CodeExchangeException(uk.ac.cam.cl.dtg.segue.auth.exceptions.CodeExchangeException) TwitterException(twitter4j.TwitterException)

Example 3 with CodeExchangeException

use of uk.ac.cam.cl.dtg.segue.auth.exceptions.CodeExchangeException in project isaac-api by isaacphysics.

the class GoogleAuthenticator method exchangeCode.

@Override
public synchronized String exchangeCode(final String authorizationCode) throws CodeExchangeException {
    try {
        GoogleTokenResponse response = new GoogleAuthorizationCodeTokenRequest(httpTransport, jsonFactory, clientSecrets.getDetails().getClientId(), clientSecrets.getDetails().getClientSecret(), authorizationCode, callbackUri).execute();
        // I don't really want to use the flow storage but it seems to be
        // easier to get credentials this way.
        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jsonFactory, clientSecrets.getDetails().getClientId(), clientSecrets.getDetails().getClientSecret(), requestedScopes).setDataStoreFactory(MemoryDataStoreFactory.getDefaultInstance()).build();
        Credential credential = flow.createAndStoreCredential(response, authorizationCode);
        String internalReferenceToken = UUID.randomUUID().toString();
        credentialStore.put(internalReferenceToken, credential);
        flow.getCredentialDataStore().clear();
        return internalReferenceToken;
    } catch (IOException e) {
        log.error("An error occurred during code exchange: " + e);
        throw new CodeExchangeException();
    }
}
Also used : Credential(com.google.api.client.auth.oauth2.Credential) GoogleAuthorizationCodeTokenRequest(com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeTokenRequest) CacheBuilder(com.google.common.cache.CacheBuilder) GoogleTokenResponse(com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse) GoogleAuthorizationCodeFlow(com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow) CodeExchangeException(uk.ac.cam.cl.dtg.segue.auth.exceptions.CodeExchangeException) IOException(java.io.IOException)

Example 4 with CodeExchangeException

use of uk.ac.cam.cl.dtg.segue.auth.exceptions.CodeExchangeException in project isaac-api by isaacphysics.

the class FacebookAuthenticator method exchangeCode.

@Override
public String exchangeCode(final String authorizationCode) throws CodeExchangeException {
    try {
        AuthorizationCodeTokenRequest request = new AuthorizationCodeTokenRequest(httpTransport, jsonFactory, new GenericUrl(TOKEN_EXCHANGE_URL), authorizationCode);
        request.setClientAuthentication(new ClientParametersAuthentication(clientId, clientSecret));
        request.setRedirectUri(callbackUri);
        TokenResponse response = request.execute();
        String accessToken;
        Long expires;
        if (response.get("error") != null) {
            throw new CodeExchangeException("Server responded with the following error" + response.get("error") + " given the request" + request.toString());
        }
        if (response.getAccessToken() != null && response.getExpiresInSeconds() != null) {
            accessToken = response.getAccessToken();
            expires = response.getExpiresInSeconds();
        } else {
            throw new IOException("access_token or expires_in values were not found");
        }
        TokenResponse tokenResponse = new TokenResponse();
        tokenResponse.setAccessToken(accessToken);
        tokenResponse.setExpiresInSeconds(expires);
        // I don't really want to use the flow storage but it seems to be
        // easier to get credentials this way.
        Builder builder = new AuthorizationCodeFlow.Builder(BearerToken.authorizationHeaderAccessMethod(), httpTransport, jsonFactory, new GenericUrl(TOKEN_EXCHANGE_URL), new ClientParametersAuthentication(clientId, clientSecret), clientId, AUTH_URL);
        builder.setScopes(requestedScopes);
        AuthorizationCodeFlow flow = builder.setDataStoreFactory(MemoryDataStoreFactory.getDefaultInstance()).build();
        Credential credential = flow.createAndStoreCredential(tokenResponse, authorizationCode);
        String internalReferenceToken = UUID.randomUUID().toString();
        credentialStore.put(internalReferenceToken, credential);
        flow.getCredentialDataStore().clear();
        return internalReferenceToken;
    } catch (IOException e) {
        String message = "An error occurred during code exchange";
        throw new CodeExchangeException(message, e);
    }
}
Also used : ClientParametersAuthentication(com.google.api.client.auth.oauth2.ClientParametersAuthentication) Credential(com.google.api.client.auth.oauth2.Credential) TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) AuthorizationCodeTokenRequest(com.google.api.client.auth.oauth2.AuthorizationCodeTokenRequest) Builder(com.google.api.client.auth.oauth2.AuthorizationCodeFlow.Builder) CodeExchangeException(uk.ac.cam.cl.dtg.segue.auth.exceptions.CodeExchangeException) GenericUrl(com.google.api.client.http.GenericUrl) IOException(java.io.IOException) AuthorizationCodeFlow(com.google.api.client.auth.oauth2.AuthorizationCodeFlow)

Aggregations

IOException (java.io.IOException)4 CodeExchangeException (uk.ac.cam.cl.dtg.segue.auth.exceptions.CodeExchangeException)4 Credential (com.google.api.client.auth.oauth2.Credential)3 AuthorizationCodeFlow (com.google.api.client.auth.oauth2.AuthorizationCodeFlow)2 Builder (com.google.api.client.auth.oauth2.AuthorizationCodeFlow.Builder)2 ClientParametersAuthentication (com.google.api.client.auth.oauth2.ClientParametersAuthentication)2 TokenResponse (com.google.api.client.auth.oauth2.TokenResponse)2 GenericUrl (com.google.api.client.http.GenericUrl)2 AuthorizationCodeTokenRequest (com.google.api.client.auth.oauth2.AuthorizationCodeTokenRequest)1 GoogleAuthorizationCodeFlow (com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow)1 GoogleAuthorizationCodeTokenRequest (com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeTokenRequest)1 GoogleTokenResponse (com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse)1 CacheBuilder (com.google.common.cache.CacheBuilder)1 ApiOperation (io.swagger.annotations.ApiOperation)1 GET (javax.ws.rs.GET)1 Path (javax.ws.rs.Path)1 Produces (javax.ws.rs.Produces)1 TwitterException (twitter4j.TwitterException)1 AccessToken (twitter4j.auth.AccessToken)1 ConfigurationBuilder (twitter4j.conf.ConfigurationBuilder)1