com.google.api.client.googleapis.auth.oauth2.GoogleIdToken Java Examples

The following examples show how to use com.google.api.client.googleapis.auth.oauth2.GoogleIdToken. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GoogleIdTokenVerifierTest.java    From styx with Apache License 2.0 6 votes vote down vote up
private String createToken() throws GeneralSecurityException, IOException {
  var issuedAt = Instant.now().getEpochSecond();
  var expiredAt = issuedAt + 3600; // One hour later
  var payload = new GoogleIdToken.Payload();
  payload.setAuthorizedParty("103411466401044735393");
  payload.setEmail("[email protected]");
  payload.setEmailVerified(true);
  payload.setIssuedAtTimeSeconds(issuedAt);
  payload.setExpirationTimeSeconds(expiredAt);
  payload.setIssuer("https://accounts.google.com");
  payload.setSubject("103411466401044735393");
  GenericJson googleMetadata = new GenericJson()
      .set("compute_engine", new GenericJson()
                                 .set("instance_creation_timestamp", 1556025719L)
                                 .set("instance_id", "5850837338805153689")
                                 .set("instance_name", "gew1-metricscatalogbro-b-b7z2")
                                 .set("project_id", "metrics-catalog")
                                 .set("project_number", 283581591831L)
                                 .set("zone", "europe-west1-d")
      );
  payload.set("google", googleMetadata);

  var header = new JsonWebSignature.Header().setAlgorithm("RS256");
  return JsonWebSignature.signUsingRsaSha256(privateKey, Utils.getDefaultJsonFactory(), header, payload);
}
 
Example #2
Source File: EndpointsPeerAuthenticator.java    From endpoints-java with Apache License 2.0 6 votes vote down vote up
@Override
public boolean authenticate(HttpServletRequest request) {
  // Preserve current check for App Engine Env.
  if (EnvUtil.isRunningOnAppEngine()) {
    return APPENGINE_PEER.equals(request.getHeader(HEADER_APPENGINE_PEER));
  }

  // Skip peer verification for localhost request.
  if (localHostAddresses.contains(request.getRemoteAddr())) {
    logger.atFine().log("Skip endpoints peer verication from localhost.");
    return true;
  }
  // Verify peer token, signer and audience.
  GoogleIdToken idToken =
      jwtAuthenticator.verifyToken(request.getHeader(HEADER_PEER_AUTHORIZATION));
  if (idToken == null || !SIGNER.equals(idToken.getPayload().getEmail())
      || !matchHostAndPort(idToken, request)) {
    return false;
  }
  return true;
}
 
Example #3
Source File: GoogleIdAuthorizer.java    From curiostack with MIT License 6 votes vote down vote up
@Override
public CompletionStage<Boolean> authorize(ServiceRequestContext ctx, OAuth2Token data) {
  final GoogleIdToken token;
  try {
    token = GoogleIdToken.parse(JacksonFactory.getDefaultInstance(), data.accessToken());
  } catch (IOException e) {
    logger.info("Could not parse id token {}", data.accessToken());
    return completedFuture(false);
  }
  return verifier
      .verify(token)
      .thenApply(
          result -> {
            if (!result) {
              logger.info("Invalid signature.");
              return false;
            }
            if (!commonNamesProvider.get().contains(token.getPayload().getEmail())) {
              logger.info("Rejecting client: {}", token.getPayload().getEmail());
              return false;
            }
            return true;
          });
}
 
Example #4
Source File: MockServer.java    From identity-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Print the audience of an unverified token string to the logs.
 * @param idTokenString the ID Token string.
 */
public static void logTokenAudience(String idTokenString) {
    try {
        GoogleIdToken idToken = GoogleIdToken.parse(jsonFactory, idTokenString);
        Log.d(TAG, "IDToken Audience:" + idToken.getPayload().getAudience());
    } catch (IOException e) {
        Log.e(TAG, "IDToken Audience: Could not parse ID Token", e);
    }
}
 
Example #5
Source File: Authenticator.java    From styx with Apache License 2.0 5 votes vote down vote up
private GoogleIdToken verifyIdToken(String token) throws IOException {
  try {
    return googleIdTokenVerifier.verify(token);
  } catch (GeneralSecurityException e) {
    logger.warn("Caught GeneralSecurityException when validating token", e);
    return null;
  }
}
 
Example #6
Source File: RequestAuthenticator.java    From styx with Apache License 2.0 5 votes vote down vote up
/**
 * Authentication an incoming Styx API request.
 * @param request The incoming request.
 * @return A {@link AuthContext} with the authentication result.
 * @throws ResponseException If the Authorization header does not have a Bearer prefix or if the token was invalid.
 */
public AuthContext authenticate(Request request) {
  final boolean hasAuthHeader = request.header(HttpHeaders.AUTHORIZATION).isPresent();

  if (!hasAuthHeader) {
    return Optional::empty;
  }

  final String authHeader = request.header(HttpHeaders.AUTHORIZATION).get();
  if (!authHeader.startsWith(BEARER_PREFIX)) {
    throw new ResponseException(Response.forStatus(Status.BAD_REQUEST
        .withReasonPhrase("Authorization token must be of type Bearer")));
  }

  final GoogleIdToken googleIdToken;
  try {
    googleIdToken = authenticator.authenticate(authHeader.substring(BEARER_PREFIX.length()));
  } catch (IllegalArgumentException e) {
    throw new ResponseException(Response.forStatus(Status.BAD_REQUEST
        .withReasonPhrase("Failed to parse Authorization token")), e);
  }

  if (googleIdToken == null) {
    throw new ResponseException(Response.forStatus(Status.UNAUTHORIZED
        .withReasonPhrase("Authorization token is invalid")));
  }

  return () -> Optional.of(googleIdToken);
}
 
Example #7
Source File: GoogleJwtAuthenticator.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
GoogleIdToken verifyToken(String token) {
  if (token == null) {
    return null;
  }
  try {
    return verifier.verify(token);
  } catch (GeneralSecurityException | IOException | IllegalArgumentException e) {
    logger.atWarning().withCause(e).log("error while verifying JWT");
    return null;
  }
}
 
Example #8
Source File: WorkflowActionAuthorizer.java    From styx with Apache License 2.0 5 votes vote down vote up
public void authorizeWorkflowAction(AuthContext ac, Workflow workflow) {
  final GoogleIdToken idToken = ac.user().orElseThrow(AssertionError::new);
  final Optional<String> serviceAccount = workflow.configuration().serviceAccount();
  if (serviceAccount.isEmpty()) {
    return;
  }
  serviceAccountUsageAuthorizer.authorizeServiceAccountUsage(workflow.id(), serviceAccount.get(), idToken);
}
 
Example #9
Source File: GoogleIdTokenAuthTest.java    From styx with Apache License 2.0 5 votes vote down vote up
private static boolean canAcquireIdToken(GoogleCredentials credentials)
    throws IOException, GeneralSecurityException {
  final GoogleIdTokenAuth idTokenAuth = GoogleIdTokenAuth.of(credentials);
  final String targetAudience = "http://styx.foo.bar";
  final Optional<String> token = idTokenAuth.getToken(targetAudience);
  final GoogleIdToken verifiedToken = VERIFIER.verify(token.orElseThrow());
  assertThat(verifiedToken, is(notNullValue()));
  if (!(credentials instanceof UserCredentials)) {
    // TODO: can we procure user id tokens with the styx service audience?
    assertThat(verifiedToken.verifyAudience(ImmutableList.of(targetAudience)), is(true));
  }
  return true;
}
 
Example #10
Source File: GoogleIdTokenAuthTest.java    From styx with Apache License 2.0 5 votes vote down vote up
@Test
public void testDefaultCredentials() throws IOException, GeneralSecurityException {
  final GoogleIdTokenAuth idTokenAuth = GoogleIdTokenAuth.ofDefaultCredential();
  final Optional<String> token = idTokenAuth.getToken("http://styx.foo.bar");
  if (credentials == null) {
    assertThat(token, is(Optional.empty()));
  } else {
    final GoogleIdToken verifiedToken = VERIFIER.verify(token.orElseThrow());
    assertThat(verifiedToken, is(notNullValue()));
  }
}
 
Example #11
Source File: GoogleIdTokenVerifier.java    From curiostack with MIT License 5 votes vote down vote up
public CompletableFuture<Boolean> verify(GoogleIdToken token) {
  Instant currentTime = clock.instant();
  if (currentTime.isAfter(
      Instant.ofEpochSecond(token.getPayload().getExpirationTimeSeconds())
          .plus(ALLOWED_TIME_SKEW))) {
    return completedFuture(false);
  }
  if (currentTime.isBefore(
      Instant.ofEpochMilli(token.getPayload().getIssuedAtTimeSeconds())
          .minus(ALLOWED_TIME_SKEW))) {
    return completedFuture(false);
  }
  return publicKeysManager
      .getKeys()
      .thenApply(
          keys -> {
            for (PublicKey key : keys) {
              try {
                if (token.verifySignature(key)) {
                  return true;
                }
              } catch (GeneralSecurityException e) {
                throw new IllegalArgumentException("Could not verify signature.", e);
              }
            }
            return false;
          });
}
 
Example #12
Source File: GoogleSecurityServiceSupplier.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public SpagoBIUserProfile checkAuthenticationToken(String token) {
	logger.debug("IN");
	LogMF.debug(logger, "Verifying token [{0}]...", token);
	GoogleIdToken idToken;
	try {
		idToken = verifyToken(token);
	} catch (GeneralSecurityException | IOException e) {
		logger.error("An exception occurred while verifying Google token [" + token + "]", e);
		return null;
	}
	if (idToken == null) {
		logger.error("Invalid ID token [" + token + "]");
		return null;
	}
	LogMF.debug(logger, "Token [{0}] verified successfully", token);

	Payload payload = idToken.getPayload();

	String userId = payload.getSubject();
	LogMF.debug(logger, "User ID: [{0}]", userId);
	String email = payload.getEmail();
	LogMF.debug(logger, "User email: [{0}]", email);
	String name = (String) payload.get("name");
	LogMF.debug(logger, "User name: [{0}]", name);
	LogMF.debug(logger, "Creating user profile object for user [{0}]...", email);
	SpagoBIUserProfile profile = createUserProfileObject(email);
	LogMF.debug(logger, "User profile object for user [{0}] created", email);
	return profile;
}
 
Example #13
Source File: SocialLogin.java    From PYX-Reloaded with Apache License 2.0 5 votes vote down vote up
@Contract("null -> null")
@Nullable
public GoogleIdToken.Payload verifyGoogle(String tokenStr) throws BaseCahHandler.CahException {
    if (tokenStr == null) return null;

    try {
        GoogleIdToken token = googleHelper.verify(tokenStr);
        return token == null ? null : token.getPayload();
    } catch (GeneralSecurityException | IOException ex) {
        throw new BaseCahHandler.CahException(Consts.ErrorCode.GOOGLE_ERROR, ex);
    }
}
 
Example #14
Source File: GoogleJwtAuthenticatorTest.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testAuthenticate() throws Exception {
  when(verifier.verify(TOKEN)).thenReturn(token);
  when(config.getClientIds()).thenReturn(ImmutableList.of(CLIENT_ID));
  when(config.getAudiences()).thenReturn(ImmutableList.of(AUDIENCE));
  User user = authenticator.authenticate(request);
  assertEquals(EMAIL, user.getEmail());
  assertEquals(USER_ID, user.getId());
  GoogleIdToken idToken = attr.get(Attribute.ID_TOKEN);
  assertNotNull(idToken);
  assertEquals(EMAIL, idToken.getPayload().getEmail());
  assertEquals(USER_ID, idToken.getPayload().getSubject());
}
 
Example #15
Source File: MockServer.java    From android-credentials with Apache License 2.0 5 votes vote down vote up
/**
 * Print the audience of an unverified token string to the logs.
 * @param idTokenString the ID Token string.
 */
public static void logTokenAudience(String idTokenString) {
    try {
        GoogleIdToken idToken = GoogleIdToken.parse(jsonFactory, idTokenString);
        Log.d(TAG, "IDToken Audience:" + idToken.getPayload().getAudience());
    } catch (IOException e) {
        Log.e(TAG, "IDToken Audience: Could not parse ID Token", e);
    }
}
 
