All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.sf.aguacate.security.service.oauth2.google.SecurityServiceOauth2Google Maven / Gradle / Ivy

There is a newer version: 0.0.17
Show newest version
package net.sf.aguacate.security.service.oauth2.google;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.util.Collections;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import net.sf.aguacate.security.service.SecurityService;
import net.sf.aguacate.security.service.SecurityValidationResponse;
import net.sf.aguacate.security.service.SecurityValidationStatus;
import net.sf.aguacate.util.codec.bridge.CodecCoupling;
import net.sf.aguacate.util.http.bridge.HttpCoupling;

public class SecurityServiceOauth2Google implements SecurityService {

	private static final Logger LOGGER = LogManager.getLogger(SecurityServiceOauth2Google.class);

	// TODO: Check for update (pooling)
	private static final URI ENDPOINT;

	static {
		try {
			Object response = HttpCoupling.defaultInstance().readMapFromGet(
					URI.create("https://accounts.google.com/.well-known/openid-configuration"),
					CodecCoupling.jsonCodecBridge());
			Class klass = response.getClass();
			if (Integer.class == klass) {
				throw new IllegalStateException("error: " + response);
			} else {
				@SuppressWarnings("unchecked")
				Map map = (Map) response;
				LOGGER.trace("GOOGLE configuration: {}", map);
				String str = (String) map.get("userinfo_endpoint");
				if (str == null) {
					throw new IllegalStateException("No userinfo_endpoint founds");
				} else {
					LOGGER.debug("user info endpoint: {}", str);
					ENDPOINT = URI.create(str);
				}
			}
		} catch (IOException e) {
			throw new IllegalStateException(e);
		}
	}

	public SecurityValidationResponse isValid(String token, String method, String resource) {
		try {
			Object response = HttpCoupling.defaultInstance().readMapFromGet(ENDPOINT,
					Collections.singletonMap("Authorization", "Bearer ".concat(token)),
					CodecCoupling.jsonCodecBridge());
			Class klass = response.getClass();
			if (Integer.class == klass) {
				switch (((Integer) response).intValue()) {
				case HttpURLConnection.HTTP_UNAUTHORIZED:
					return new SecurityValidationResponse(SecurityValidationStatus.UNAUTHORIZED);
				case HttpURLConnection.HTTP_FORBIDDEN:
					return new SecurityValidationResponse(SecurityValidationStatus.FORBIDDEN);
				default:
					return new SecurityValidationResponse(SecurityValidationStatus.UNSUPPORTED);
				}
			} else {
				LOGGER.trace(response);
				@SuppressWarnings("unchecked")
				Map map = (Map) response;
				return new SecurityValidationResponse(SecurityValidationStatus.SUCCESS, map);
			}
		} catch (IOException e) {
			return new SecurityValidationResponse(SecurityValidationStatus.UNINTELLIGIBLE);
		}
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy