Java Code Examples for org.gluu.oxauth.model.util.Util

The following examples show how to use org.gluu.oxauth.model.util.Util. These examples are extracted from open source projects. 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 Project: oxTrust   Source File: Configuration.java    License: MIT License 6 votes vote down vote up
public String getPropertyValue(String propertyName) {
   	if (StringHelper.equalsIgnoreCase(Configuration.OAUTH_PROPERTY_AUTHORIZE_URL, propertyName)) {
   		return openIdConfiguration.getAuthorizationEndpoint();
   	} else if (StringHelper.equalsIgnoreCase(Configuration.OAUTH_PROPERTY_TOKEN_URL, propertyName)) {
   		return openIdConfiguration.getTokenEndpoint();
   	} else if (StringHelper.equalsIgnoreCase(Configuration.OAUTH_PROPERTY_USERINFO_URL, propertyName)) {
   		return openIdConfiguration.getUserInfoEndpoint();
   	} else if (StringHelper.equalsIgnoreCase(Configuration.OAUTH_PROPERTY_LOGOUT_URL, propertyName)) {
   		return openIdConfiguration.getEndSessionEndpoint();
   	} else if (StringHelper.equalsIgnoreCase(Configuration.OAUTH_PROPERTY_LOGOUT_REDIRECT_URL, propertyName)) {
   		return appConfiguration.getOpenIdPostLogoutRedirectUri();
   	} else if (StringHelper.equalsIgnoreCase(Configuration.OAUTH_PROPERTY_CLIENT_ID, propertyName)) {
   		return appConfiguration.getOpenIdClientId();
   	} else if (StringHelper.equalsIgnoreCase(Configuration.OAUTH_PROPERTY_CLIENT_PASSWORD, propertyName)) {
   		return appConfiguration.getOpenIdClientPassword();
   	} else if (StringHelper.equalsIgnoreCase(Configuration.OAUTH_PROPERTY_CLIENT_SCOPE, propertyName)) {
   		return Util.listAsString(appConfiguration.getOpenIdScopes());
   	}

   	return null;
}
 
Example 2
Source Project: oxAuth   Source File: SoftwareStatement.java    License: MIT License 6 votes vote down vote up
public String getEncodedJwt(JSONObject jwks) throws Exception {
    String encodedJwt = null;

    if (cryptoProvider == null) {
        throw new Exception("The Crypto Provider cannot be null.");
    }

    JSONObject headerJsonObject = headerToJSONObject();
    JSONObject payloadJsonObject = getClaims();
    String headerString = ClientUtil.toPrettyJson(headerJsonObject);
    String payloadString = ClientUtil.toPrettyJson(payloadJsonObject);
    String encodedHeader = Base64Util.base64urlencode(headerString.getBytes(Util.UTF8_STRING_ENCODING));
    String encodedPayload = Base64Util.base64urlencode(payloadString.getBytes(Util.UTF8_STRING_ENCODING));
    String signingInput = encodedHeader + "." + encodedPayload;
    String encodedSignature = cryptoProvider.sign(signingInput, keyId, sharedKey, signatureAlgorithm);

    encodedJwt = encodedHeader + "." + encodedPayload + "." + encodedSignature;

    return encodedJwt;
}
 
Example 3
Source Project: oxAuth   Source File: UmaClient.java    License: MIT License 6 votes vote down vote up
public static Token request(final String tokenUrl, final String umaClientId, final String umaClientSecret, UmaScopeType scopeType,
                            ClientExecutor clientExecutor, String... scopeArray) throws Exception {

    String scope = scopeType.getValue();
    if (scopeArray != null && scopeArray.length > 0) {
        for (String s : scopeArray) {
            scope = scope + " " + s;
        }
    }

    TokenClient tokenClient = new TokenClient(tokenUrl);
    if (clientExecutor != null) {
        tokenClient.setExecutor(clientExecutor);
    }
    TokenResponse response = tokenClient.execClientCredentialsGrant(scope, umaClientId, umaClientSecret);

    if (response.getStatus() == 200) {
        final String patToken = response.getAccessToken();
        final Integer expiresIn = response.getExpiresIn();
        if (Util.allNotBlank(patToken)) {
            return new Token(null, null, patToken, scopeType.getValue(), expiresIn);
        }
    }

    return null;
}
 