Example #16
Source File: PubSubAuthenticatedPush.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp)
    throws IOException, ServletException {

  // Verify that the request originates from the application.
  if (req.getParameter("token").compareTo(pubsubVerificationToken) != 0) {
    resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    return;
  }
  // Get the Cloud Pub/Sub-generated JWT in the "Authorization" header.
  String authorizationHeader = req.getHeader("Authorization");
  if (authorizationHeader == null
      || authorizationHeader.isEmpty()
      || authorizationHeader.split(" ").length != 2) {
    resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    return;
  }
  String authorization = authorizationHeader.split(" ")[1];

  try {
    // Verify and decode the JWT.
    // Note: For high volume push requests, it would save some network overhead
    // if you verify the tokens offline by decoding them using Google's Public
    // Cert; caching already seen tokens works best when a large volume of
    // messsages have prompted a singple push server to handle them, in which
    // case they would all share the same token for a limited time window.
    GoogleIdToken idToken = verifier.verify(authorization);
    messageRepository.saveToken(authorization);
    messageRepository.saveClaim(idToken.getPayload().toPrettyString());
    // parse message object from "message" field in the request body json
    // decode message data from base64
    Message message = getMessage(req);
    messageRepository.save(message);
    // 200, 201, 204, 102 status codes are interpreted as success by the Pub/Sub system
    resp.setStatus(102);
    super.doPost(req, resp);
  } catch (Exception e) {
    resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
  }
}
 
Example #17
Source File: GoogleJwtAuthenticator.java    From endpoints-java with Apache License 2.0 4 votes vote down vote up
@Override
public User authenticate(HttpServletRequest request) {
  Attribute attr = Attribute.from(request);
  if (attr.isEnabled(Attribute.SKIP_TOKEN_AUTH)) {
    return null;
  }

  String token = GoogleAuth.getAuthToken(request);
  if (!GoogleAuth.isJwt(token)) {
    return null;
  }

  GoogleIdToken idToken = verifyToken(token);
  if (idToken == null) {
    return null;
  }

  attr.set(Attribute.ID_TOKEN, idToken);

  String clientId = idToken.getPayload().getAuthorizedParty();
  String audience = (String) idToken.getPayload().getAudience();

  ApiMethodConfig config = attr.get(Attribute.API_METHOD_CONFIG);

  // Check client id.
  if ((attr.isEnabled(Attribute.ENABLE_CLIENT_ID_WHITELIST)
      && !GoogleAuth.checkClientId(clientId, config.getClientIds(), false))) {
    logger.atWarning().log("ClientId is not allowed: %s", clientId);
    return null;
  }
  // Check audience.
  if (!GoogleAuth.checkAudience(audience, config.getAudiences(), clientId)) {
    logger.atWarning().log("Audience is not allowed: %s", audience);
    return null;
  }

  String userId = idToken.getPayload().getSubject();
  String email = idToken.getPayload().getEmail();
  User user = (userId == null && email == null) ? null : new User(userId, email);
  if (attr.isEnabled(Attribute.REQUIRE_APPENGINE_USER)) {
    com.google.appengine.api.users.User appEngineUser =
        (email == null) ? null : new com.google.appengine.api.users.User(email, "");
    attr.set(Attribute.AUTHENTICATED_APPENGINE_USER, appEngineUser);
    logger.atFine().log("appEngineUser = %s", appEngineUser);
  } else {
    logger.atFine().log("user = %s", user);
  }
  return user;
}
 
Example #18
Source File: GoogleAccount.java    From PYX-Reloaded with Apache License 2.0 4 votes vote down vote up
public GoogleAccount(ResultSet user, GoogleIdToken.Payload token) throws SQLException, ParseException {
    super(user, token.getEmailVerified());

    subject = user.getString("google_sub");
}
 
Example #19
Source File: ServiceAccountUsageAuthorizer.java    From styx with Apache License 2.0 4 votes vote down vote up
@Override
public boolean shouldEnforceAuthorization(WorkflowId workflowId, String serviceAccount, GoogleIdToken idToken) {
  return whitelist.contains(workflowId);
}
 
Example #20
Source File: ServiceAccountUsageAuthorizer.java    From styx with Apache License 2.0 4 votes vote down vote up
@Override
public boolean shouldEnforceAuthorization(WorkflowId workflowId, String serviceAccount, GoogleIdToken idToken) {
  return true;
}
 
Example #21
Source File: ServiceAccountUsageAuthorizer.java    From styx with Apache License 2.0 4 votes vote down vote up
@Override
public void authorizeServiceAccountUsage(WorkflowId workflowId, String serviceAccount, GoogleIdToken idToken) {
  // nop
}
 
Example #22
Source File: GoogleSecurityServiceSupplier.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
private GoogleIdToken verifyToken(String token) throws GeneralSecurityException, IOException {
	GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(new NetHttpTransport(), JacksonFactory.getDefaultInstance())
			.setAudience(Collections.singletonList(GoogleSignInConfig.getClientId())).build();
	GoogleIdToken idToken = verifier.verify(token);
	return idToken;
}
 
Example #23
Source File: UsersWithAccount.java    From PYX-Reloaded with Apache License 2.0 4 votes vote down vote up
@NotNull
public GoogleAccount registerWithGoogle(@NotNull String nickname, @NotNull GoogleIdToken.Payload token) {
    GoogleAccount account = new GoogleAccount(nickname, token);
    addAccount(account);
    return account;
}
 
Example #24
Source File: RegisterHandler.java    From PYX-Reloaded with Apache License 2.0 4 votes vote down vote up
@NotNull
@Override
public JsonWrapper handle(@Nullable User user, Parameters params, HttpServerExchange exchange) throws BaseJsonHandler.StatusException {
    if (banList.contains(exchange.getHostName()))
        throw new BaseCahHandler.CahException(Consts.ErrorCode.BANNED);

    PreparingShutdown.get().check();

    Consts.AuthType type;
    try {
        type = Consts.AuthType.parse(params.getStringNotNull(Consts.GeneralKeys.AUTH_TYPE));
    } catch (ParseException ex) {
        throw new BaseCahHandler.CahException(Consts.ErrorCode.BAD_REQUEST, ex);
    }

    UserAccount account;
    String nickname;
    switch (type) {
        case PASSWORD:
            nickname = params.getStringNotNull(Consts.UserData.NICKNAME);
            if (!Pattern.matches(Consts.VALID_NAME_PATTERN, nickname))
                throw new BaseCahHandler.CahException(Consts.ErrorCode.INVALID_NICK);

            account = accounts.getPasswordAccountForNickname(nickname);
            if (account == null) { // Without account
                user = new User(nickname, exchange.getHostName(), Sessions.generateNewId());
            } else {
                String password = params.getStringNotNull(Consts.AuthType.PASSWORD);
                if (password.isEmpty() || !BCrypt.checkpw(password, ((PasswordAccount) account).hashedPassword))
                    throw new BaseCahHandler.CahException(Consts.ErrorCode.WRONG_PASSWORD);

                user = User.withAccount(account, exchange.getHostName());
            }
            break;
        case GOOGLE:
            if (!socialLogin.googleEnabled())
                throw new BaseCahHandler.CahException(Consts.ErrorCode.UNSUPPORTED_AUTH_TYPE);

            GoogleIdToken.Payload googleToken = socialLogin.verifyGoogle(params.getStringNotNull(Consts.AuthType.GOOGLE));
            if (googleToken == null) throw new BaseCahHandler.CahException(Consts.ErrorCode.GOOGLE_INVALID_TOKEN);

            account = accounts.getGoogleAccount(googleToken);
            if (account == null) throw new BaseCahHandler.CahException(Consts.ErrorCode.GOOGLE_NOT_REGISTERED);

            nickname = account.username;
            user = User.withAccount(account, exchange.getHostName());
            break;
        case FACEBOOK:
            if (!socialLogin.facebookEnabled())
                throw new BaseCahHandler.CahException(Consts.ErrorCode.UNSUPPORTED_AUTH_TYPE);

            FacebookToken facebookToken = socialLogin.verifyFacebook(params.getStringNotNull(Consts.AuthType.FACEBOOK));
            if (facebookToken == null)
                throw new BaseCahHandler.CahException(Consts.ErrorCode.FACEBOOK_INVALID_TOKEN);

            account = accounts.getFacebookAccount(facebookToken);
            if (account == null) throw new BaseCahHandler.CahException(Consts.ErrorCode.FACEBOOK_NOT_REGISTERED);

            nickname = account.username;
            user = User.withAccount(account, exchange.getHostName());
            break;
        case GITHUB:
            if (!socialLogin.githubEnabled())
                throw new BaseCahHandler.CahException(Consts.ErrorCode.UNSUPPORTED_AUTH_TYPE);

            String githubToken = params.getStringNotNull(Consts.AuthType.GITHUB);

            GithubProfileInfo githubInfo = socialLogin.infoGithub(githubToken);
            account = accounts.getGithubAccount(githubInfo);
            if (account == null) throw new BaseCahHandler.CahException(Consts.ErrorCode.GITHUB_NOT_REGISTERED);

            nickname = account.username;
            user = User.withAccount(account, exchange.getHostName());
            break;
        case TWITTER:
            if (!socialLogin.twitterEnabled())
                throw new BaseCahHandler.CahException(Consts.ErrorCode.UNSUPPORTED_AUTH_TYPE);

            String twitterTokens = params.getStringNotNull(Consts.AuthType.TWITTER);

            TwitterProfileInfo twitterInfo = socialLogin.infoTwitter(twitterTokens);
            account = accounts.getTwitterAccount(twitterInfo);
            if (account == null) throw new BaseCahHandler.CahException(Consts.ErrorCode.TWITTER_NOT_REGISTERED);

            nickname = account.username;
            user = User.withAccount(account, exchange.getHostName());
            break;
        default:
            throw new BaseCahHandler.CahException(Consts.ErrorCode.BAD_REQUEST);
    }

    User registeredUser = users.checkAndAdd(user);
    if (registeredUser != null) user = registeredUser;
    exchange.setResponseCookie(new CookieImpl("PYX-Session", Sessions.get().add(user)));

    return new JsonWrapper()
            .add(Consts.UserData.NICKNAME, nickname)
            .add(Consts.UserData.IS_ADMIN, user.isAdmin());
}
 