Example 4
Source Project: oxAuth   Source File: UmaClient.java    License: MIT License 6 votes vote down vote up
public static Token request(final String tokenUrl, final TokenRequest tokenRequest) throws Exception {
	if (tokenRequest.getGrantType() != GrantType.CLIENT_CREDENTIALS) {
		return null;
	}

    TokenClient tokenClient = new TokenClient(tokenUrl);

    tokenClient.setRequest(tokenRequest);

    TokenResponse response = tokenClient.exec();

    if (response.getStatus() == 200) {
        final String patToken = response.getAccessToken();
        final Integer expiresIn = response.getExpiresIn();
        if (Util.allNotBlank(patToken)) {
            return new Token(null, null, patToken, response.getScope(), expiresIn);
        }
    }

    return null;
}
 
Example 5
Source Project: oxAuth   Source File: BackchannelAuthenticationRequest.java    License: MIT License 6 votes vote down vote up
@Override
public String getQueryString() {
    QueryBuilder builder = QueryBuilder.instance();

    final String scopesAsString = Util.listAsString(scope);
    final String acrValuesAsString = Util.listAsString(acrValues);

    builder.append(BackchannelAuthenticationRequestParam.SCOPE, scopesAsString);
    builder.append(BackchannelAuthenticationRequestParam.CLIENT_NOTIFICATION_TOKEN, clientNotificationToken);
    builder.append(BackchannelAuthenticationRequestParam.ACR_VALUES, acrValuesAsString);
    builder.append(BackchannelAuthenticationRequestParam.LOGIN_HINT_TOKEN, loginHintToken);
    builder.append(BackchannelAuthenticationRequestParam.ID_TOKEN_HINT, idTokenHint);
    builder.append(BackchannelAuthenticationRequestParam.LOGIN_HINT, loginHint);
    builder.append(BackchannelAuthenticationRequestParam.BINDING_MESSAGE, bindingMessage);
    builder.append(BackchannelAuthenticationRequestParam.USER_CODE, userCode);
    builder.appendIfNotNull(BackchannelAuthenticationRequestParam.REQUESTED_EXPIRY, requestedExpiry);
    builder.appendIfNotNull(BackchannelAuthenticationRequestParam.CLIENT_ID, clientId);
    builder.appendIfNotNull(BackchannelAuthenticationRequestParam.REQUEST, request);
    builder.appendIfNotNull(BackchannelAuthenticationRequestParam.REQUEST_URI, requestUri);

    appendClientAuthnToQuery(builder);
    return builder.toString();
}
 
Example 6
Source Project: oxAuth   Source File: BcFirebaseMessagingSwServlet.java    License: MIT License 6 votes vote down vote up
private void loadFirebaseMessagingSwFile(HttpServletResponse response) {
	String baseJavascriptFileConfiguration = "/WEB-INF/firebase-messaging-sw.js";
	try (InputStream in = getServletContext().getResourceAsStream(baseJavascriptFileConfiguration);
			OutputStream out = response.getOutputStream()) {
		String content = IOUtils.toString(in, StandardCharsets.UTF_8);

		Map<String, String> publicConfiguration = new HashMap<>();
		publicConfiguration.put("apiKey", appConfiguration.getCibaEndUserNotificationConfig().getApiKey());
		publicConfiguration.put("authDomain", appConfiguration.getCibaEndUserNotificationConfig().getAuthDomain());
		publicConfiguration.put("databaseURL", appConfiguration.getCibaEndUserNotificationConfig().getDatabaseURL());
		publicConfiguration.put("projectId", appConfiguration.getCibaEndUserNotificationConfig().getProjectId());
		publicConfiguration.put("storageBucket", appConfiguration.getCibaEndUserNotificationConfig().getStorageBucket());
		publicConfiguration.put("messagingSenderId", appConfiguration.getCibaEndUserNotificationConfig().getMessagingSenderId());
		publicConfiguration.put("appId", appConfiguration.getCibaEndUserNotificationConfig().getAppId());

		content = content.replace("'${FIREBASE_CONFIG}'", Util.asJson(publicConfiguration));

		IOUtils.write(content, out, StandardCharsets.UTF_8);
	} catch (IOException e) {
		log.debug("Error loading firebase-messaging-sw.js configuration file: " + e.getMessage());
	}
}
 