Example #25
Source File: CreateAccountHandler.java    From PYX-Reloaded with Apache License 2.0 4 votes vote down vote up
@NotNull
@Override
public JsonWrapper handle(User user, Parameters params, HttpServerExchange exchange) throws BaseJsonHandler.StatusException {
    if (banList.contains(exchange.getHostName()))
        throw new BaseCahHandler.CahException(Consts.ErrorCode.BANNED);

    PreparingShutdown.get().check();

    String nickname = params.getStringNotNull(Consts.UserData.NICKNAME);
    if (!Pattern.matches(Consts.VALID_NAME_PATTERN, nickname))
        throw new BaseCahHandler.CahException(Consts.ErrorCode.INVALID_NICK);
    if (connectedUsers.hasUser(nickname) || accounts.hasNickname(nickname))
        throw new BaseCahHandler.CahException(Consts.ErrorCode.NICK_IN_USE);

    UserAccount account;
    Consts.AuthType type;
    try {
        type = Consts.AuthType.parse(params.getStringNotNull(Consts.GeneralKeys.AUTH_TYPE));
    } catch (ParseException ex) {
        throw new BaseCahHandler.CahException(Consts.ErrorCode.BAD_REQUEST, ex);
    }

    switch (type) {
        case PASSWORD:
            if (!emails.enabled()) throw new BaseCahHandler.CahException(Consts.ErrorCode.UNSUPPORTED_AUTH_TYPE);

            String email = params.getStringNotNull(Consts.UserData.EMAIL);
            if (email.isEmpty()) throw new BaseCahHandler.CahException(Consts.ErrorCode.BAD_REQUEST);

            if (accounts.hasEmail(email)) throw new BaseCahHandler.CahException(Consts.ErrorCode.EMAIL_IN_USE);

            String password = params.getStringNotNull(Consts.AuthType.PASSWORD);
            if (password.isEmpty()) throw new BaseCahHandler.CahException(Consts.ErrorCode.BAD_REQUEST);

            account = accounts.registerWithPassword(nickname, email, password);
            emails.sendEmailVerification(account);
            break;
        case GOOGLE:
            if (!socialLogin.googleEnabled())
                throw new BaseCahHandler.CahException(Consts.ErrorCode.UNSUPPORTED_AUTH_TYPE);

            GoogleIdToken.Payload googleToken = socialLogin.verifyGoogle(params.getStringNotNull(Consts.AuthType.GOOGLE));
            if (googleToken == null) throw new BaseCahHandler.CahException(Consts.ErrorCode.GOOGLE_INVALID_TOKEN);

            if (accounts.hasEmail(googleToken.getEmail()))
                throw new BaseCahHandler.CahException(Consts.ErrorCode.EMAIL_IN_USE);

            account = accounts.registerWithGoogle(nickname, googleToken);
            break;
        case FACEBOOK:
            if (!socialLogin.facebookEnabled())
                throw new BaseCahHandler.CahException(Consts.ErrorCode.UNSUPPORTED_AUTH_TYPE);

            FacebookToken facebookToken = socialLogin.verifyFacebook(params.getStringNotNull(Consts.AuthType.FACEBOOK));
            if (facebookToken == null)
                throw new BaseCahHandler.CahException(Consts.ErrorCode.FACEBOOK_INVALID_TOKEN);

            FacebookProfileInfo facebookInfo = socialLogin.infoFacebook(facebookToken.userId);
            if (accounts.hasEmail(facebookInfo.email))
                throw new BaseCahHandler.CahException(Consts.ErrorCode.EMAIL_IN_USE);

            account = accounts.registerWithFacebook(nickname, facebookToken, facebookInfo);
            break;
        case GITHUB:
            if (!socialLogin.githubEnabled())
                throw new BaseCahHandler.CahException(Consts.ErrorCode.UNSUPPORTED_AUTH_TYPE);

            String githubToken = params.getString(Consts.AuthType.GITHUB);
            if (githubToken == null)
                throw new BaseCahHandler.CahException(Consts.ErrorCode.GITHUB_INVALID_TOKEN);

            GithubProfileInfo githubInfo = socialLogin.infoGithub(githubToken);
            if (accounts.hasEmail(githubInfo.email))
                throw new BaseCahHandler.CahException(Consts.ErrorCode.EMAIL_IN_USE);

            account = accounts.registerWithGithub(nickname, githubInfo);
            break;
        case TWITTER:
            if (!socialLogin.twitterEnabled())
                throw new BaseCahHandler.CahException(Consts.ErrorCode.UNSUPPORTED_AUTH_TYPE);

            String twitterTokens = params.getString(Consts.AuthType.TWITTER);
            if (twitterTokens == null)
                throw new BaseCahHandler.CahException(Consts.ErrorCode.TWITTER_INVALID_TOKEN);

            TwitterProfileInfo twitterInfo = socialLogin.infoTwitter(twitterTokens);
            if (accounts.hasEmail(twitterInfo.email))
                throw new BaseCahHandler.CahException(Consts.ErrorCode.EMAIL_IN_USE);

            account = accounts.registerWithTwitter(nickname, twitterInfo);
            break;
        default:
            throw new BaseCahHandler.CahException(Consts.ErrorCode.BAD_REQUEST);
    }

    return account.toJson();
}
 
Example #26
Source File: GoogleAccount.java    From PYX-Reloaded with Apache License 2.0 4 votes vote down vote up
public GoogleAccount(String nickname, GoogleIdToken.Payload token) {
    super(nickname, token.getEmail(), Consts.AuthType.GOOGLE, token.getEmailVerified(), (String) token.getOrDefault("picture", null));

    this.subject = token.getSubject();
}
 
Example #27
Source File: ServiceAccountUsageAuthorizer.java    From styx with Apache License 2.0 2 votes vote down vote up
/**
 * Returns true if authorization should be enforced, false otherwise.
 */
boolean shouldEnforceAuthorization(WorkflowId workflowId, String serviceAccount, GoogleIdToken idToken);
 
Example #28
Source File: ServiceAccountUsageAuthorizer.java    From styx with Apache License 2.0 2 votes vote down vote up
/**
 * Authorize service account usage by a principal in a workflow.
 * @throws ResponseException if not authorized.
 */
void authorizeServiceAccountUsage(WorkflowId workflowId, String serviceAccount, GoogleIdToken idToken);
 
Example #29
Source File: Middlewares.java    From styx with Apache License 2.0 votes vote down vote up
Optional<GoogleIdToken> user();