Example 7
Source Project: oxAuth   Source File: CibaRequestCacheControl.java    License: MIT License 6 votes vote down vote up
public CibaRequestCacheControl(User user, Client client, int expiresIn, List<String> scopeList,
                               String clientNotificationToken, String bindingMessage, Long lastAccessControl,
                               String acrValues) {
    byte[] nonce = new byte[24];
    new SecureRandom().nextBytes(nonce);
    this.authReqId = Util.byteArrayToHexString(nonce);
    this.user = user;
    this.client = client;
    this.scopes = scopeList;
    this.status = CibaRequestStatus.PENDING;
    this.expiresIn = expiresIn;
    this.clientNotificationToken = clientNotificationToken;
    this.bindingMessage = bindingMessage;
    this.lastAccessControl = lastAccessControl;
    this.tokensDelivered = false;
    this.acrValues = acrValues;
}
 
Example 8
Source Project: oxAuth   Source File: RequestParameterService.java    License: MIT License 6 votes vote down vote up
public String parametersAsString(final Map<String, String> parameterMap) throws UnsupportedEncodingException {
    final StringBuilder sb = new StringBuilder();
    final Set<Entry<String, String>> set = parameterMap.entrySet();
    for (Map.Entry<String, String> entry : set) {
        final String value = (String) entry.getValue();
        if (StringUtils.isNotBlank(value)) {
            sb.append(entry.getKey()).append("=").append(URLEncoder.encode(value, Util.UTF8_STRING_ENCODING)).append("&");
        }
    }

    String result = sb.toString();
    if (result.endsWith("&")) {
        result = result.substring(0, result.length() - 1);
    }
    return result;
}
 
Example 9
Source Project: oxAuth   Source File: LogoutAction.java    License: MIT License 6 votes vote down vote up
private boolean restoreLogoutParametersFromSession(SessionId sessionId) throws IllegalArgumentException, JsonParseException, JsonMappingException, IOException {
    if (sessionId == null) {
        return false;
    }

    this.sessionId = sessionId;
    Map<String, String> sessionAttributes = sessionId.getSessionAttributes();

    boolean restoreParameters = sessionAttributes.containsKey(EXTERNAL_LOGOUT);
    if (!restoreParameters) {
        return false;
    }

    String logoutParametersBase64 = sessionAttributes.get(EXTERNAL_LOGOUT_DATA);
    String logoutParametersJson = new String(Base64Util.base64urldecode(logoutParametersBase64), Util.UTF8_STRING_ENCODING);

    LogoutParameters logoutParameters = jsonService.jsonToObject(logoutParametersJson, LogoutParameters.class);

    this.idTokenHint = logoutParameters.getIdTokenHint();
    this.postLogoutRedirectUri = logoutParameters.getPostLogoutRedirectUri();

    return true;
}
 
Example 10
Source Project: oxAuth   Source File: AuthorizeAction.java    License: MIT License 6 votes vote down vote up
public void checkUiLocales() {
    List<String> uiLocalesList = null;
    if (StringUtils.isNotBlank(uiLocales)) {
        uiLocalesList = Util.splittedStringAsList(uiLocales, " ");

        List<Locale> supportedLocales = languageBean.getSupportedLocales();
        Locale matchingLocale = LocaleUtil.localeMatch(uiLocalesList, supportedLocales);

        if (matchingLocale != null) {
            languageBean.setLocale(matchingLocale);
        }
    } else {
        Locale requestedLocale = facesContext.getExternalContext().getRequestLocale();
        if (requestedLocale != null) {
            languageBean.setLocale(requestedLocale);
            return;
        }
        
        Locale defaultLocale = facesContext.getApplication().getDefaultLocale();
        if (defaultLocale != null) {
            languageBean.setLocale(defaultLocale);
        }
    }
}
 
Example 11
Source Project: oxAuth   Source File: RedirectUri.java    License: MIT License 6 votes vote down vote up
public String getQueryString() {
    StringBuilder sb = new StringBuilder();
    for (Map.Entry<String, String> entry : responseParameters.entrySet()) {
        try {
            if (StringUtils.isNotBlank(entry.getKey()) && StringUtils.isNotBlank(entry.getValue())) {
                if (sb.length() > 0) {
                    sb.append('&');
                }
                sb.append(URLEncoder.encode(entry.getKey(), Util.UTF8_STRING_ENCODING));
                sb.append('=').append(URLEncoder.encode(entry.getValue(), Util.UTF8_STRING_ENCODING));
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    return sb.toString();
}
 
Example 12
Source Project: oxAuth   Source File: PureJwt.java    License: MIT License 6 votes vote down vote up
public PureJwt(String p_encodedHeader, String p_encodedPayload, String p_encodedSignature) {

        m_encodedHeader = p_encodedHeader;
        m_encodedPayload = p_encodedPayload;
        m_encodedSignature = p_encodedSignature;
        m_signingInput = m_encodedHeader + "." + m_encodedPayload;

        String decodedPayloadTemp = null;
        String decodedHeaderTemp = null;
        try {
            decodedHeaderTemp = new String(Base64Util.base64urldecode(p_encodedHeader), Util.UTF8_STRING_ENCODING);
            decodedPayloadTemp = new String(Base64Util.base64urldecode(p_encodedPayload), Util.UTF8_STRING_ENCODING);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        m_decodedHeader = decodedHeaderTemp;
        m_decodedPayload = decodedPayloadTemp;
    }
 
Example 13
Source Project: oxAuth   Source File: OxAuthCryptoProvider.java    License: MIT License 6 votes vote down vote up
public OxAuthCryptoProvider(String keyStoreFile, String keyStoreSecret, String dnName, boolean rejectNoneAlg) throws Exception {
    this.rejectNoneAlg = rejectNoneAlg;
    if (!Util.isNullOrEmpty(keyStoreFile) && !Util.isNullOrEmpty(keyStoreSecret) /* && !Util.isNullOrEmpty(dnName) */) {
        this.keyStoreFile = keyStoreFile;
        this.keyStoreSecret = keyStoreSecret;
        this.dnName = dnName;

        keyStore = KeyStore.getInstance("JKS");
        try {
            File f = new File(keyStoreFile);
            if (!f.exists()) {
                keyStore.load(null, keyStoreSecret.toCharArray());
                FileOutputStream fos = new FileOutputStream(keyStoreFile);
                keyStore.store(fos, keyStoreSecret.toCharArray());
                fos.close();
            }
            final InputStream is = new FileInputStream(keyStoreFile);
            keyStore.load(is, keyStoreSecret.toCharArray());
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
    }
}
 
Example 14
Source Project: oxAuth   Source File: OxAuthCryptoProvider.java    License: MIT License 6 votes vote down vote up
public PublicKey getPublicKey(String alias) {
    PublicKey publicKey = null;

    try {
        if (Util.isNullOrEmpty(alias)) {
            return null;
        }

        java.security.cert.Certificate certificate = keyStore.getCertificate(alias);
        if (certificate == null) {
            return null;
        }
        publicKey = certificate.getPublicKey();

        checkKeyExpiration(alias);
    } catch (KeyStoreException e) {
        e.printStackTrace();
    }

    return publicKey;
}
 
Example 15
Source Project: oxAuth   Source File: OxAuthCryptoProvider.java    License: MIT License 6 votes vote down vote up
public PrivateKey getPrivateKey(String alias)
        throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException {
    if (Util.isNullOrEmpty(alias)) {
        return null;
    }

    Key key = keyStore.getKey(alias, keyStoreSecret.toCharArray());
    if (key == null) {
        return null;
    }
    PrivateKey privateKey = (PrivateKey) key;

    checkKeyExpiration(alias);

    return privateKey;
}
 
Example 16
Source Project: oxd   Source File: UmaTokenService.java    License: Apache License 2.0 6 votes vote down vote up
private Token obtainTokenWithClientCredentials(OpenIdConfigurationResponse discovery, Rp rp, UmaScopeType scopeType) {
    final TokenClient tokenClient = opClientFactory.createTokenClientWithUmaProtectionScope(discovery.getTokenEndpoint());
    tokenClient.setExecutor(httpService.getClientExecutor());
    final TokenResponse response = tokenClient.execClientCredentialsGrant(scopesAsString(scopeType), rp.getClientId(), rp.getClientSecret());
    if (response != null) {
        if (Util.allNotBlank(response.getAccessToken())) {
            if (scopeType != null && !response.getScope().contains(scopeType.getValue())) {
                LOG.error("oxd requested scope " + scopeType + " but AS returned access_token without that scope, token scopes :" + response.getScope());
                LOG.error("Please check AS(oxauth) configuration and make sure UMA scope (uma_protection) is enabled.");
                throw new RuntimeException("oxd requested scope " + scopeType + " but AS returned access_token without that scope, token scopes :" + response.getScope());
            }

            final Token opResponse = TokenFactory.newToken(scopeType);
            opResponse.setToken(response.getAccessToken());
            opResponse.setRefreshToken(response.getRefreshToken());
            opResponse.setExpiresIn(response.getExpiresIn());
            return opResponse;
        } else {
            LOG.error("Token is blank in response, site: " + rp);
        }
    } else {
        LOG.error("No response from TokenClient");
    }
    throw new RuntimeException("Failed to obtain PAT.");
}
 
Example 17
Source Project: oxAuth   Source File: BaseRequest.java    License: MIT License 5 votes vote down vote up
/**
 * Returns the client credentials encoded using base64.
 *
 * @return The encoded client credentials.
 */
public String getEncodedCredentials() {
    try {
        if (hasCredentials()) {
            return Base64.encodeBase64String(Util.getBytes(getCredentials()));
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    return null;
}
 
Example 18
Source Project: oxAuth   Source File: BaseClient.java    License: MIT License 5 votes vote down vote up
protected void addReqParam(String p_key, String p_value) {
    if (Util.allNotBlank(p_key, p_value)) {
        if (request.getAuthorizationMethod() == AuthorizationMethod.FORM_ENCODED_BODY_PARAMETER) {
            clientRequest.formParameter(p_key, p_value);
        } else {
            clientRequest.queryParameter(p_key, p_value);
        }
    }
}
 
Example 19
Source Project: oxAuth   Source File: EndSessionRequest.java    License: MIT License 5 votes vote down vote up
/**
 * Returns a query string with the parameters of the end session request.
 * Any <code>null</code> or empty parameter will be omitted.
 *
 * @return A query string of parameters.
 */
@Override
public String getQueryString() {
    StringBuilder queryStringBuilder = new StringBuilder();

    try {
        if (StringUtils.isNotBlank(idTokenHint)) {
            queryStringBuilder.append(EndSessionRequestParam.ID_TOKEN_HINT)
                    .append("=")
                    .append(idTokenHint);
        }
        if (StringUtils.isNotBlank(postLogoutRedirectUri)) {
            queryStringBuilder.append("&")
                    .append(EndSessionRequestParam.POST_LOGOUT_REDIRECT_URI)
                    .append("=")
                    .append(URLEncoder.encode(postLogoutRedirectUri, Util.UTF8_STRING_ENCODING));
        }
        if (StringUtils.isNotBlank(state)) {
            queryStringBuilder.append("&")
                    .append(EndSessionRequestParam.STATE)
                    .append("=")
                    .append(URLEncoder.encode(state, Util.UTF8_STRING_ENCODING));
        }

        if (StringUtils.isNotBlank(sessionId)) {
            queryStringBuilder.append("&")
                    .append(EndSessionRequestParam.SESSION_ID)
                    .append("=")
                    .append(URLEncoder.encode(sessionId, Util.UTF8_STRING_ENCODING));
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    return queryStringBuilder.toString();
}
 
Example 20
Source Project: oxAuth   Source File: BaseTest.java    License: MIT License 5 votes vote down vote up
protected void navigateToAuhorizationUrl(WebDriver driver, String authorizationRequestUrl) {
	try {
		driver.navigate().to(URLDecoder.decode(authorizationRequestUrl, Util.UTF8_STRING_ENCODING));
	} catch (UnsupportedEncodingException ex) {
           fail("Failed to decode the authorization URL.");
	}
}
 
Example 21
Source Project: oxAuth   Source File: AbstractPage.java    License: MIT License 5 votes vote down vote up
public void navigate(String url) {
    try {
        final WebDriver driver = config.getDriver();
        output("Navigate URL: " + url);
        //printCookies();
        driver.navigate().to(URLDecoder.decode(url, Util.UTF8_STRING_ENCODING));
    } catch (UnsupportedEncodingException ex) {
        fail("Failed to decode the URL.");
    }
}
 
Example 22
Source Project: oxAuth   Source File: CIBARegisterClientResponseService.java    License: MIT License 5 votes vote down vote up
public void updateResponse(JSONObject responseJsonObject, Client client) {
    try {
        Util.addToJSONObjectIfNotNull(responseJsonObject, BACKCHANNEL_TOKEN_DELIVERY_MODE.toString(), client.getBackchannelTokenDeliveryMode());
        Util.addToJSONObjectIfNotNull(responseJsonObject, BACKCHANNEL_CLIENT_NOTIFICATION_ENDPOINT.toString(), client.getBackchannelClientNotificationEndpoint());
        Util.addToJSONObjectIfNotNull(responseJsonObject, BACKCHANNEL_AUTHENTICATION_REQUEST_SIGNING_ALG.toString(), client.getBackchannelAuthenticationRequestSigningAlg());
        Util.addToJSONObjectIfNotNull(responseJsonObject, BACKCHANNEL_USER_CODE_PARAMETER.toString(), client.getBackchannelUserCodeParameter());
    } catch (JSONException e) {
        log.error("Failed to update response.", e);
    }
}
 
Example 23
Source Project: oxAuth   Source File: EndSessionUtils.java    License: MIT License 5 votes vote down vote up
public static String createFronthannelHtml(Set<String> logoutUris, String postLogoutUrl, String state) {
    String iframes = "";
    for (String logoutUri : logoutUris) {
        iframes = iframes + String.format("<iframe height=\"0\" width=\"0\" src=\"%s\" sandbox=\"allow-same-origin allow-scripts allow-popups allow-forms\"></iframe>", logoutUri);
    }

    String html = "<!DOCTYPE html>" +
            "<html>" +
            "<head>";

    if (!Util.isNullOrEmpty(postLogoutUrl)) {

        if (!Util.isNullOrEmpty(state)) {
            if (postLogoutUrl.contains("?")) {
                postLogoutUrl += "&state=" + state;
            } else {
                postLogoutUrl += "?state=" + state;
            }
        }

        html += "<script>" +
                "window.onload=function() {" +
                "window.location='" + postLogoutUrl + "'" +
                "}" +
                "</script>";
    }

    html += "<title>Your logout was successful</title>" +
            "</head>" +
            "<body>" +
            "Your logout was successful.<br/>" +
            iframes +
            "</body>" +
            "</html>";
    return html;
}
 
Example 24
Source Project: oxAuth   Source File: RegisterParamsValidator.java    License: MIT License 5 votes vote down vote up
public void validateLogoutUri(String logoutUri, List<String> redirectUris, ErrorResponseFactory errorResponseFactory) {
    if (Util.isNullOrEmpty(logoutUri)) { // logout uri is optional so null or empty string is valid
        return;
    }

    // preconditions
    if (redirectUris == null || redirectUris.isEmpty()) {
        log.debug("Preconditions of logout uri validation are failed.");
        throwInvalidLogoutUri(errorResponseFactory);
        return;
    }

    try {
        Set<String> redirectUriHosts = collectUriHosts(redirectUris);

        URI uri = new URI(logoutUri);

        if (!redirectUriHosts.contains(uri.getHost())) {
            log.debug("logout uri host is not within redirect_uris, logout_uri: {}, redirect_uris: {}", logoutUri, redirectUris);
            throwInvalidLogoutUri(errorResponseFactory);
            return;
        }

        if (!HTTPS.equalsIgnoreCase(uri.getScheme())) {
            log.debug("logout uri schema is not https, logout_uri: {}", logoutUri);
            throwInvalidLogoutUri(errorResponseFactory);
        }
    } catch (Exception e) {
        log.debug(e.getMessage(), e);
        throwInvalidLogoutUri(errorResponseFactory);
    }
}
 
Example 25
Source Project: oxAuth   Source File: UserInfoMember.java    License: MIT License 5 votes vote down vote up
public UserInfoMember(JSONObject jsonObject) throws JSONException {
    claims = new ArrayList<Claim>();

    for (Iterator<String> iterator = jsonObject.keys(); iterator.hasNext(); ) {
        String claimName = iterator.next();
        ClaimValue claimValue = null;

        if (jsonObject.isNull(claimName)) {
            claimValue = ClaimValue.createNull();
        } else {
            JSONObject claimValueJsonObject = jsonObject.getJSONObject(claimName);
            if (claimValueJsonObject.has("essential")) {
                boolean essential = claimValueJsonObject.getBoolean("essential");
                claimValue = ClaimValue.createEssential(essential);
            } else if (claimValueJsonObject.has("values")) {
                JSONArray claimValueJsonArray = claimValueJsonObject.getJSONArray("values");
                List<String> claimValueArr = Util.asList(claimValueJsonArray);
                claimValue = ClaimValue.createValueList(claimValueArr);
            }
        }

        Claim claim = new Claim(claimName, claimValue);
        claims.add(claim);
    }

    preferredLocales = new ArrayList<String>();
    if (jsonObject.has("preferred_locales")) {
        JSONArray preferredLocalesJsonArray = jsonObject.getJSONArray("preferred_locales");

        for (int i = 0; i < preferredLocalesJsonArray.length(); i++) {
            preferredLocales.add(preferredLocalesJsonArray.getString(i));
        }
    }
}
 
Example 26
Source Project: oxAuth   Source File: IdTokenMember.java    License: MIT License 5 votes vote down vote up
public IdTokenMember(JSONObject jsonObject) throws JSONException {
    claims = new ArrayList<Claim>();

    for (Iterator<String> iterator = jsonObject.keys(); iterator.hasNext(); ) {
        String claimName = iterator.next();
        ClaimValue claimValue = null;

        if (claimName != null && claimName.equals("max_age") && jsonObject.has("max_age")) {
            maxAge = jsonObject.getInt("max_age");
        } else if (jsonObject.isNull(claimName)) {
            claimValue = ClaimValue.createNull();
        } else {
            JSONObject claimValueJsonObject = jsonObject.getJSONObject(claimName);

            if (claimValueJsonObject.has("values")) {
                JSONArray claimValueJsonArray = claimValueJsonObject.getJSONArray("values");
                List<String> claimValueArr = Util.asList(claimValueJsonArray);
                claimValue = ClaimValue.createValueList(claimValueArr);
            } else if (claimValueJsonObject.has("value")) {
                String value = claimValueJsonObject.getString("value");
                claimValue = ClaimValue.createSingleValue(value);
            }
            if (claimValueJsonObject.has("essential")) {
                final boolean essential = claimValueJsonObject.getBoolean("essential");
                if (claimValue != null) {
                    claimValue.setEssential(essential);
                } else {
                    claimValue = ClaimValue.createEssential(essential);
                }
            }
        }

        Claim claim = new Claim(claimName, claimValue);
        claims.add(claim);
    }
}
 
Example 27
Source Project: oxAuth   Source File: SessionIdService.java    License: MIT License 5 votes vote down vote up
/**
 * By definition we expects space separated acr values as it is defined in spec. But we also try maybe some client
 * sent it to us as json array. So we try both.
 *
 * @return acr value list
 */
public List<String> acrValuesList(String acrValues) {
    List<String> acrs;
    try {
        acrs = Util.jsonArrayStringAsList(acrValues);
    } catch (JSONException ex) {
        acrs = Util.splittedStringAsList(acrValues, " ");
    }

    return acrs;
}
 
Example 28
Source Project: oxAuth   Source File: ExternalScriptContext.java    License: MIT License 5 votes vote down vote up
public boolean isInNetwork(String cidrNotation) {
    final String ip = getIpAddress();
    if (Util.allNotBlank(ip, cidrNotation)) {
        final SubnetUtils utils = new SubnetUtils(cidrNotation);
        return utils.getInfo().isInRange(ip);
    }
    return false;
}
 
Example 29
Source Project: oxAuth   Source File: AuthenticationService.java    License: MIT License 5 votes vote down vote up
public Map<String, String> getExternalScriptExtraParameters(Map<String, String> sessionIdAttributes) {
    String authExternalAttributesString = sessionIdAttributes.get(AUTH_EXTERNAL_ATTRIBUTES);
    Map<String, String> authExternalAttributes = new HashMap<String, String>();
    try {
        authExternalAttributes = Util.jsonObjectArrayStringAsMap(authExternalAttributesString);
    } catch (JSONException ex) {
        log.error("Failed to convert JSON array of auth_external_attributes to Map<String, String>");
    }

    return authExternalAttributes;
}
 
Example 30
Source Project: oxAuth   Source File: AuthenticationService.java    License: MIT License 5 votes vote down vote up
public void setExternalScriptExtraParameters(Map<String, String> sessionIdAttributes,
                                              Map<String, String> authExternalAttributes) {
    String authExternalAttributesString = null;
    try {
        authExternalAttributesString = Util.mapAsString(authExternalAttributes);
    } catch (JSONException ex) {
        log.error("Failed to convert Map<String, String> of auth_external_attributes to JSON array");
    }

    sessionIdAttributes.put(AUTH_EXTERNAL_ATTRIBUTES, authExternalAttributesString);
}