proj_name
stringclasses
131 values
relative_path
stringlengths
30
228
class_name
stringlengths
1
68
func_name
stringlengths
1
48
masked_class
stringlengths
78
9.82k
func_body
stringlengths
46
9.61k
len_input
int64
29
2.01k
len_output
int64
14
1.94k
total
int64
55
2.05k
relevant_context
stringlengths
0
38.4k
pac4j_pac4j
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/credentials/extractor/OAuth20CredentialsExtractor.java
OAuth20CredentialsExtractor
getOAuthCredentials
class OAuth20CredentialsExtractor extends OAuthCredentialsExtractor { /** * <p>Constructor for OAuth20CredentialsExtractor.</p> * * @param configuration a {@link OAuth20Configuration} object * @param client a {@link IndirectClient} object */ public OAuth20CredentialsExtractor(final OAuth20Configuration configuration, final IndirectClient client) { super(configuration, client); } /** {@inheritDoc} */ @Override protected Optional<Credentials> getOAuthCredentials(final WebContext context, final SessionStore sessionStore) {<FILL_FUNCTION_BODY>} }
if (((OAuth20Configuration) configuration).isWithState()) { val stateParameter = context.getRequestParameter(OAuth20Configuration.STATE_REQUEST_PARAMETER); if (stateParameter.isPresent()) { val stateSessionAttributeName = this.client.getStateSessionAttributeName(); val sessionState = (String) sessionStore.get(context, stateSessionAttributeName).orElse(null); // clean from session after retrieving it sessionStore.set(context, stateSessionAttributeName, null); logger.debug("sessionState: {} / stateParameter: {}", sessionState, stateParameter); if (!stateParameter.get().equals(sessionState)) { val message = "State parameter mismatch: session expired or possible threat of cross-site request forgery"; throw new OAuthCredentialsException(message); } } else { val message = "Missing state parameter: session expired or possible threat of cross-site request forgery"; throw new OAuthCredentialsException(message); } } val codeParameter = context.getRequestParameter(OAuth20Configuration.OAUTH_CODE); if (codeParameter.isPresent()) { val code = OAuthEncoder.decode(codeParameter.get()); logger.debug("code: {}", code); return Optional.of(new OAuth20Credentials(code)); } else { logger.debug("No credential found"); return Optional.empty(); }
170
364
534
<methods>public Optional<org.pac4j.core.credentials.Credentials> extract(CallContext) <variables>protected org.pac4j.core.client.IndirectClient client,protected org.pac4j.oauth.config.OAuthConfiguration configuration,protected final org.slf4j.Logger logger
pac4j_pac4j
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/credentials/extractor/OAuthCredentialsExtractor.java
OAuthCredentialsExtractor
extract
class OAuthCredentialsExtractor implements CredentialsExtractor { protected final Logger logger = LoggerFactory.getLogger(getClass()); protected OAuthConfiguration configuration; protected IndirectClient client; /** * <p>Constructor for OAuthCredentialsExtractor.</p> * * @param configuration a {@link OAuthConfiguration} object * @param client a {@link IndirectClient} object */ protected OAuthCredentialsExtractor(final OAuthConfiguration configuration, final IndirectClient client) { CommonHelper.assertNotNull("client", client); CommonHelper.assertNotNull("configuration", configuration); this.configuration = configuration; this.client = client; } /** {@inheritDoc} */ @Override public Optional<Credentials> extract(final CallContext ctx) {<FILL_FUNCTION_BODY>} /** * Get the OAuth credentials from the web context. * * @param context the web context * @param sessionStore the session store * @return the OAuth credentials */ protected abstract Optional<Credentials> getOAuthCredentials(WebContext context, SessionStore sessionStore); }
val webContext = ctx.webContext(); val hasBeenCancelled = (Boolean) configuration.getHasBeenCancelledFactory().apply(webContext); // check if the authentication has been cancelled if (hasBeenCancelled) { logger.debug("authentication has been cancelled by user"); return Optional.empty(); } // check errors try { var errorFound = false; val oauthCredentialsException = new OAuthCredentialsException("Failed to retrieve OAuth credentials, error parameters found"); for (val key : OAuthCredentialsException.ERROR_NAMES) { val value = webContext.getRequestParameter(key); if (value.isPresent()) { errorFound = true; oauthCredentialsException.setErrorMessage(key, value.get()); } } if (errorFound) { throw oauthCredentialsException; } else { return getOAuthCredentials(webContext, ctx.sessionStore()); } } catch (final OAuthException e) { throw new TechnicalException(e); }
293
275
568
<no_super_class>
pac4j_pac4j
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/profile/JsonHelper.java
JsonHelper
getElement
class JsonHelper { private static ObjectMapper mapper; static { mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); } private JsonHelper() {} /** * Return the first node of a JSON response. * * @param text JSON text * @return the first node of the JSON response or null if exception is thrown */ public static JsonNode getFirstNode(final String text) { return getFirstNode(text, null); } /** * Return the first node of a JSON response. * * @param text JSON text * @param path path to find the first node * @return the first node of the JSON response or null if exception is thrown */ public static JsonNode getFirstNode(final String text, final String path) { try { var node = mapper.readValue(text, JsonNode.class); if (path != null) { node = (JsonNode) getElement(node, path); } return node; } catch (final IOException e) { LOGGER.error("Cannot get first node", e); } return null; } /** * Return the field with name in JSON as a string, a boolean, a number or a node. * * @param json json * @param name node name * @return the field */ public static Object getElement(final JsonNode json, final String name) {<FILL_FUNCTION_BODY>} /** * Returns the JSON string for the object. * * @param obj the object * @return the JSON string */ public static String toJSONString(final Object obj) { try { return mapper.writeValueAsString(obj); } catch (final JsonProcessingException e) { LOGGER.error("Cannot to JSON string", e); } return null; } /** * <p>Getter for the field <code>mapper</code>.</p> * * @return a {@link ObjectMapper} object */ public static ObjectMapper getMapper() { return mapper; } }
if (json != null && name != null) { var node = json; for (var nodeName : name.split("\\.")) { if (node != null) { if (nodeName.matches("\\d+")) { node = node.get(Integer.parseInt(nodeName)); } else { node = node.get(nodeName); } } } if (node != null) { if (node.isNumber()) { return node.numberValue(); } else if (node.isBoolean()) { return node.booleanValue(); } else if (node.isTextual()) { return node.textValue(); } else if (node.isNull()) { return null; } else { return node; } } } return null;
573
217
790
<no_super_class>
pac4j_pac4j
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/profile/bitbucket/BitbucketProfileDefinition.java
BitbucketProfileDefinition
extractUserProfile
class BitbucketProfileDefinition extends OAuthProfileDefinition { /** Constant <code>LAST_NAME="last_name"</code> */ public static final String LAST_NAME = "last_name"; /** Constant <code>IS_TEAM="is_team"</code> */ public static final String IS_TEAM = "is_team"; /** Constant <code>AVATAR="avatar"</code> */ public static final String AVATAR = "avatar"; /** Constant <code>RESOURCE_URI="resource_uri"</code> */ public static final String RESOURCE_URI = "resource_uri"; /** * <p>Constructor for BitbucketProfileDefinition.</p> */ public BitbucketProfileDefinition() { super(x -> new BitbucketProfile()); Arrays.stream(new String[] {Pac4jConstants.USERNAME, LAST_NAME}) .forEach(a -> primary(a, Converters.STRING)); primary(IS_TEAM, Converters.BOOLEAN); primary(AVATAR, Converters.URL); primary(RESOURCE_URI, Converters.URL); } /** {@inheritDoc} */ @Override public String getProfileUrl(final Token token, final OAuthConfiguration configuration) { return "https://bitbucket.org/api/1.0/user/"; } /** {@inheritDoc} */ @Override public BitbucketProfile extractUserProfile(final String body) {<FILL_FUNCTION_BODY>} }
val profile = (BitbucketProfile) newProfile(); var json = JsonHelper.getFirstNode(body); if (json != null) { json = (JsonNode) JsonHelper.getElement(json, "user"); if (json != null) { profile.setId(ProfileHelper.sanitizeIdentifier(JsonHelper.getElement(json, Pac4jConstants.USERNAME))); for (val attribute : getPrimaryAttributes()) { convertAndAdd(profile, PROFILE_ATTRIBUTE, attribute, JsonHelper.getElement(json, attribute)); } } else { raiseProfileExtractionJsonError(body, "user"); } } else { raiseProfileExtractionJsonError(body); } return profile;
406
187
593
<methods>public void <init>() ,public void <init>(org.pac4j.core.profile.factory.ProfileFactory) ,public abstract org.pac4j.core.profile.CommonProfile extractUserProfile(java.lang.String) ,public abstract java.lang.String getProfileUrl(com.github.scribejava.core.model.Token, org.pac4j.oauth.config.OAuthConfiguration) ,public com.github.scribejava.core.model.Verb getProfileVerb() <variables>
pac4j_pac4j
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/profile/casoauthwrapper/CasAuthenticationDateFormatter.java
CasAuthenticationDateFormatter
convert
class CasAuthenticationDateFormatter extends DateConverter { /** * <p>Constructor for CasAuthenticationDateFormatter.</p> */ public CasAuthenticationDateFormatter() { super("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); } /** {@inheritDoc} */ @Override public Object convert(final Object attribute) {<FILL_FUNCTION_BODY>} }
var a = attribute; if (a instanceof String s) { var pos = s.lastIndexOf("["); if (pos > 0) { s = s.substring(0, pos); pos = s.lastIndexOf(":"); if (pos > 0) { s = s.substring(0, pos) + s.substring(pos + 1, s.length()); } a = s; } } return super.convert(a);
110
127
237
<methods>public void <init>() ,public void <init>(java.lang.String) ,public void <init>(java.lang.String, java.util.Locale) <variables>protected java.lang.String format,protected java.util.Locale locale
pac4j_pac4j
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/profile/casoauthwrapper/CasOAuthWrapperProfileDefinition.java
CasOAuthWrapperProfileDefinition
extractUserProfile
class CasOAuthWrapperProfileDefinition extends OAuthProfileDefinition { private static final String ID = "id"; /** Constant <code>IS_FROM_NEW_LOGIN="isFromNewLogin"</code> */ public static final String IS_FROM_NEW_LOGIN = "isFromNewLogin"; /** Constant <code>AUTHENTICATION_DATE="authenticationDate"</code> */ public static final String AUTHENTICATION_DATE = "authenticationDate"; /** Constant <code>AUTHENTICATION_METHOD="authenticationMethod"</code> */ public static final String AUTHENTICATION_METHOD = "authenticationMethod"; /** Constant <code>SUCCESSFUL_AUTHENTICATION_HANDLERS="successfulAuthenticationHandlers"</code> */ public static final String SUCCESSFUL_AUTHENTICATION_HANDLERS = "successfulAuthenticationHandlers"; /** Constant <code>LONG_TERM_AUTHENTICATION_REQUEST_TOKEN_USED="longTermAuthenticationRequestTokenUsed"</code> */ public static final String LONG_TERM_AUTHENTICATION_REQUEST_TOKEN_USED = "longTermAuthenticationRequestTokenUsed"; /** * <p>Constructor for CasOAuthWrapperProfileDefinition.</p> */ public CasOAuthWrapperProfileDefinition() { super(x -> new CasOAuthWrapperProfile()); primary(IS_FROM_NEW_LOGIN, Converters.BOOLEAN); primary(AUTHENTICATION_DATE, new CasAuthenticationDateFormatter()); primary(AUTHENTICATION_METHOD, Converters.STRING); primary(SUCCESSFUL_AUTHENTICATION_HANDLERS, Converters.STRING); primary(LONG_TERM_AUTHENTICATION_REQUEST_TOKEN_USED, Converters.BOOLEAN); } /** {@inheritDoc} */ @Override public String getProfileUrl(final Token accessToken, final OAuthConfiguration configuration) { return ((CasOAuthWrapperApi20) configuration.getApi()).getCasServerUrl() + "/profile"; } /** {@inheritDoc} */ @Override public CasOAuthWrapperProfile extractUserProfile(final String body) {<FILL_FUNCTION_BODY>} protected void extractAttributes(final JsonNode json, final CasOAuthWrapperProfile profile) { // CAS <= v4.2 if (json instanceof ArrayNode) { val nodes = json.iterator(); while (nodes.hasNext()) { val nextNode = nodes.next(); val attribute = nextNode.fieldNames().next(); if (!ID.equals(attribute)) { convertAndAdd(profile, PROFILE_ATTRIBUTE, attribute, JsonHelper.getElement(nextNode, attribute)); } } // CAS v5 } else if (json instanceof ObjectNode) { val keys = json.fieldNames(); while (keys.hasNext()) { val key = keys.next(); if (!ID.equals(key)) { convertAndAdd(profile, PROFILE_ATTRIBUTE, key, JsonHelper.getElement(json, key)); } } } } }
val profile = (CasOAuthWrapperProfile) newProfile(); var json = JsonHelper.getFirstNode(body); if (json != null) { profile.setId(ProfileHelper.sanitizeIdentifier(JsonHelper.getElement(json, ID))); val attributes = json.get("attributes"); if (attributes != null) { extractAttributes(attributes, profile); } else { // flatten profiles extractAttributes(json, profile); } } else { raiseProfileExtractionJsonError(body); } return profile;
801
145
946
<methods>public void <init>() ,public void <init>(org.pac4j.core.profile.factory.ProfileFactory) ,public abstract org.pac4j.core.profile.CommonProfile extractUserProfile(java.lang.String) ,public abstract java.lang.String getProfileUrl(com.github.scribejava.core.model.Token, org.pac4j.oauth.config.OAuthConfiguration) ,public com.github.scribejava.core.model.Verb getProfileVerb() <variables>
pac4j_pac4j
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/profile/converter/JsonConverter.java
JsonConverter
convert
class JsonConverter implements AttributeConverter { private final Class<? extends Object> clazz; private TypeReference<? extends Object> typeReference; /** * <p>Constructor for JsonConverter.</p> * * @param clazz a {@link Class} object */ public JsonConverter(final Class<? extends Object> clazz) { this.clazz = clazz; } /** * <p>Constructor for JsonConverter.</p> * * @param clazz a {@link Class} object * @param typeReference a {@link TypeReference} object */ public JsonConverter(final Class<? extends Object> clazz, final TypeReference<? extends Object> typeReference) { this(clazz); this.typeReference = typeReference; } /** {@inheritDoc} */ @Override public Object convert(final Object attribute) {<FILL_FUNCTION_BODY>} }
if (attribute != null) { if (clazz.isAssignableFrom(attribute.getClass())) { return attribute; } else if (attribute instanceof String || attribute instanceof JsonNode) { final String s; if (attribute instanceof String) { s = (String) attribute; } else { s = JsonHelper.toJSONString(attribute); } try { if (typeReference != null) { return JsonHelper.getMapper().readValue(s, typeReference); } else { return JsonHelper.getMapper().readValue(s, clazz); } } catch (final IOException e) { LOGGER.error("Cannot read value", e); } } } return null;
243
193
436
<no_super_class>
pac4j_pac4j
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/profile/creator/OAuth10ProfileCreator.java
OAuth10ProfileCreator
getAccessToken
class OAuth10ProfileCreator extends OAuthProfileCreator { /** * <p>Constructor for OAuth10ProfileCreator.</p> * * @param configuration a {@link OAuth10Configuration} object * @param client a {@link IndirectClient} object */ public OAuth10ProfileCreator(final OAuth10Configuration configuration, final IndirectClient client) { super(configuration, client); } /** {@inheritDoc} */ @Override protected OAuth1AccessToken getAccessToken(final Credentials credentials) {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override protected void addTokenToProfile(final UserProfile userProfile, final Token tok) { val profile = (OAuth10Profile) userProfile; val accessToken = (OAuth1AccessToken) tok; if (profile != null) { val token = accessToken.getToken(); logger.debug("add access_token: {} to profile", token); profile.setAccessToken(token); profile.setAccessSecret(accessToken.getTokenSecret()); } } /** {@inheritDoc} */ @Override protected void signRequest(final OAuthService service, final Token tok, final OAuthRequest request) { val token = (OAuth1AccessToken) tok; ((OAuth10aService) service).signRequest(token, request); if (this.configuration.isTokenAsHeader()) { request.addHeader("Authorization", "Bearer " + token.getToken()); } } }
// we assume the access token only has been passed: it can be a bearer call (HTTP client) if (credentials instanceof TokenCredentials) { val accessToken = ((TokenCredentials) credentials).getToken(); return new OAuth1AccessToken(accessToken, null); } // regular OAuth flow return ((OAuth10Credentials) credentials).getAccessToken();
403
98
501
<methods>public Optional<org.pac4j.core.profile.UserProfile> create(CallContext, org.pac4j.core.credentials.Credentials) <variables>protected org.pac4j.core.client.IndirectClient client,protected org.pac4j.oauth.config.OAuthConfiguration configuration,protected final org.slf4j.Logger logger,protected static final non-sealed com.fasterxml.jackson.databind.ObjectMapper mapper
pac4j_pac4j
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/profile/creator/OAuth20ProfileCreator.java
OAuth20ProfileCreator
getAccessToken
class OAuth20ProfileCreator extends OAuthProfileCreator { /** * <p>Constructor for OAuth20ProfileCreator.</p> * * @param configuration a {@link OAuth20Configuration} object * @param client a {@link IndirectClient} object */ public OAuth20ProfileCreator(final OAuth20Configuration configuration, final IndirectClient client) { super(configuration, client); } /** {@inheritDoc} */ @Override protected OAuth2AccessToken getAccessToken(final Credentials credentials) {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override protected void addTokenToProfile(final UserProfile profile, final Token token) { if (profile != null) { val oauth2Token = (OAuth2AccessToken) token; val accessToken = oauth2Token.getAccessToken(); logger.debug("add access_token: {} to profile", accessToken); ((OAuth20Profile) profile).setAccessToken(accessToken); ((OAuth20Profile) profile).setRefreshToken(oauth2Token.getRefreshToken()); } } /** {@inheritDoc} */ @Override protected void signRequest(final OAuthService service, final Token token, final OAuthRequest request) { ((OAuth20Service) service).signRequest((OAuth2AccessToken) token, request); val accessToken = ((OAuth2AccessToken) token).getAccessToken(); if (this.configuration.isTokenAsHeader()) { request.addHeader(HttpConstants.AUTHORIZATION_HEADER, HttpConstants.BEARER_HEADER_PREFIX + accessToken); } if (Verb.POST.equals(request.getVerb())) { request.addParameter(OAuthConfiguration.OAUTH_TOKEN, accessToken); } } }
// we assume the access token only has been passed: it can be a bearer call (HTTP client) if (credentials instanceof TokenCredentials) { val accessToken = ((TokenCredentials) credentials).getToken(); return new OAuth2AccessToken(accessToken); } // regular OAuth flow return ((OAuth20Credentials) credentials).getAccessToken();
479
96
575
<methods>public Optional<org.pac4j.core.profile.UserProfile> create(CallContext, org.pac4j.core.credentials.Credentials) <variables>protected org.pac4j.core.client.IndirectClient client,protected org.pac4j.oauth.config.OAuthConfiguration configuration,protected final org.slf4j.Logger logger,protected static final non-sealed com.fasterxml.jackson.databind.ObjectMapper mapper
pac4j_pac4j
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/profile/creator/OAuthProfileCreator.java
OAuthProfileCreator
create
class OAuthProfileCreator implements ProfileCreator { protected final Logger logger = LoggerFactory.getLogger(getClass()); /** Constant <code>mapper</code> */ protected static final ObjectMapper mapper; static { mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); } protected OAuthConfiguration configuration; protected IndirectClient client; /** * <p>Constructor for OAuthProfileCreator.</p> * * @param configuration a {@link OAuthConfiguration} object * @param client a {@link IndirectClient} object */ protected OAuthProfileCreator(final OAuthConfiguration configuration, final IndirectClient client) { CommonHelper.assertNotNull("client", client); CommonHelper.assertNotNull("configuration", configuration); this.configuration = configuration; this.client = client; } /** {@inheritDoc} */ @Override public Optional<UserProfile> create(final CallContext ctx, final Credentials credentials) {<FILL_FUNCTION_BODY>} /** * Get the access token from OAuth credentials. * * @param credentials credentials * @return the access token */ protected abstract Token getAccessToken(final Credentials credentials); /** * Retrieve the user profile from the access token. * * @param context the web context * @param accessToken the access token * @return the user profile */ protected Optional<UserProfile> retrieveUserProfileFromToken(final WebContext context, final Token accessToken) { val profileDefinition = configuration.getProfileDefinition(); val profileUrl = profileDefinition.getProfileUrl(accessToken, configuration); val service = this.configuration.buildService(context, client); val body = sendRequestForData(service, accessToken, profileUrl, profileDefinition.getProfileVerb()); logger.info("UserProfile: " + body); if (body == null) { throw new HttpCommunicationException("No data found for accessToken: " + accessToken); } final UserProfile profile = configuration.getProfileDefinition().extractUserProfile(body); addTokenToProfile(profile, accessToken); return Optional.of(profile); } /** * Make a request to get the data of the authenticated user for the provider. * * @param service the OAuth service * @param accessToken the access token * @param dataUrl url of the data * @param verb method used to request data * @return the user data response */ protected String sendRequestForData(final OAuthService service, final Token accessToken, final String dataUrl, Verb verb) { logger.debug("accessToken: {} / dataUrl: {}", accessToken, dataUrl); val t0 = System.currentTimeMillis(); val request = createOAuthRequest(dataUrl, verb); signRequest(service, accessToken, request); final String body; final int code; try { var response = service.execute(request); code = response.getCode(); body = response.getBody(); } catch (final IOException | InterruptedException | ExecutionException e) { throw new HttpCommunicationException("Error getting body: " + e.getMessage()); } val t1 = System.currentTimeMillis(); logger.debug("Request took: " + (t1 - t0) + " ms for: " + dataUrl); logger.debug("response code: {} / response body: {}", code, body); if (code != 200) { throw new HttpCommunicationException(code, body); } return body; } /** * Sign the request. * * @param service the service * @param token the token * @param request the request */ protected abstract void signRequest(OAuthService service, Token token, OAuthRequest request); /** * Create an OAuth request. * * @param url the url to call * @param verb method used to create the request * @return the request */ protected OAuthRequest createOAuthRequest(final String url, final Verb verb) { return new OAuthRequest(verb, url); } /** * Add the access token to the profile (as an attribute). * * @param profile the user profile * @param accessToken the access token */ protected abstract void addTokenToProfile(final UserProfile profile, final Token accessToken); }
try { val token = getAccessToken(credentials); return retrieveUserProfileFromToken(ctx.webContext(), token); } catch (final OAuthException e) { throw new TechnicalException(e); }
1,152
59
1,211
<no_super_class>
pac4j_pac4j
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/profile/cronofy/CronofyProfileCreator.java
CronofyProfileCreator
retrieveUserProfileFromToken
class CronofyProfileCreator extends OAuth20ProfileCreator { /** * <p>Constructor for CronofyProfileCreator.</p> * * @param configuration a {@link OAuth20Configuration} object * @param client a {@link IndirectClient} object */ public CronofyProfileCreator(final OAuth20Configuration configuration, final IndirectClient client) { super(configuration, client); } /** {@inheritDoc} */ protected Optional<UserProfile> retrieveUserProfileFromToken(final WebContext context, final Token accessToken) {<FILL_FUNCTION_BODY>} }
final UserProfile profile = configuration.getProfileDefinition().extractUserProfile(accessToken.getRawResponse()); addTokenToProfile(profile, accessToken); return Optional.of(profile);
164
49
213
<methods>public void <init>(org.pac4j.oauth.config.OAuth20Configuration, org.pac4j.core.client.IndirectClient) <variables>
pac4j_pac4j
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/profile/cronofy/CronofyProfileDefinition.java
CronofyProfileDefinition
extractUserProfile
class CronofyProfileDefinition extends OAuthProfileDefinition { /** Constant <code>SUB="sub"</code> */ public static final String SUB = "sub"; /** Constant <code>ACCOUNT_ID="account_id"</code> */ public static final String ACCOUNT_ID = "account_id"; /** Constant <code>PROVIDER_NAME="provider_name"</code> */ public static final String PROVIDER_NAME = "provider_name"; /** Constant <code>PROFILE_ID="profile_id"</code> */ public static final String PROFILE_ID = "profile_id"; /** Constant <code>PROFILE_NAME="profile_name"</code> */ public static final String PROFILE_NAME = "profile_name"; /** Constant <code>PROVIDER_SERVICE="provider_service"</code> */ public static final String PROVIDER_SERVICE = "provider_service"; /** * <p>Constructor for CronofyProfileDefinition.</p> */ public CronofyProfileDefinition() { super(x -> new CronofyProfile()); Arrays.stream(new String[] {ACCOUNT_ID, PROVIDER_NAME, PROFILE_ID, PROFILE_NAME, PROVIDER_SERVICE}) .forEach(a -> primary(a, Converters.STRING)); } /** {@inheritDoc} */ @Override public String getProfileUrl(final Token accessToken, final OAuthConfiguration configuration) { return null; } /** {@inheritDoc} */ @Override public CronofyProfile extractUserProfile(final String body) {<FILL_FUNCTION_BODY>} }
val profile = (CronofyProfile) newProfile(); val json = JsonHelper.getFirstNode(body); if (json != null) { profile.setId(ProfileHelper.sanitizeIdentifier(JsonHelper.getElement(json, SUB))); convertAndAdd(profile, PROFILE_ATTRIBUTE, ACCOUNT_ID, JsonHelper.getElement(json, ACCOUNT_ID)); val linkingProfile = (JsonNode) JsonHelper.getElement(json, "linking_profile"); if (linkingProfile != null) { convertAndAdd(profile, PROFILE_ATTRIBUTE, PROVIDER_NAME, JsonHelper.getElement(linkingProfile, PROVIDER_NAME)); convertAndAdd(profile, PROFILE_ATTRIBUTE, PROFILE_ID, JsonHelper.getElement(linkingProfile, PROFILE_ID)); convertAndAdd(profile, PROFILE_ATTRIBUTE, PROFILE_NAME, JsonHelper.getElement(linkingProfile, PROFILE_NAME)); convertAndAdd(profile, PROFILE_ATTRIBUTE, PROVIDER_SERVICE, JsonHelper.getElement(linkingProfile, PROVIDER_SERVICE)); } } else { raiseProfileExtractionJsonError(body); } return profile;
437
304
741
<methods>public void <init>() ,public void <init>(org.pac4j.core.profile.factory.ProfileFactory) ,public abstract org.pac4j.core.profile.CommonProfile extractUserProfile(java.lang.String) ,public abstract java.lang.String getProfileUrl(com.github.scribejava.core.model.Token, org.pac4j.oauth.config.OAuthConfiguration) ,public com.github.scribejava.core.model.Verb getProfileVerb() <variables>
pac4j_pac4j
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/profile/definition/OAuthProfileDefinition.java
OAuthProfileDefinition
raiseProfileExtractionJsonError
class OAuthProfileDefinition extends CommonProfileDefinition { /** * <p>Constructor for OAuthProfileDefinition.</p> */ public OAuthProfileDefinition() { super(); } /** * <p>Constructor for OAuthProfileDefinition.</p> * * @param profileFactory a {@link ProfileFactory} object */ public OAuthProfileDefinition(final ProfileFactory profileFactory) { super(profileFactory); } /** * Get HTTP Method to request profile. * * @return http verb */ public Verb getProfileVerb() { return Verb.GET; } /** * Retrieve the url of the profile of the authenticated user for the provider. * * @param accessToken only used when constructing dynamic urls from data in the token * @param configuration the current configuration * @return the url of the user profile given by the provider */ public abstract String getProfileUrl(Token accessToken, OAuthConfiguration configuration); /** * Extract the user profile from the response (JSON, XML...) of the profile url. * * @param body the response body * @return the returned profile */ public abstract CommonProfile extractUserProfile(String body); /** * Throws a {@link TechnicalException} to indicate that user profile extraction has failed. * * @param body the request body that the user profile should be have been extracted from * @param missingNode the name of a JSON node that was found missing. may be omitted */ protected void raiseProfileExtractionJsonError(String body, String missingNode) { logger.error("Unable to extract user profile as no JSON node '{}' was found in body: {}", missingNode, body); throw new TechnicalException("No JSON node '" + missingNode + "' to extract user profile from"); } /** * Throws a {@link TechnicalException} to indicate that user profile extraction has failed. * * @param body the request body that the user profile should have been extracted from */ protected void raiseProfileExtractionJsonError(String body) {<FILL_FUNCTION_BODY>} /** * Throws a {@link TechnicalException} to indicate that user profile extraction has failed. * * @param body the request body that the user profile should have been extracted from */ protected void raiseProfileExtractionError(String body) { logger.error("Unable to extract user profile from body: {}", body); throw new TechnicalException("Unable to extract user profile"); } }
logger.error("Unable to extract user profile as no JSON node was found in body: {}", body); throw new TechnicalException("No JSON node to extract user profile from");
638
44
682
<methods>public void <init>() ,public void <init>(org.pac4j.core.profile.factory.ProfileFactory) <variables>public static final java.lang.String DISPLAY_NAME,public static final java.lang.String EMAIL,public static final java.lang.String FAMILY_NAME,public static final java.lang.String FIRST_NAME,public static final java.lang.String GENDER,public static final java.lang.String LOCALE,public static final java.lang.String LOCATION,public static final java.lang.String PICTURE_URL,public static final java.lang.String PROFILE_URL
pac4j_pac4j
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/profile/dropbox/DropBoxProfileDefinition.java
DropBoxProfileDefinition
extractUserProfile
class DropBoxProfileDefinition extends OAuthProfileDefinition { /** Constant <code>REFERRAL_LINK="referral_link"</code> */ public static final String REFERRAL_LINK = "referral_link"; /** Constant <code>COUNTRY="country"</code> */ public static final String COUNTRY = "country"; /** Constant <code>EMAIL_VERIFIED="email_verified"</code> */ public static final String EMAIL_VERIFIED = "email_verified"; /** * <p>Constructor for DropBoxProfileDefinition.</p> */ public DropBoxProfileDefinition() { super(x -> new DropBoxProfile()); primary(REFERRAL_LINK, Converters.STRING); primary(COUNTRY, Converters.LOCALE); primary(REFERRAL_LINK, Converters.URL); primary(EMAIL, Converters.STRING); primary(EMAIL_VERIFIED, Converters.BOOLEAN); } /** {@inheritDoc} */ @Override public String getProfileUrl(final Token token, final OAuthConfiguration configuration) { return "https://api.dropboxapi.com/2/users/get_current_account"; } /** {@inheritDoc} */ @Override public Verb getProfileVerb() { return Verb.POST; } /** {@inheritDoc} */ @Override public DropBoxProfile extractUserProfile(final String body) {<FILL_FUNCTION_BODY>} }
val profile = (DropBoxProfile) newProfile(); var json = JsonHelper.getFirstNode(body); if (json != null) { profile.setId(ProfileHelper.sanitizeIdentifier(JsonHelper.getElement(json, "account_id"))); for (val attribute : getPrimaryAttributes()) { convertAndAdd(profile, PROFILE_ATTRIBUTE, attribute, JsonHelper.getElement(json, attribute)); } json = (JsonNode) JsonHelper.getElement(json, "name"); if (json != null) { convertAndAdd(profile, PROFILE_ATTRIBUTE, FIRST_NAME, JsonHelper.getElement(json, "familiar_name")); convertAndAdd(profile, PROFILE_ATTRIBUTE, FAMILY_NAME, JsonHelper.getElement(json, "surname")); convertAndAdd(profile, PROFILE_ATTRIBUTE, DISPLAY_NAME, JsonHelper.getElement(json, "display_name")); } } else { raiseProfileExtractionJsonError(body); } return profile;
407
265
672
<methods>public void <init>() ,public void <init>(org.pac4j.core.profile.factory.ProfileFactory) ,public abstract org.pac4j.core.profile.CommonProfile extractUserProfile(java.lang.String) ,public abstract java.lang.String getProfileUrl(com.github.scribejava.core.model.Token, org.pac4j.oauth.config.OAuthConfiguration) ,public com.github.scribejava.core.model.Verb getProfileVerb() <variables>
pac4j_pac4j
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/profile/facebook/FacebookProfileCreator.java
FacebookProfileCreator
addExchangeToken
class FacebookProfileCreator extends OAuth20ProfileCreator { private static final String EXCHANGE_TOKEN_URL = "https://graph.facebook.com/v2.8/oauth/access_token?grant_type=fb_exchange_token"; private static final String EXCHANGE_TOKEN_PARAMETER = "fb_exchange_token"; /** * <p>Constructor for FacebookProfileCreator.</p> * * @param configuration a {@link OAuth20Configuration} object * @param client a {@link IndirectClient} object */ public FacebookProfileCreator(final OAuth20Configuration configuration, final IndirectClient client) { super(configuration, client); } /** {@inheritDoc} */ @Override protected Optional<UserProfile> retrieveUserProfileFromToken(final WebContext context, final Token accessToken) { val profileDefinition = configuration.getProfileDefinition(); val facebookConfiguration = (FacebookConfiguration) configuration; val profileUrl = profileDefinition.getProfileUrl(accessToken, configuration); val service = (OAuth20Service) this.configuration.buildService(context, client); var body = sendRequestForData(service, accessToken, profileUrl, Verb.GET); if (body == null) { throw new HttpCommunicationException("Not data found for accessToken: " + accessToken); } UserProfile profile = (FacebookProfile) profileDefinition.extractUserProfile(body); addTokenToProfile(profile, accessToken); if (profile != null && facebookConfiguration.isRequiresExtendedToken()) { var url = CommonHelper.addParameter(EXCHANGE_TOKEN_URL, OAuthConstants.CLIENT_ID, configuration.getKey()); url = CommonHelper.addParameter(url, OAuthConstants.CLIENT_SECRET, configuration.getSecret()); url = addExchangeToken(url, (OAuth2AccessToken) accessToken); val request = createOAuthRequest(url, Verb.GET); val t0 = System.currentTimeMillis(); final Response response; final int code; try { response = service.execute(request); body = response.getBody(); code = response.getCode(); } catch (final IOException | InterruptedException | ExecutionException e) { throw new HttpCommunicationException("Error getting body:" + e.getMessage()); } val t1 = System.currentTimeMillis(); logger.debug("Request took: " + (t1 - t0) + " ms for: " + url); logger.debug("response code: {} / response body: {}", code, body); if (code == 200) { logger.debug("Retrieve extended token from {}", body); final OAuth2AccessToken extendedAccessToken; try { extendedAccessToken = ((DefaultApi20) configuration.getApi()).getAccessTokenExtractor().extract(response); } catch (IOException | OAuthException ex) { throw new HttpCommunicationException("Error extracting token: " + ex.getMessage()); } logger.debug("Extended token: {}", extendedAccessToken); addTokenToProfile(profile, extendedAccessToken); } else { logger.error("Cannot get extended token: {} / {}", code, body); } } return Optional.of(profile); } /** * Adds the token to the URL in question. If we require appsecret_proof, then this method * will also add the appsecret_proof parameter to the URL, as Facebook expects. * * @param url the URL to modify * @param accessToken the token we're passing back and forth * @return url with additional parameter(s) */ protected String addExchangeToken(final String url, final OAuth2AccessToken accessToken) {<FILL_FUNCTION_BODY>} }
val profileDefinition = (FacebookProfileDefinition) configuration.getProfileDefinition(); val facebookConfiguration = (FacebookConfiguration) configuration; var computedUrl = url; if (facebookConfiguration.isUseAppsecretProof()) { computedUrl = profileDefinition.computeAppSecretProof(computedUrl, accessToken, facebookConfiguration); } return CommonHelper.addParameter(computedUrl, EXCHANGE_TOKEN_PARAMETER, accessToken.getAccessToken());
966
116
1,082
<methods>public void <init>(org.pac4j.oauth.config.OAuth20Configuration, org.pac4j.core.client.IndirectClient) <variables>
pac4j_pac4j
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/profile/facebook/converter/FacebookRelationshipStatusConverter.java
FacebookRelationshipStatusConverter
convert
class FacebookRelationshipStatusConverter implements AttributeConverter { /** {@inheritDoc} */ @Override public FacebookRelationshipStatus convert(final Object attribute) {<FILL_FUNCTION_BODY>} }
if (attribute != null) { if (attribute instanceof String) { var s = ((String) attribute).toLowerCase(); s = s.replaceAll("_", " "); s = s.replaceAll("'", Pac4jConstants.EMPTY_STRING); if ("single".equals(s)) { return FacebookRelationshipStatus.SINGLE; } else if ("in a relationship".equals(s)) { return FacebookRelationshipStatus.IN_A_RELATIONSHIP; } else if ("engaged".equals(s)) { return FacebookRelationshipStatus.ENGAGED; } else if ("married".equals(s)) { return FacebookRelationshipStatus.MARRIED; } else if ("its complicated".equals(s)) { return FacebookRelationshipStatus.ITS_COMPLICATED; } else if ("in an open relationship".equals(s)) { return FacebookRelationshipStatus.IN_AN_OPEN_RELATIONSHIP; } else if ("widowed".equals(s)) { return FacebookRelationshipStatus.WIDOWED; } else if ("separated".equals(s)) { return FacebookRelationshipStatus.SEPARATED; } else if ("divorced".equals(s)) { return FacebookRelationshipStatus.DIVORCED; } else if ("in a civil union".equals(s)) { return FacebookRelationshipStatus.IN_A_CIVIL_UNION; } else if ("in a domestic partnership".equals(s)) { return FacebookRelationshipStatus.IN_A_DOMESTIC_PARTNERSHIP; } } else if (attribute instanceof FacebookRelationshipStatus) { return (FacebookRelationshipStatus) attribute; } } return null;
55
454
509
<no_super_class>
pac4j_pac4j
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/profile/figshare/FigShareProfileDefinition.java
FigShareProfileDefinition
extractUserProfile
class FigShareProfileDefinition extends OAuthProfileDefinition { /** Constant <code>LAST_NAME="last_name"</code> */ public static final String LAST_NAME = "last_name"; /** * <p>Constructor for FigShareProfileDefinition.</p> */ public FigShareProfileDefinition() { super(x -> new FigShareProfile()); primary(LAST_NAME, Converters.STRING); } /** {@inheritDoc} */ @Override public String getProfileUrl(final Token accessToken, final OAuthConfiguration configuration) { return "https://api.figshare.com/v2/account"; } /** {@inheritDoc} */ @Override public FigShareProfile extractUserProfile(final String body) {<FILL_FUNCTION_BODY>} }
val profile = (FigShareProfile) newProfile(); val json = JsonHelper.getFirstNode(body); if (json != null) { if (getProfileId() != null) { profile.setId(ProfileHelper.sanitizeIdentifier(JsonHelper.getElement(json, getProfileId()))); } for (val attribute : getPrimaryAttributes()) { convertAndAdd(profile, PROFILE_ATTRIBUTE, attribute, JsonHelper.getElement(json, attribute)); } } else { raiseProfileExtractionJsonError(body); } return profile;
210
149
359
<methods>public void <init>() ,public void <init>(org.pac4j.core.profile.factory.ProfileFactory) ,public abstract org.pac4j.core.profile.CommonProfile extractUserProfile(java.lang.String) ,public abstract java.lang.String getProfileUrl(com.github.scribejava.core.model.Token, org.pac4j.oauth.config.OAuthConfiguration) ,public com.github.scribejava.core.model.Verb getProfileVerb() <variables>
pac4j_pac4j
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/profile/foursquare/FoursquareProfileDefinition.java
FoursquareProfileDefinition
extractUserProfile
class FoursquareProfileDefinition extends OAuthProfileDefinition { /** Constant <code>FIRST_NAME="firstName"</code> */ public static final String FIRST_NAME = "firstName"; /** Constant <code>LAST_NAME="lastName"</code> */ public static final String LAST_NAME = "lastName"; /** Constant <code>PHOTO="photo"</code> */ public static final String PHOTO = "photo"; /** Constant <code>FIRENDS="friends"</code> */ public static final String FIRENDS = "friends"; /** Constant <code>HOME_CITY="homeCity"</code> */ public static final String HOME_CITY = "homeCity"; /** Constant <code>CONTACT="contact"</code> */ public static final String CONTACT = "contact"; /** Constant <code>BIO="bio"</code> */ public static final String BIO = "bio"; /** * <p>Constructor for FoursquareProfileDefinition.</p> */ public FoursquareProfileDefinition() { super(x -> new FoursquareProfile()); Arrays.stream(new String[] { FIRST_NAME, LAST_NAME, HOME_CITY, BIO, PHOTO }).forEach(a -> primary(a, Converters.STRING)); primary(GENDER, Converters.GENDER); primary(FIRENDS, new JsonConverter(FoursquareUserFriends.class)); primary(CONTACT, new JsonConverter(FoursquareUserContact.class)); primary(PHOTO, new JsonConverter(FoursquareUserPhoto.class)); } /** {@inheritDoc} */ @Override public String getProfileUrl(final Token accessToken, final OAuthConfiguration configuration) { return "https://api.foursquare.com/v2/users/self?v=20131118"; } /** {@inheritDoc} */ @Override public FoursquareProfile extractUserProfile(String body) {<FILL_FUNCTION_BODY>} }
var profile = (FoursquareProfile) newProfile(); var json = JsonHelper.getFirstNode(body); if (json == null) { raiseProfileExtractionJsonError(body); } var response = (JsonNode) JsonHelper.getElement(json, "response"); if (response == null) { raiseProfileExtractionJsonError(body, "response"); } var user = (JsonNode) JsonHelper.getElement(response, "user"); if (user != null) { profile.setId(ProfileHelper.sanitizeIdentifier(JsonHelper.getElement(user, "id"))); for (val attribute : getPrimaryAttributes()) { convertAndAdd(profile, PROFILE_ATTRIBUTE, attribute, JsonHelper.getElement(user, attribute)); } } else { raiseProfileExtractionJsonError(body, "user"); } return profile;
546
224
770
<methods>public void <init>() ,public void <init>(org.pac4j.core.profile.factory.ProfileFactory) ,public abstract org.pac4j.core.profile.CommonProfile extractUserProfile(java.lang.String) ,public abstract java.lang.String getProfileUrl(com.github.scribejava.core.model.Token, org.pac4j.oauth.config.OAuthConfiguration) ,public com.github.scribejava.core.model.Verb getProfileVerb() <variables>
pac4j_pac4j
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/profile/generic/GenericOAuth20ProfileDefinition.java
GenericOAuth20ProfileDefinition
extractUserProfile
class GenericOAuth20ProfileDefinition extends OAuthProfileDefinition { private final Map<String,String> profileAttributes = new HashMap<>(); private String profileUrl = null; private Verb profileVerb = null; private String firstNodePath = null; /** * <p>Setter for the field <code>profileVerb</code>.</p> * * @param value a {@link Verb} object */ public void setProfileVerb(final Verb value) { this.profileVerb = value; } /** {@inheritDoc} */ @Override public Verb getProfileVerb() { if (profileVerb != null) { return this.profileVerb; } else { return super.getProfileVerb(); } } /** * <p>Setter for the field <code>profileUrl</code>.</p> * * @param profileUrl a {@link String} object */ public void setProfileUrl(final String profileUrl) { this.profileUrl = profileUrl; } /** {@inheritDoc} */ @Override public String getProfileUrl(final Token accessToken, final OAuthConfiguration configuration) { return profileUrl; } /** {@inheritDoc} */ @Override public OAuth20Profile extractUserProfile(final String body) {<FILL_FUNCTION_BODY>} /** * <p>Getter for the field <code>profileAttributes</code>.</p> * * @return a {@link Map} object */ public Map<String, String> getProfileAttributes() { return this.profileAttributes; } /** * Add an attribute as a primary one and its converter. * * @param name name of the attribute * @param converter converter */ public void profileAttribute(final String name, final AttributeConverter converter) { profileAttribute(name, name, converter); } /** * Add an attribute as a primary one and its converter. * * @param name name of the attribute * @param tag json reference * @param converter converter */ public void profileAttribute(final String name, String tag, final AttributeConverter converter) { profileAttributes.put(name, tag); getConverters().put(name, Objects.requireNonNullElseGet(converter, StringConverter::new)); } /** * <p>Getter for the field <code>firstNodePath</code>.</p> * * @return a {@link String} object */ public String getFirstNodePath() { return firstNodePath; } /** * <p>Setter for the field <code>firstNodePath</code>.</p> * * @param firstNodePath a {@link String} object */ public void setFirstNodePath(final String firstNodePath) { this.firstNodePath = firstNodePath; } }
val profile = new OAuth20Profile(); val json = JsonHelper.getFirstNode(body, getFirstNodePath()); if (json != null) { profile.setId(ProfileHelper.sanitizeIdentifier(JsonHelper.getElement(json, getProfileId()))); for (val attribute : getPrimaryAttributes()) { convertAndAdd(profile, PROFILE_ATTRIBUTE, attribute, JsonHelper.getElement(json, attribute)); } for (val attribute : getSecondaryAttributes()) { convertAndAdd(profile, PROFILE_ATTRIBUTE, attribute, JsonHelper.getElement(json, attribute)); } for (val entry : getProfileAttributes().entrySet()) { val key = entry.getKey(); val value = entry.getValue(); convertAndAdd(profile, PROFILE_ATTRIBUTE, key, JsonHelper.getElement(json, value)); } } else { raiseProfileExtractionJsonError(body); } return profile;
768
243
1,011
<methods>public void <init>() ,public void <init>(org.pac4j.core.profile.factory.ProfileFactory) ,public abstract org.pac4j.core.profile.CommonProfile extractUserProfile(java.lang.String) ,public abstract java.lang.String getProfileUrl(com.github.scribejava.core.model.Token, org.pac4j.oauth.config.OAuthConfiguration) ,public com.github.scribejava.core.model.Verb getProfileVerb() <variables>
pac4j_pac4j
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/profile/github/GitHubProfileDefinition.java
GitHubProfileDefinition
extractUserProfile
class GitHubProfileDefinition extends OAuthProfileDefinition { /** Constant <code>TYPE="type"</code> */ public static final String TYPE = "type"; /** Constant <code>BLOG="blog"</code> */ public static final String BLOG = "blog"; /** Constant <code>URL="url"</code> */ public static final String URL = "url"; /** Constant <code>PUBLIC_GISTS="public_gists"</code> */ public static final String PUBLIC_GISTS = "public_gists"; /** Constant <code>FOLLOWING="following"</code> */ public static final String FOLLOWING = "following"; /** Constant <code>PRIVATE_GISTS="private_gists"</code> */ public static final String PRIVATE_GISTS = "private_gists"; /** Constant <code>PUBLIC_REPOS="public_repos"</code> */ public static final String PUBLIC_REPOS = "public_repos"; /** Constant <code>GRAVATAR_ID="gravatar_id"</code> */ public static final String GRAVATAR_ID = "gravatar_id"; /** Constant <code>AVATAR_URL="avatar_url"</code> */ public static final String AVATAR_URL = "avatar_url"; /** Constant <code>FOLLOWERS="followers"</code> */ public static final String FOLLOWERS = "followers"; /** Constant <code>LOGIN="login"</code> */ public static final String LOGIN = "login"; /** Constant <code>COMPANY="company"</code> */ public static final String COMPANY = "company"; /** Constant <code>HIREABLE="hireable"</code> */ public static final String HIREABLE = "hireable"; /** Constant <code>COLLABORATORS="collaborators"</code> */ public static final String COLLABORATORS = "collaborators"; /** Constant <code>HTML_URL="html_url"</code> */ public static final String HTML_URL = "html_url"; /** Constant <code>BIO="bio"</code> */ public static final String BIO = "bio"; /** Constant <code>TOTAL_PRIVATE_REPOS="total_private_repos"</code> */ public static final String TOTAL_PRIVATE_REPOS = "total_private_repos"; /** Constant <code>CREATED_AT="created_at"</code> */ public static final String CREATED_AT = "created_at"; /** Constant <code>UPDATED_AT="updated_at"</code> */ public static final String UPDATED_AT = "updated_at"; /** Constant <code>NAME="name"</code> */ public static final String NAME = "name"; /** Constant <code>DISK_USAGE="disk_usage"</code> */ public static final String DISK_USAGE = "disk_usage"; /** Constant <code>PLAN="plan"</code> */ public static final String PLAN = "plan"; /** Constant <code>OWNED_PRIVATE_REPOS="owned_private_repos"</code> */ public static final String OWNED_PRIVATE_REPOS = "owned_private_repos"; /** * <p>Constructor for GitHubProfileDefinition.</p> */ public GitHubProfileDefinition() { super(x -> new GitHubProfile()); Arrays.asList(new String[] { URL, COMPANY, NAME, BLOG, LOGIN, LOCATION, TYPE, GRAVATAR_ID, BIO }).forEach(a -> primary(a, Converters.STRING)); Arrays.asList(new String[] { FOLLOWING, PUBLIC_REPOS, PUBLIC_GISTS, DISK_USAGE, COLLABORATORS, OWNED_PRIVATE_REPOS, TOTAL_PRIVATE_REPOS, PRIVATE_GISTS, FOLLOWERS }).forEach(a -> primary(a, Converters.INTEGER)); primary(HIREABLE, Converters.BOOLEAN); primary(CREATED_AT, Converters.DATE_TZ_RFC822); primary(UPDATED_AT, Converters.DATE_TZ_RFC822); primary(AVATAR_URL, Converters.URL); primary(HTML_URL, Converters.URL); primary(PLAN, new JsonConverter(GitHubPlan.class)); } /** {@inheritDoc} */ @Override public String getProfileUrl(final Token accessToken, final OAuthConfiguration configuration) { return "https://api.github.com/user"; } /** {@inheritDoc} */ @Override public GitHubProfile extractUserProfile(final String body) {<FILL_FUNCTION_BODY>} }
val profile = (GitHubProfile) newProfile(); val json = JsonHelper.getFirstNode(body); if (json != null) { profile.setId(ProfileHelper.sanitizeIdentifier(JsonHelper.getElement(json, "id"))); for (val attribute : getPrimaryAttributes()) { convertAndAdd(profile, PROFILE_ATTRIBUTE, attribute, JsonHelper.getElement(json, attribute)); } } else { raiseProfileExtractionJsonError(body); } return profile;
1,303
133
1,436
<methods>public void <init>() ,public void <init>(org.pac4j.core.profile.factory.ProfileFactory) ,public abstract org.pac4j.core.profile.CommonProfile extractUserProfile(java.lang.String) ,public abstract java.lang.String getProfileUrl(com.github.scribejava.core.model.Token, org.pac4j.oauth.config.OAuthConfiguration) ,public com.github.scribejava.core.model.Verb getProfileVerb() <variables>
pac4j_pac4j
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/profile/google2/Google2ProfileDefinition.java
Google2ProfileDefinition
extractUserProfile
class Google2ProfileDefinition extends OAuthProfileDefinition { /** Constant <code>EMAIL_VERIFIED="email_verified"</code> */ public static final String EMAIL_VERIFIED = "email_verified"; /** Constant <code>GIVEN_NAME="given_name"</code> */ public static final String GIVEN_NAME = "given_name"; /** Constant <code>NAME="name"</code> */ public static final String NAME = "name"; /** Constant <code>PICTURE="picture"</code> */ public static final String PICTURE = "picture"; /** Constant <code>PROFILE="profile"</code> */ public static final String PROFILE = "profile"; /** * <p>Constructor for Google2ProfileDefinition.</p> */ public Google2ProfileDefinition() { super(x -> new Google2Profile()); primary(EMAIL_VERIFIED, Converters.BOOLEAN); primary(GIVEN_NAME, Converters.STRING); primary(NAME, Converters.STRING); primary(PICTURE, Converters.URL); primary(PROFILE, Converters.URL); } /** {@inheritDoc} */ @Override public String getProfileUrl(final Token accessToken, final OAuthConfiguration configuration) { return "https://www.googleapis.com/oauth2/v3/userinfo"; } /** {@inheritDoc} */ @Override public Google2Profile extractUserProfile(final String body) {<FILL_FUNCTION_BODY>} }
val profile = (Google2Profile) newProfile(); val json = JsonHelper.getFirstNode(body); if (json != null) { profile.setId(ProfileHelper.sanitizeIdentifier(JsonHelper.getElement(json, "sub"))); for (val attribute : getPrimaryAttributes()) { convertAndAdd(profile, PROFILE_ATTRIBUTE, attribute, JsonHelper.getElement(json, attribute)); } } else { raiseProfileExtractionJsonError(body); } return profile;
415
132
547
<methods>public void <init>() ,public void <init>(org.pac4j.core.profile.factory.ProfileFactory) ,public abstract org.pac4j.core.profile.CommonProfile extractUserProfile(java.lang.String) ,public abstract java.lang.String getProfileUrl(com.github.scribejava.core.model.Token, org.pac4j.oauth.config.OAuthConfiguration) ,public com.github.scribejava.core.model.Verb getProfileVerb() <variables>
pac4j_pac4j
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/profile/hiorgserver/HiOrgServerProfileDefinition.java
HiOrgServerProfileDefinition
extractUserProfile
class HiOrgServerProfileDefinition extends OAuthProfileDefinition { /** Constant <code>USER_ID="user_id"</code> */ public static final String USER_ID = "user_id"; /** Constant <code>USERNAME="username"</code> */ public static final String USERNAME = "username"; /** Constant <code>NAME="name"</code> */ public static final String NAME = "name"; /** Constant <code>FIRST_NAME="vorname"</code> */ public static final String FIRST_NAME = "vorname"; /** Constant <code>FULL_NAME="fullname"</code> */ public static final String FULL_NAME = "fullname"; /** Constant <code>ROLES="gruppe"</code> */ public static final String ROLES = "gruppe"; /** Constant <code>LEADER="leitung"</code> */ public static final String LEADER = "leitung"; /** Constant <code>POSITION="funktion"</code> */ public static final String POSITION = "funktion"; /** Constant <code>ORGANISATION_ID="orga"</code> */ public static final String ORGANISATION_ID = "orga"; /** Constant <code>ORGANISATION_NAME="organisation"</code> */ public static final String ORGANISATION_NAME = "organisation"; /** Constant <code>ALTERNATIVE_ID="alt_user_id"</code> */ public static final String ALTERNATIVE_ID = "alt_user_id"; /** Constant <code>TYPED_ALTERNATIVE_ID="typed_alt_user_id"</code> */ public static final String TYPED_ALTERNATIVE_ID = "typed_alt_user_id"; /** Constant <code>BASE_URL="https://www.hiorg-server.de/api/oauth2/"{trunked}</code> */ protected static final String BASE_URL = "https://www.hiorg-server.de/api/oauth2/v1/user.php"; /** * <p>Constructor for HiOrgServerProfileDefinition.</p> */ public HiOrgServerProfileDefinition() { super(x -> new HiOrgServerProfile()); primary(USERNAME, Converters.STRING); primary(NAME, Converters.STRING); primary(FIRST_NAME, Converters.STRING); primary(FULL_NAME, Converters.STRING); primary(ROLES, Converters.INTEGER); primary(LEADER, Converters.BOOLEAN); primary(POSITION, Converters.STRING); primary(ORGANISATION_ID, Converters.STRING); primary(ORGANISATION_NAME, Converters.STRING); secondary(ALTERNATIVE_ID, Converters.STRING); secondary(TYPED_ALTERNATIVE_ID, Converters.STRING); } /** {@inheritDoc} */ @Override public String getProfileUrl(final Token accessToken, final OAuthConfiguration configuration) { return BASE_URL; } /** {@inheritDoc} */ @Override public HiOrgServerProfile extractUserProfile(String body) {<FILL_FUNCTION_BODY>} /** * <p>extractRoles.</p> * * @param profile a {@link HiOrgServerProfile} object */ protected void extractRoles(HiOrgServerProfile profile) { final Integer rolesAsInt = profile.getRolesAsInteger(); Set<String> roles = new HashSet<>(); for (var i = 0; i <= 10; i++) { var groupId = (int) Math.pow(2, i); var isGroupSet = (rolesAsInt & groupId) == groupId; if (isGroupSet) { logger.debug("Extracted role " + groupId); roles.add(String.valueOf(groupId)); } } profile.setRoles(roles); } }
val profile = (HiOrgServerProfile) newProfile(); val json = JsonHelper.getFirstNode(body); if (json != null) { logger.debug("Extracting user profile from JSON node " + json); profile.setId(ProfileHelper.sanitizeIdentifier(JsonHelper.getElement(json, USER_ID))); for (val attribute : getPrimaryAttributes()) { convertAndAdd(profile, PROFILE_ATTRIBUTE, attribute, JsonHelper.getElement(json, attribute)); } // Secondary attributes are generated from primary attributes convertAndAdd(profile, PROFILE_ATTRIBUTE, ALTERNATIVE_ID, profile.getAlternativeId()); convertAndAdd(profile, PROFILE_ATTRIBUTE, TYPED_ALTERNATIVE_ID, profile.getTypedAlternativeId()); } else { raiseProfileExtractionJsonError(body); } extractRoles(profile); return profile;
1,067
236
1,303
<methods>public void <init>() ,public void <init>(org.pac4j.core.profile.factory.ProfileFactory) ,public abstract org.pac4j.core.profile.CommonProfile extractUserProfile(java.lang.String) ,public abstract java.lang.String getProfileUrl(com.github.scribejava.core.model.Token, org.pac4j.oauth.config.OAuthConfiguration) ,public com.github.scribejava.core.model.Verb getProfileVerb() <variables>
pac4j_pac4j
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/profile/linkedin2/LinkedIn2Profile.java
LinkedIn2Profile
getPictureUrl
class LinkedIn2Profile extends OAuth20Profile { @Serial private static final long serialVersionUID = 100L; /** * <p>getLocalizedFirstName.</p> * * @return a {@link String} object */ public String getLocalizedFirstName() { return (String) getAttribute(LinkedIn2ProfileDefinition.LOCALIZED_FIRST_NAME); } /** * <p>getLocalizedLastName.</p> * * @return a {@link String} object */ public String getLocalizedLastName() { return (String) getAttribute(LinkedIn2ProfileDefinition.LOCALIZED_LAST_NAME); } /** * <p>getProfilePicture.</p> * * @return a {@link LinkedIn2ProfilePicture} object */ public LinkedIn2ProfilePicture getProfilePicture() { return (LinkedIn2ProfilePicture) getAttribute(LinkedIn2ProfileDefinition.PROFILE_PICTURE); } /** * <p>getProfileEmails.</p> * * @return a {@link LinkedIn2ProfileEmails} object */ public LinkedIn2ProfileEmails getProfileEmails() { return (LinkedIn2ProfileEmails) getAttribute(LinkedIn2ProfileDefinition.PROFILE_EMAILS); } /** {@inheritDoc} */ @Override public String getFirstName() { return getLocalizedFirstName(); } /** {@inheritDoc} */ @Override public String getFamilyName() { return getLocalizedLastName(); } /** {@inheritDoc} */ @Override public String getDisplayName() { return getFirstName() + " " + getFamilyName(); } /** {@inheritDoc} */ @Override public URI getPictureUrl() {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override public String getEmail() { val pe = getProfileEmails(); if (pe == null) { return null; } val elements = pe.getElements(); if (elements == null || elements.length == 0) { return null; } val element = elements[0]; if (element == null) { return null; } val handleTilde = element.getHandleTilde(); if (handleTilde == null) { return null; } return handleTilde.getEmailAddress(); } }
val pp = getProfilePicture(); if (pp == null) { return null; } val displayImageTilde = pp.getDisplayImageTilde(); if (displayImageTilde == null) { return null; } val elements = displayImageTilde.getElements(); if (elements == null || elements.length == 0) { return null; } val element = elements[0]; if (element == null) { return null; } val identifiers = element.getIdentifiers(); if (identifiers == null || identifiers.length == 0) { return null; } val identifier = identifiers[0]; if (identifier == null) { return null; } val identifier2 = identifier.getIdentifier(); if (identifier2 == null) { return null; } return CommonHelper.asURI(identifier2);
667
240
907
<methods>public non-sealed void <init>() ,public java.lang.String getAccessToken() ,public java.lang.String getRefreshToken() ,public void removeLoginData() ,public void setAccessToken(java.lang.String) ,public void setRefreshToken(java.lang.String) <variables>private static final java.lang.String ACCESS_TOKEN,private static final java.lang.String REFRESH_TOKEN,private static final long serialVersionUID
pac4j_pac4j
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/profile/linkedin2/LinkedIn2ProfileCreator.java
LinkedIn2ProfileCreator
retrieveUserProfileFromToken
class LinkedIn2ProfileCreator extends OAuth20ProfileCreator { private static final String EMAIL_URL = "https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~))"; /** * <p>Constructor for LinkedIn2ProfileCreator.</p> * * @param configuration a {@link OAuth20Configuration} object * @param client a {@link IndirectClient} object */ public LinkedIn2ProfileCreator(final OAuth20Configuration configuration, final IndirectClient client) { super(configuration, client); } /** {@inheritDoc} */ @Override protected Optional<UserProfile> retrieveUserProfileFromToken(final WebContext context, final Token accessToken) {<FILL_FUNCTION_BODY>} }
super.retrieveUserProfileFromToken(context, accessToken); val profileDefinition = (LinkedIn2ProfileDefinition) configuration.getProfileDefinition(); val linkedin2Configuration = (LinkedIn2Configuration) configuration; val profileUrl = profileDefinition.getProfileUrl(accessToken, linkedin2Configuration); val service = (OAuth20Service) configuration.buildService(context, client); var body = sendRequestForData(service, accessToken, profileUrl, profileDefinition.getProfileVerb()); if (body == null) { throw new HttpCommunicationException("Not data found for accessToken: " + accessToken); } val profile = profileDefinition.extractUserProfile(body); addTokenToProfile(profile, accessToken); if (profile == null || !linkedin2Configuration.getScope().contains("r_emailaddress")) { return Optional.ofNullable(profile); } body = sendRequestForData(service, accessToken, EMAIL_URL, profileDefinition.getProfileVerb()); if (body == null) { throw new HttpCommunicationException("Not email data found for accessToken: " + accessToken); } try { val profileEmails = JsonHelper.getMapper().readValue(body, LinkedIn2ProfileEmails.class); profile.addAttribute(LinkedIn2ProfileDefinition.PROFILE_EMAILS, profileEmails); } catch (IOException e) { logger.error(e.getMessage(), e); } return Optional.of(profile);
207
377
584
<methods>public void <init>(org.pac4j.oauth.config.OAuth20Configuration, org.pac4j.core.client.IndirectClient) <variables>
pac4j_pac4j
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/profile/linkedin2/LinkedIn2ProfileDefinition.java
LinkedIn2ProfileDefinition
extractUserProfile
class LinkedIn2ProfileDefinition extends OAuthProfileDefinition { /** Constant <code>LOCALIZED_FIRST_NAME="localizedFirstName"</code> */ public static final String LOCALIZED_FIRST_NAME = "localizedFirstName"; /** Constant <code>LOCALIZED_LAST_NAME="localizedLastName"</code> */ public static final String LOCALIZED_LAST_NAME = "localizedLastName"; /** Constant <code>PROFILE_PICTURE="profilePicture"</code> */ public static final String PROFILE_PICTURE = "profilePicture"; /** Constant <code>PROFILE_EMAILS="profileEmails"</code> */ public static final String PROFILE_EMAILS = "profileEmails"; /** * <p>Constructor for LinkedIn2ProfileDefinition.</p> */ public LinkedIn2ProfileDefinition() { super(x -> new LinkedIn2Profile()); Arrays.stream(new String[] {LOCALIZED_FIRST_NAME, LOCALIZED_LAST_NAME}).forEach(a -> primary(a, Converters.STRING)); primary(PROFILE_PICTURE, new JsonConverter(LinkedIn2ProfilePicture.class)); } /** {@inheritDoc} */ @Override public String getProfileUrl(final Token accessToken, final OAuthConfiguration configuration) { return ((LinkedIn2Configuration) configuration).getProfileUrl(); } /** {@inheritDoc} */ @Override public LinkedIn2Profile extractUserProfile(final String body) {<FILL_FUNCTION_BODY>} }
val profile = (LinkedIn2Profile) newProfile(); val json = JsonHelper.getFirstNode(body); if (json == null) { raiseProfileExtractionJsonError(body); } profile.setId(ProfileHelper.sanitizeIdentifier(JsonHelper.getElement(json, "id"))); for (val attribute : getPrimaryAttributes()) { convertAndAdd(profile, PROFILE_ATTRIBUTE, attribute, JsonHelper.getElement(json, attribute)); } return profile;
417
128
545
<methods>public void <init>() ,public void <init>(org.pac4j.core.profile.factory.ProfileFactory) ,public abstract org.pac4j.core.profile.CommonProfile extractUserProfile(java.lang.String) ,public abstract java.lang.String getProfileUrl(com.github.scribejava.core.model.Token, org.pac4j.oauth.config.OAuthConfiguration) ,public com.github.scribejava.core.model.Verb getProfileVerb() <variables>
pac4j_pac4j
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/profile/linkedin2/LinkedIn2ProfilePicture.java
Identifier
toString
class Identifier implements Serializable { @Serial private static final long serialVersionUID = 1L; private String identifier; private String file; private int index; private String mediaType; private String identifierType; private int identifierExpiresInSeconds; public String getIdentifier() { return identifier; } public void setIdentifier(String identifier) { this.identifier = identifier; } public String getFile() { return file; } public void setFile(String file) { this.file = file; } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } public String getMediaType() { return mediaType; } public void setMediaType(String mediaType) { this.mediaType = mediaType; } public String getIdentifierType() { return identifierType; } public void setIdentifierType(String identifierType) { this.identifierType = identifierType; } public int getIdentifierExpiresInSeconds() { return identifierExpiresInSeconds; } public void setIdentifierExpiresInSeconds(int identifierExpiresInSeconds) { this.identifierExpiresInSeconds = identifierExpiresInSeconds; } @Override public String toString() { return String.format( "{identifier: %s, file: %s, index: %d, mediaType: %s, identifierType: %s, identifierExpiresInSeconds: %d}", identifier, file, index, mediaType, identifierType, identifierExpiresInSeconds); } } private String artifact; private String authorizationMethod; private Data data; private Identifier[] identifiers; public String getArtifact() { return artifact; } public void setArtifact(String artifact) { this.artifact = artifact; } public String getAuthorizationMethod() { return authorizationMethod; } public void setAuthorizationMethod(String authorizationMethod) { this.authorizationMethod = authorizationMethod; } public Data getData() { return data; } public void setData(Data data) { this.data = data; } public Identifier[] getIdentifiers() { return deepCopy(identifiers); } public void setIdentifiers(Identifier[] identifiers) { this.identifiers = deepCopy(identifiers); } @Override public String toString() {<FILL_FUNCTION_BODY>
return String.format("{artifact: %s, authorizationMethod: %s, data: %s, identifiers: %s}", artifact, authorizationMethod, data, Arrays.asList(identifiers));
683
54
737
<no_super_class>
pac4j_pac4j
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/profile/ok/OkProfileDefinition.java
OkProfileDefinition
getProfileUrl
class OkProfileDefinition extends OAuthProfileDefinition { /** Constant <code>UID="uid"</code> */ public static final String UID = "uid"; /** Constant <code>BIRTHDAY="birthday"</code> */ public static final String BIRTHDAY = "birthday"; /** Constant <code>AGE="age"</code> */ public static final String AGE = "age"; /** Constant <code>NAME="name"</code> */ public static final String NAME = "name"; /** Constant <code>LOCATION_CITY="location.city"</code> */ public static final String LOCATION_CITY = "location.city"; /** Constant <code>LOCATION_COUNTRY="location.country"</code> */ public static final String LOCATION_COUNTRY = "location.country"; /** Constant <code>LOCATION_COUNTRY_CODE="location.countryCode"</code> */ public static final String LOCATION_COUNTRY_CODE = "location.countryCode"; /** Constant <code>LOCATION_COUNTRY_NAME="location.countryName"</code> */ public static final String LOCATION_COUNTRY_NAME = "location.countryName"; /** Constant <code>ONLINE="online"</code> */ public static final String ONLINE = "online"; /** Constant <code>LAST_NAME="last_name"</code> */ public static final String LAST_NAME = "last_name"; /** Constant <code>HAS_EMAIL="has_email"</code> */ public static final String HAS_EMAIL = "has_email"; /** Constant <code>CURRENT_STATUS="current_status"</code> */ public static final String CURRENT_STATUS = "current_status"; /** Constant <code>CURRENT_STATUS_ID="current_status_id"</code> */ public static final String CURRENT_STATUS_ID = "current_status_id"; /** Constant <code>CURRENT_STATUS_DATE="current_status_date"</code> */ public static final String CURRENT_STATUS_DATE = "current_status_date"; /** Constant <code>PIC_1="pic_1"</code> */ public static final String PIC_1 = "pic_1"; /** Constant <code>PIC_2="pic_2"</code> */ public static final String PIC_2 = "pic_2"; private static final String API_BASE_URL = "http://api.ok.ru/fb.do?"; /** * <p>Constructor for OkProfileDefinition.</p> */ public OkProfileDefinition() { super(x -> new OkProfile()); Arrays.stream(new String[] {UID, BIRTHDAY, AGE, NAME, LOCATION_CITY, LOCATION_COUNTRY, LOCATION_COUNTRY_CODE, LOCATION_COUNTRY_NAME, ONLINE, LAST_NAME, HAS_EMAIL, CURRENT_STATUS, CURRENT_STATUS_ID, CURRENT_STATUS_DATE}) .forEach(a -> primary(a, Converters.STRING)); primary(PIC_1, Converters.URL); primary(PIC_2, Converters.URL); } /** {@inheritDoc} */ @Override public String getProfileUrl(final Token token, final OAuthConfiguration configuration) {<FILL_FUNCTION_BODY>} /** * <p>getMD5SignAsHexString.</p> * * @param strForEncoding a {@link String} object * @return a {@link String} object * @throws NoSuchAlgorithmException if any. */ protected String getMD5SignAsHexString(final String strForEncoding) throws NoSuchAlgorithmException { var md = MessageDigest.getInstance("MD5"); var result = new StringBuilder(); for (var aByte : md.digest(strForEncoding.getBytes(StandardCharsets.UTF_8))) { if ((0xff & aByte) < 0x10) { result.append("0").append(Integer.toHexString(0xFF & aByte)); } else { result.append(Integer.toHexString(0xFF & aByte)); } } return result.toString(); } /** {@inheritDoc} */ @Override public OkProfile extractUserProfile(String body) { val profile = (OkProfile) newProfile(); var userNode = JsonHelper.getFirstNode(body); if (userNode != null) { profile.setId(ProfileHelper.sanitizeIdentifier(JsonHelper.getElement(userNode, OkProfileDefinition.UID))); for (val attribute : getPrimaryAttributes()) { convertAndAdd(profile, PROFILE_ATTRIBUTE, attribute, JsonHelper.getElement(userNode, attribute)); } } else { raiseProfileExtractionJsonError(body); } return profile; } }
val accessToken = ((OAuth2AccessToken) token).getAccessToken(); var baseParams = "application_key=" + ((OkConfiguration) configuration).getPublicKey() + "&format=json" + "&method=users.getCurrentUser"; final String finalSign; try { val preSign = getMD5SignAsHexString(accessToken + configuration.getSecret()); finalSign = getMD5SignAsHexString(baseParams.replaceAll("&", Pac4jConstants.EMPTY_STRING) + preSign); } catch (Exception e) { logger.error(e.getMessage()); return null; } return API_BASE_URL + baseParams + "&access_token=" + accessToken + "&sig=" + finalSign;
1,295
199
1,494
<methods>public void <init>() ,public void <init>(org.pac4j.core.profile.factory.ProfileFactory) ,public abstract org.pac4j.core.profile.CommonProfile extractUserProfile(java.lang.String) ,public abstract java.lang.String getProfileUrl(com.github.scribejava.core.model.Token, org.pac4j.oauth.config.OAuthConfiguration) ,public com.github.scribejava.core.model.Verb getProfileVerb() <variables>
pac4j_pac4j
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/profile/paypal/PayPalProfileDefinition.java
PayPalProfileDefinition
extractUserProfile
class PayPalProfileDefinition extends OAuthProfileDefinition { /** Constant <code>ADDRESS="address"</code> */ public static final String ADDRESS = "address"; /** Constant <code>LANGUAGE="language"</code> */ public static final String LANGUAGE = "language"; /** Constant <code>ZONEINFO="zoneinfo"</code> */ public static final String ZONEINFO = "zoneinfo"; /** Constant <code>NAME="name"</code> */ public static final String NAME = "name"; /** Constant <code>GIVEN_NAME="given_name"</code> */ public static final String GIVEN_NAME = "given_name"; /** * <p>Constructor for PayPalProfileDefinition.</p> */ public PayPalProfileDefinition() { super(x -> new PayPalProfile()); Arrays.stream(new String[] {ZONEINFO, NAME, GIVEN_NAME}).forEach(a -> primary(a, Converters.STRING)); primary(ADDRESS, new JsonConverter(PayPalAddress.class)); primary(LANGUAGE, Converters.LOCALE); } /** {@inheritDoc} */ @Override public String getProfileUrl(final Token accessToken, final OAuthConfiguration configuration) { return "https://api.paypal.com/v1/identity/openidconnect/userinfo?schema=openid"; } /** {@inheritDoc} */ @Override public PayPalProfile extractUserProfile(final String body) {<FILL_FUNCTION_BODY>} }
val profile = (PayPalProfile) newProfile(); val json = JsonHelper.getFirstNode(body); if (json != null) { val userId = (String) JsonHelper.getElement(json, "user_id"); profile.setId(CommonHelper.substringAfter(userId, "/user/")); for (val attribute : getPrimaryAttributes()) { convertAndAdd(profile, PROFILE_ATTRIBUTE, attribute, JsonHelper.getElement(json, attribute)); } } else { raiseProfileExtractionJsonError(body); } return profile;
408
147
555
<methods>public void <init>() ,public void <init>(org.pac4j.core.profile.factory.ProfileFactory) ,public abstract org.pac4j.core.profile.CommonProfile extractUserProfile(java.lang.String) ,public abstract java.lang.String getProfileUrl(com.github.scribejava.core.model.Token, org.pac4j.oauth.config.OAuthConfiguration) ,public com.github.scribejava.core.model.Verb getProfileVerb() <variables>
pac4j_pac4j
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/profile/qq/QQProfileCreator.java
QQProfileCreator
retrieveUserProfileFromToken
class QQProfileCreator extends OAuth20ProfileCreator { /** * <p>Constructor for QQProfileCreator.</p> * * @param configuration a {@link OAuth20Configuration} object * @param client a {@link IndirectClient} object */ public QQProfileCreator(final OAuth20Configuration configuration, final IndirectClient client) { super(configuration, client); } /** {@inheritDoc} */ @Override public Optional<UserProfile> retrieveUserProfileFromToken(final WebContext context, final Token accessToken) {<FILL_FUNCTION_BODY>} }
var profileDefinition = (QQProfileDefinition) configuration.getProfileDefinition(); var openidUrl = profileDefinition.getOpenidUrl((OAuth2AccessToken) accessToken, (OAuth20Configuration) configuration); val service = (OAuth20Service) this.configuration.buildService(context, client); var body = sendRequestForData(service, accessToken, openidUrl, Verb.GET); var openid = profileDefinition.extractOpenid(body); var profileUrl = profileDefinition.getProfileUrl(accessToken, configuration); profileUrl = CommonHelper.addParameter(profileUrl, "openid", openid); profileUrl = CommonHelper.addParameter(profileUrl, "oauth_consumer_key", configuration.getKey()); body = sendRequestForData(service, accessToken, profileUrl, Verb.GET); if (body == null) { throw new HttpCommunicationException("Not data found for accessToken: " + accessToken); } val profile = profileDefinition.extractUserProfile(body); addTokenToProfile(profile, accessToken); profile.setId(openid); return Optional.of(profile);
164
290
454
<methods>public void <init>(org.pac4j.oauth.config.OAuth20Configuration, org.pac4j.core.client.IndirectClient) <variables>
pac4j_pac4j
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/profile/qq/QQProfileDefinition.java
QQProfileDefinition
extractParameter
class QQProfileDefinition extends OAuthProfileDefinition { /** Constant <code>OPENID_REGEX</code> */ public static final Pattern OPENID_REGEX = Pattern.compile("\"openid\"\\s*:\\s*\"(\\S*?)\""); /** Constant <code>RET="ret"</code> */ public static final String RET = "ret"; /** Constant <code>MSG="msg"</code> */ public static final String MSG = "msg"; /** Constant <code>NICKNAME="nickname"</code> */ public static final String NICKNAME = "nickname"; /** Constant <code>PROVINCE="province"</code> */ public static final String PROVINCE = "province"; /** Constant <code>CITY="city"</code> */ public static final String CITY = "city"; /** Constant <code>YEAR="year"</code> */ public static final String YEAR = "year"; /** Constant <code>FIGUREURL="figureurl"</code> */ public static final String FIGUREURL = "figureurl"; /** Constant <code>FIGUREURL_1="figureurl_1"</code> */ public static final String FIGUREURL_1 = "figureurl_1"; /** Constant <code>FIGUREURL_2="figureurl_2"</code> */ public static final String FIGUREURL_2 = "figureurl_2"; /** Constant <code>FIGUREURL_QQ_1="figureurl_qq_1"</code> */ public static final String FIGUREURL_QQ_1 = "figureurl_qq_1"; /** Constant <code>FIGUREURL_QQ_2="figureurl_qq_2"</code> */ public static final String FIGUREURL_QQ_2 = "figureurl_qq_2"; /** * <p>Constructor for QQProfileDefinition.</p> */ public QQProfileDefinition() { Arrays.stream(new String[]{ MSG, NICKNAME, PROVINCE, CITY, YEAR }).forEach(a -> primary(a, Converters.STRING)); Arrays.stream(new String[]{ FIGUREURL, FIGUREURL_1, FIGUREURL_2, FIGUREURL_QQ_1, FIGUREURL_QQ_2 }).forEach(a -> primary(a, Converters.URL)); primary(RET, Converters.INTEGER); primary(GENDER, new GenderConverter("男", "女")); primary(YEAR, new DateConverter("yyyy")); } /** * <p>getOpenidUrl.</p> * * @param accessToken a {@link OAuth2AccessToken} object * @param configuration a {@link OAuth20Configuration} object * @return a {@link String} object */ public String getOpenidUrl(OAuth2AccessToken accessToken, OAuth20Configuration configuration) { return "https://graph.qq.com/oauth2.0/me"; } /** {@inheritDoc} */ @Override public String getProfileUrl(final Token accessToken, final OAuthConfiguration configuration) { return "https://graph.qq.com/user/get_user_info"; } /** {@inheritDoc} */ @Override public QQProfile extractUserProfile(String body) { val profile = new QQProfile(); val json = JsonHelper.getFirstNode(body); if (json != null) { for (val attribute : getPrimaryAttributes()) { convertAndAdd(profile, PROFILE_ATTRIBUTE, attribute, JsonHelper.getElement(json, attribute)); } } else { raiseProfileExtractionJsonError(body); } return profile; } /** * <p>extractOpenid.</p> * * @param body a {@link String} object * @return a {@link String} object */ public String extractOpenid(String body) { var openid = extractParameter(body, OPENID_REGEX, true); return openid; } /** * <p>extractParameter.</p> * * @param response a {@link String} object * @param regexPattern a {@link Pattern} object * @param required a boolean * @return a {@link String} object * @throws OAuthException if any. */ protected static String extractParameter(CharSequence response, Pattern regexPattern, boolean required) throws OAuthException {<FILL_FUNCTION_BODY>} }
val matcher = regexPattern.matcher(response); if (matcher.find()) { return matcher.group(1); } if (required) { throw new OAuthException( "Response body is incorrect. Can't extract a '" + regexPattern.pattern() + "' from this: '" + response + "'", null); } return null;
1,225
100
1,325
<methods>public void <init>() ,public void <init>(org.pac4j.core.profile.factory.ProfileFactory) ,public abstract org.pac4j.core.profile.CommonProfile extractUserProfile(java.lang.String) ,public abstract java.lang.String getProfileUrl(com.github.scribejava.core.model.Token, org.pac4j.oauth.config.OAuthConfiguration) ,public com.github.scribejava.core.model.Verb getProfileVerb() <variables>
pac4j_pac4j
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/profile/strava/StravaProfileDefinition.java
StravaProfileDefinition
extractUserProfile
class StravaProfileDefinition extends OAuthProfileDefinition { /** Constant <code>ID="id"</code> */ public static final String ID = "id"; /** Constant <code>RESOURCE_STATE="resource_state"</code> */ public static final String RESOURCE_STATE = "resource_state"; /** Constant <code>FIRST_NAME="firstname"</code> */ public static final String FIRST_NAME = "firstname"; /** Constant <code>LAST_NAME="lastname"</code> */ public static final String LAST_NAME = "lastname"; /** Constant <code>PROFILE_MEDIUM="profile_medium"</code> */ public static final String PROFILE_MEDIUM = "profile_medium"; /** Constant <code>PROFILE="profile"</code> */ public static final String PROFILE = "profile"; /** Constant <code>CITY="city"</code> */ public static final String CITY = "city"; /** Constant <code>STATE="state"</code> */ public static final String STATE = "state"; /** Constant <code>COUNTRY="country"</code> */ public static final String COUNTRY = "country"; /** Constant <code>SEX="sex"</code> */ public static final String SEX = "sex"; // friend // follower /** Constant <code>PREMIUM="premium"</code> */ public static final String PREMIUM = "premium"; /** Constant <code>CREATED_AT="created_at"</code> */ public static final String CREATED_AT = "created_at"; /** Constant <code>UPDATED_AT="updated_at"</code> */ public static final String UPDATED_AT = "updated_at"; /** Constant <code>BADGE_TYPE_ID="badge_type_id"</code> */ public static final String BADGE_TYPE_ID = "badge_type_id"; /** Constant <code>FOLLOWER_COUNT="follower_count"</code> */ public static final String FOLLOWER_COUNT = "follower_count"; /** Constant <code>FRIEND_COUNT="friend_count"</code> */ public static final String FRIEND_COUNT = "friend_count"; // mutual_friend_count /** Constant <code>DATE_PREFERENCE="date_preference"</code> */ public static final String DATE_PREFERENCE = "date_preference"; /** Constant <code>MEASUREMENT_PREFERENCE="measurement_preference"</code> */ public static final String MEASUREMENT_PREFERENCE = "measurement_preference"; // ftp /** Constant <code>CLUBS="clubs"</code> */ public static final String CLUBS = "clubs"; /** Constant <code>BIKES="bikes"</code> */ public static final String BIKES = "bikes"; /** Constant <code>SHOES="shoes"</code> */ public static final String SHOES = "shoes"; /** * <p>Constructor for StravaProfileDefinition.</p> */ public StravaProfileDefinition() { super(x -> new StravaProfile()); Arrays.stream(new String[] {FIRST_NAME, LAST_NAME, PROFILE_MEDIUM, CITY, STATE, COUNTRY, DATE_PREFERENCE, MEASUREMENT_PREFERENCE}).forEach(a -> primary(a, Converters.STRING)); primary(ID, Converters.LONG); primary(RESOURCE_STATE, Converters.INTEGER); primary(BADGE_TYPE_ID, Converters.INTEGER); primary(FOLLOWER_COUNT, Converters.INTEGER); primary(FRIEND_COUNT, Converters.INTEGER); primary(PREMIUM, Converters.BOOLEAN); primary(SEX, Converters.GENDER); primary(CREATED_AT, Converters.DATE_TZ_RFC822); primary(UPDATED_AT, Converters.DATE_TZ_RFC822); primary(CLUBS, new JsonConverter(List.class, new TypeReference<List<StravaClub>>() {})); AttributeConverter multiGearConverter = new JsonConverter(List.class, new TypeReference<List<StravaGear>>() {}); primary(BIKES, multiGearConverter); primary(SHOES, multiGearConverter); primary(PROFILE, Converters.URL); } /** {@inheritDoc} */ @Override public String getProfileUrl(final Token accessToken, final OAuthConfiguration configuration) { return "https://www.strava.com/api/v3/athlete"; } /** {@inheritDoc} */ @Override public StravaProfile extractUserProfile(String body) {<FILL_FUNCTION_BODY>} }
val profile = (StravaProfile) newProfile(); val json = JsonHelper.getFirstNode(body); if (json != null) { profile.setId(ProfileHelper.sanitizeIdentifier(JsonHelper.getElement(json, StravaProfileDefinition.ID))); for (val attribute : getPrimaryAttributes()) { convertAndAdd(profile, PROFILE_ATTRIBUTE, attribute, JsonHelper.getElement(json, attribute)); } } else { raiseProfileExtractionJsonError(body); } return profile;
1,313
136
1,449
<methods>public void <init>() ,public void <init>(org.pac4j.core.profile.factory.ProfileFactory) ,public abstract org.pac4j.core.profile.CommonProfile extractUserProfile(java.lang.String) ,public abstract java.lang.String getProfileUrl(com.github.scribejava.core.model.Token, org.pac4j.oauth.config.OAuthConfiguration) ,public com.github.scribejava.core.model.Verb getProfileVerb() <variables>
pac4j_pac4j
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/profile/vk/VkProfileDefinition.java
VkProfileDefinition
extractUserProfile
class VkProfileDefinition extends OAuthProfileDefinition { /** Constant <code>LAST_NAME="last_name"</code> */ public static final String LAST_NAME = "last_name"; /** Constant <code>SEX="sex"</code> */ public static final String SEX = "sex"; /** Constant <code>BIRTH_DATE="bdate"</code> */ public static final String BIRTH_DATE = "bdate"; /** Constant <code>PHOTO_50="photo_50"</code> */ public static final String PHOTO_50 = "photo_50"; /** Constant <code>PHOTO_100="photo_100"</code> */ public static final String PHOTO_100 = "photo_100"; /** Constant <code>PHOTO_200_ORIG="photo_200_orig"</code> */ public static final String PHOTO_200_ORIG = "photo_200_orig"; /** Constant <code>PHOTO_200="photo_200"</code> */ public static final String PHOTO_200 = "photo_200"; /** Constant <code>PHOTO_400_ORIG="photo_400_orig"</code> */ public static final String PHOTO_400_ORIG = "photo_400_orig"; /** Constant <code>PHOTO_MAX="photo_max"</code> */ public static final String PHOTO_MAX = "photo_max"; /** Constant <code>PHOTO_MAX_ORIG="photo_max_orig"</code> */ public static final String PHOTO_MAX_ORIG = "photo_max_orig"; /** Constant <code>ONLINE="online"</code> */ public static final String ONLINE = "online"; /** Constant <code>ONLINE_MOBILE="online_mobile"</code> */ public static final String ONLINE_MOBILE = "online_mobile"; /** Constant <code>DOMAIN="domain"</code> */ public static final String DOMAIN = "domain"; /** Constant <code>HAS_MOBILE="has_mobile"</code> */ public static final String HAS_MOBILE = "has_mobile"; /** Constant <code>MOBILE_PHONE="mobile_phone"</code> */ public static final String MOBILE_PHONE = "mobile_phone"; /** Constant <code>HOME_PHONE="home_phone"</code> */ public static final String HOME_PHONE = "home_phone"; /** Constant <code>SKYPE="skype"</code> */ public static final String SKYPE = "skype"; /** Constant <code>SITE="site"</code> */ public static final String SITE = "site"; /** Constant <code>CAN_POST="can_post"</code> */ public static final String CAN_POST = "can_post"; /** Constant <code>CAN_SEE_ALL_POST="can_see_all_posts"</code> */ public static final String CAN_SEE_ALL_POST = "can_see_all_posts"; /** Constant <code>CAN_SEE_AUDIO="can_see_audio"</code> */ public static final String CAN_SEE_AUDIO = "can_see_audio"; /** Constant <code>CAN_WRITE_PRIVATE_MESSAGE="can_write_private_message"</code> */ public static final String CAN_WRITE_PRIVATE_MESSAGE = "can_write_private_message"; /** Constant <code>STATUS="status"</code> */ public static final String STATUS = "status"; /** Constant <code>COMMON_COUNT="common_count"</code> */ public static final String COMMON_COUNT = "common_count"; /** Constant <code>RELATION="relation"</code> */ public static final String RELATION = "relation"; /** Constant <code>BASE_URL="https://api.vk.com/method/users.get"</code> */ protected final static String BASE_URL = "https://api.vk.com/method/users.get"; /** * <p>Constructor for VkProfileDefinition.</p> */ public VkProfileDefinition() { super(x -> new VkProfile()); Arrays.stream(new String[] {LAST_NAME, PHOTO_50, PHOTO_100, PHOTO_200_ORIG, PHOTO_200, PHOTO_400_ORIG, PHOTO_MAX, PHOTO_MAX_ORIG, DOMAIN, MOBILE_PHONE, HOME_PHONE, SKYPE, SITE, STATUS}) .forEach(a -> primary(a, Converters.STRING)); primary(COMMON_COUNT, Converters.INTEGER); primary(RELATION, Converters.INTEGER); Arrays.stream(new String[] {ONLINE, ONLINE_MOBILE, HAS_MOBILE, CAN_POST, CAN_SEE_ALL_POST, CAN_SEE_AUDIO, CAN_WRITE_PRIVATE_MESSAGE}) .forEach(a -> primary(a, Converters.BOOLEAN)); primary(BIRTH_DATE, new DateConverter("dd.MM.yyyy")); primary(SEX, new GenderConverter("2", "1")); } /** {@inheritDoc} */ @Override public String getProfileUrl(final Token accessToken, final OAuthConfiguration configuration) { return BASE_URL + "?fields=" + ((VkConfiguration) configuration).getFields(); } /** {@inheritDoc} */ @Override public VkProfile extractUserProfile(final String body) {<FILL_FUNCTION_BODY>} }
val profile = (VkProfile) newProfile(); var json = JsonHelper.getFirstNode(body); if (json != null) { var array = (ArrayNode) json.get("response"); var userNode = array.get(0); if (userNode == null) { raiseProfileExtractionJsonError(body, "response"); } profile.setId(ProfileHelper.sanitizeIdentifier(JsonHelper.getElement(userNode, "uid"))); for (val attribute : getPrimaryAttributes()) { convertAndAdd(profile, PROFILE_ATTRIBUTE, attribute, JsonHelper.getElement(userNode, attribute)); } } else { raiseProfileExtractionJsonError(body); } return profile;
1,535
188
1,723
<methods>public void <init>() ,public void <init>(org.pac4j.core.profile.factory.ProfileFactory) ,public abstract org.pac4j.core.profile.CommonProfile extractUserProfile(java.lang.String) ,public abstract java.lang.String getProfileUrl(com.github.scribejava.core.model.Token, org.pac4j.oauth.config.OAuthConfiguration) ,public com.github.scribejava.core.model.Verb getProfileVerb() <variables>
pac4j_pac4j
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/profile/wechat/WechatProfile.java
WechatProfile
getLocation
class WechatProfile extends OAuth20Profile { @Serial private static final long serialVersionUID = 2576512203937798654L; /** {@inheritDoc} */ @Override public String getDisplayName() { return (String) getAttribute(WechatProfileDefinition.NICKNAME); } /** {@inheritDoc} */ @Override public String getUsername() { return (String) getAttribute(WechatProfileDefinition.NICKNAME); } /** {@inheritDoc} */ @Override public Gender getGender() { return (Gender) getAttribute(WechatProfileDefinition.SEX); } /** {@inheritDoc} */ @Override public String getLocation() {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override public URI getPictureUrl() { return (URI) getAttribute(WechatProfileDefinition.HEADIMGURL); } }
val location = getAttribute(WechatProfileDefinition.CITY) + "," + getAttribute(WechatProfileDefinition.PROVINCE) + "," + getAttribute(WechatProfileDefinition.COUNTRY); return location;
258
61
319
<methods>public non-sealed void <init>() ,public java.lang.String getAccessToken() ,public java.lang.String getRefreshToken() ,public void removeLoginData() ,public void setAccessToken(java.lang.String) ,public void setRefreshToken(java.lang.String) <variables>private static final java.lang.String ACCESS_TOKEN,private static final java.lang.String REFRESH_TOKEN,private static final long serialVersionUID
pac4j_pac4j
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/profile/wechat/WechatProfileCreator.java
WechatProfileCreator
retrieveUserProfileFromToken
class WechatProfileCreator extends OAuth20ProfileCreator { /** * <p>Constructor for WechatProfileCreator.</p> * * @param configuration a {@link OAuth20Configuration} object * @param client a {@link IndirectClient} object */ public WechatProfileCreator(OAuth20Configuration configuration, IndirectClient client) { super(configuration, client); } /** {@inheritDoc} */ @Override protected Optional<UserProfile> retrieveUserProfileFromToken(final WebContext context, final Token accessToken) {<FILL_FUNCTION_BODY>} }
val token = (WechatToken) accessToken; val profile = super.retrieveUserProfileFromToken(context, token); profile.get().setId(token.getOpenid()); return profile;
159
54
213
<methods>public void <init>(org.pac4j.oauth.config.OAuth20Configuration, org.pac4j.core.client.IndirectClient) <variables>
pac4j_pac4j
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/profile/wechat/WechatProfileDefinition.java
WechatProfileDefinition
extractUserProfile
class WechatProfileDefinition extends OAuthProfileDefinition { /** Constant <code>OPENID="openid"</code> */ public static final String OPENID = "openid"; /** Constant <code>NICKNAME="nickname"</code> */ public static final String NICKNAME = "nickname"; /** * Gender, 1 male and 2 female */ public static final String SEX = "sex"; /** Constant <code>PROVINCE="province"</code> */ public static final String PROVINCE = "province"; /** Constant <code>CITY="city"</code> */ public static final String CITY = "city"; /** * country, For example, China is CN */ public static final String COUNTRY = "country"; /** * User avatar, the last value represents the size of the square avatar (0, 46, 64, 96, 132 values are optional, 0 is 640 * 640 * square avatar), the item is empty when the user has no avatar */ public static final String HEADIMGURL = "headimgurl"; /** * User privilege information, json array, such as WeChat Waka users (chinaunicom) */ public static final String PRIVILEGE = "privilege "; /** * User union identity. For an application under the WeChat open platform account, the unionid of the same user is unique. */ public static final String UNIONID = "unionid"; /** * <p>Constructor for WechatProfileDefinition.</p> */ public WechatProfileDefinition() { Arrays.stream(new String[]{ OPENID, NICKNAME, PROVINCE, CITY, COUNTRY, PRIVILEGE, UNIONID }).forEach(a -> primary(a, Converters.STRING)); primary(SEX, new GenderConverter("1", "2")); primary(HEADIMGURL, Converters.URL); } /** {@inheritDoc} */ @Override public String getProfileUrl(final Token accessToken, final OAuthConfiguration configuration) { if (accessToken instanceof WechatToken token) { String profileUrl; if (WechatClient.WechatScope.SNSAPI_BASE.toString().equalsIgnoreCase(token.getScope())) { profileUrl = "https://api.weixin.qq.com/sns/auth?openid=" + token.getOpenid(); } else { profileUrl = "https://api.weixin.qq.com/sns/userinfo?openid=" + token.getOpenid(); } return profileUrl; } else { throw new OAuthException("Token in getProfileUrl is not an WechatToken"); } } /** {@inheritDoc} */ @Override public WechatProfile extractUserProfile(String body) {<FILL_FUNCTION_BODY>} }
val profile = new WechatProfile(); val json = JsonHelper.getFirstNode(body); if (json != null) { var errcode = (Integer) JsonHelper.getElement(json, "errcode"); if (errcode != null && errcode > 0) { var errmsg = JsonHelper.getElement(json, "errmsg"); throw new OAuthException( errmsg != null ? errmsg.toString() : "error code " + errcode); } for (val attribute : getPrimaryAttributes()) { convertAndAdd(profile, PROFILE_ATTRIBUTE, attribute, JsonHelper.getElement(json, attribute)); } } else { raiseProfileExtractionJsonError(body); } return profile;
779
190
969
<methods>public void <init>() ,public void <init>(org.pac4j.core.profile.factory.ProfileFactory) ,public abstract org.pac4j.core.profile.CommonProfile extractUserProfile(java.lang.String) ,public abstract java.lang.String getProfileUrl(com.github.scribejava.core.model.Token, org.pac4j.oauth.config.OAuthConfiguration) ,public com.github.scribejava.core.model.Verb getProfileVerb() <variables>
pac4j_pac4j
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/profile/weibo/WeiboProfile.java
WeiboProfile
getProfileUrl
class WeiboProfile extends OAuth20Profile { @Serial private static final long serialVersionUID = -7486869356444327783L; /** {@inheritDoc} */ @Override public String getFirstName() { return (String) getAttribute(WeiboProfileDefinition.NAME); } /** {@inheritDoc} */ @Override public String getDisplayName() { return (String) getAttribute(WeiboProfileDefinition.SCREEN_NAME); } /** {@inheritDoc} */ @Override public String getUsername() { return (String) getAttribute(WeiboProfileDefinition.SCREEN_NAME); } /** {@inheritDoc} */ @Override public Locale getLocale() { return (Locale) getAttribute(WeiboProfileDefinition.LANG); } /** {@inheritDoc} */ @Override public URI getPictureUrl() { return (URI) getAttribute(WeiboProfileDefinition.AVATAR_HD); } /** {@inheritDoc} */ @Override public URI getProfileUrl() {<FILL_FUNCTION_BODY>} }
val attribute = (URI) getAttribute(WeiboProfileDefinition.PROFILE_URL); if (attribute.isAbsolute()) { return attribute; } else { return CommonHelper.asURI("http://weibo.com/" + attribute.toString()); }
312
71
383
<methods>public non-sealed void <init>() ,public java.lang.String getAccessToken() ,public java.lang.String getRefreshToken() ,public void removeLoginData() ,public void setAccessToken(java.lang.String) ,public void setRefreshToken(java.lang.String) <variables>private static final java.lang.String ACCESS_TOKEN,private static final java.lang.String REFRESH_TOKEN,private static final long serialVersionUID
pac4j_pac4j
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/profile/windowslive/WindowsLiveProfileDefinition.java
WindowsLiveProfileDefinition
extractUserProfile
class WindowsLiveProfileDefinition extends OAuthProfileDefinition { /** Constant <code>NAME="name"</code> */ public static final String NAME = "name"; /** Constant <code>LAST_NAME="last_name"</code> */ public static final String LAST_NAME = "last_name"; /** Constant <code>LINK="link"</code> */ public static final String LINK = "link"; /** * <p>Constructor for WindowsLiveProfileDefinition.</p> */ public WindowsLiveProfileDefinition() { super(x -> new WindowsLiveProfile()); Arrays.stream(new String[] {NAME, LAST_NAME}).forEach(a -> primary(a, Converters.STRING)); primary(LINK, Converters.URL); } /** {@inheritDoc} */ @Override public String getProfileUrl(final Token accessToken, final OAuthConfiguration configuration) { return "https://apis.live.net/v5.0/me"; } /** {@inheritDoc} */ @Override public WindowsLiveProfile extractUserProfile(final String body) {<FILL_FUNCTION_BODY>} }
val profile = (WindowsLiveProfile) newProfile(); val json = JsonHelper.getFirstNode(body); if (json != null) { profile.setId(ProfileHelper.sanitizeIdentifier(JsonHelper.getElement(json, "id"))); for (val attribute : getPrimaryAttributes()) { convertAndAdd(profile, PROFILE_ATTRIBUTE, attribute, JsonHelper.getElement(json, attribute)); } } else { raiseProfileExtractionJsonError(body); } return profile;
302
132
434
<methods>public void <init>() ,public void <init>(org.pac4j.core.profile.factory.ProfileFactory) ,public abstract org.pac4j.core.profile.CommonProfile extractUserProfile(java.lang.String) ,public abstract java.lang.String getProfileUrl(com.github.scribejava.core.model.Token, org.pac4j.oauth.config.OAuthConfiguration) ,public com.github.scribejava.core.model.Verb getProfileVerb() <variables>
pac4j_pac4j
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/profile/wordpress/WordPressProfileDefinition.java
WordPressProfileDefinition
extractUserProfile
class WordPressProfileDefinition extends OAuthProfileDefinition { /** Constant <code>PRIMARY_BLOG="primary_blog"</code> */ public static final String PRIMARY_BLOG = "primary_blog"; /** Constant <code>AVATAR_URL="avatar_URL"</code> */ public static final String AVATAR_URL = "avatar_URL"; /** Constant <code>PROFILE_URL="profile_URL"</code> */ public static final String PROFILE_URL = "profile_URL"; /** Constant <code>LINKS="links"</code> */ public static final String LINKS = "links"; /** * <p>Constructor for WordPressProfileDefinition.</p> */ public WordPressProfileDefinition() { super(x -> new WordPressProfile()); primary(Pac4jConstants.USERNAME, Converters.STRING); primary(PRIMARY_BLOG, Converters.INTEGER); primary(AVATAR_URL, Converters.URL); primary(PROFILE_URL, Converters.URL); secondary(LINKS, new JsonConverter(WordPressLinks.class)); } /** {@inheritDoc} */ @Override public String getProfileUrl(final Token accessToken, final OAuthConfiguration configuration) { return "https://public-api.wordpress.com/rest/v1/me/?pretty=1"; } /** {@inheritDoc} */ @Override public WordPressProfile extractUserProfile(final String body) {<FILL_FUNCTION_BODY>} }
val profile = (WordPressProfile) newProfile(); var json = JsonHelper.getFirstNode(body); if (json != null) { profile.setId(ProfileHelper.sanitizeIdentifier(JsonHelper.getElement(json, "ID"))); for (val attribute : getPrimaryAttributes()) { convertAndAdd(profile, PROFILE_ATTRIBUTE, attribute, JsonHelper.getElement(json, attribute)); } json = json.get("meta"); if (json != null) { val attribute = WordPressProfileDefinition.LINKS; convertAndAdd(profile, PROFILE_ATTRIBUTE, attribute, JsonHelper.getElement(json, attribute)); } } else { raiseProfileExtractionJsonError(body); } return profile;
398
193
591
<methods>public void <init>() ,public void <init>(org.pac4j.core.profile.factory.ProfileFactory) ,public abstract org.pac4j.core.profile.CommonProfile extractUserProfile(java.lang.String) ,public abstract java.lang.String getProfileUrl(com.github.scribejava.core.model.Token, org.pac4j.oauth.config.OAuthConfiguration) ,public com.github.scribejava.core.model.Verb getProfileVerb() <variables>
pac4j_pac4j
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/profile/yahoo/YahooProfile.java
YahooProfile
getEmail
class YahooProfile extends OAuth10Profile { @Serial private static final long serialVersionUID = 791758805376191144L; /** {@inheritDoc} */ @Override public String getEmail() {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override public String getFirstName() { return (String) getAttribute(YahooProfileDefinition.GIVEN_NAME); } /** {@inheritDoc} */ @Override public String getFamilyName() { return (String) getAttribute(YahooProfileDefinition.FAMILY_NAME); } /** {@inheritDoc} */ @Override public String getDisplayName() { return getFirstName() + " " + getFamilyName(); } /** {@inheritDoc} */ @Override public String getUsername() { return (String) getAttribute(YahooProfileDefinition.NICKNAME); } /** {@inheritDoc} */ @Override public Locale getLocale() { return (Locale) getAttribute(YahooProfileDefinition.LANG); } /** {@inheritDoc} */ @Override public URI getPictureUrl() { val yahooImage = (YahooImage) getAttribute(YahooProfileDefinition.IMAGE); if (yahooImage != null) { return CommonHelper.asURI(yahooImage.getImageUrl()); } return null; } /** {@inheritDoc} */ @Override public URI getProfileUrl() { return (URI) getAttribute(YahooProfileDefinition.PROFILE_URL); } /** * <p>getAboutMe.</p> * * @return a {@link String} object */ public String getAboutMe() { return (String) getAttribute(YahooProfileDefinition.ABOUT_ME); } /** * <p>getAddresses.</p> * * @return a {@link List} object */ public List<YahooAddress> getAddresses() { return (List<YahooAddress>) getAttribute(YahooProfileDefinition.ADDRESSES); } /** * <p>getBirthYear.</p> * * @return a {@link Integer} object */ public Integer getBirthYear() { return (Integer) getAttribute(YahooProfileDefinition.BIRTH_YEAR); } /** * <p>getBirthdate.</p> * * @return a {@link Date} object */ public Date getBirthdate() { return (Date) getAttribute(YahooProfileDefinition.BIRTHDATE); } /** * <p>getCreated.</p> * * @return a {@link Date} object */ public Date getCreated() { return (Date) getAttribute(YahooProfileDefinition.CREATED); } /** * <p>getDisplayAge.</p> * * @return a {@link Integer} object */ public Integer getDisplayAge() { return (Integer) getAttribute(YahooProfileDefinition.DISPLAY_AGE); } /** * <p>getDisclosures.</p> * * @return a {@link List} object */ public List<YahooDisclosure> getDisclosures() { return (List<YahooDisclosure>) getAttribute(YahooProfileDefinition.DISCLOSURES); } /** * <p>getEmails.</p> * * @return a {@link List} object */ public List<YahooEmail> getEmails() { return (List<YahooEmail>) getAttribute(YahooProfileDefinition.EMAILS); } /** * <p>getImage.</p> * * @return a {@link YahooImage} object */ public YahooImage getImage() { return (YahooImage) getAttribute(YahooProfileDefinition.IMAGE); } /** * <p>getInterests.</p> * * @return a {@link List} object */ public List<YahooInterest> getInterests() { return (List<YahooInterest>) getAttribute(YahooProfileDefinition.INTERESTS); } /** * <p>getIsConnected.</p> * * @return a {@link Boolean} object */ public Boolean getIsConnected() { return (Boolean) getAttribute(YahooProfileDefinition.IS_CONNECTED); } /** * <p>getMemberSince.</p> * * @return a {@link Date} object */ public Date getMemberSince() { return (Date) getAttribute(YahooProfileDefinition.MEMBER_SINCE); } /** * <p>getTimeZone.</p> * * @return a {@link String} object */ public String getTimeZone() { return (String) getAttribute(YahooProfileDefinition.TIME_ZONE); } /** * <p>getUpdated.</p> * * @return a {@link Date} object */ public Date getUpdated() { return (Date) getAttribute(YahooProfileDefinition.UPDATED); } /** * <p>getUri.</p> * * @return a {@link String} object */ public String getUri() { return (String) getAttribute(YahooProfileDefinition.URI); } /** * <p>getAgeCategory.</p> * * @return a {@link String} object */ public String getAgeCategory() { return (String) getAttribute(YahooProfileDefinition.AGE_CATEGORY); } }
val emails = getEmails(); if (emails != null) { for (val email : emails) { if (email != null && (Boolean.TRUE.equals(email.getPrimary()) || emails.size() == 1)) { return email.getHandle(); } } } return null;
1,572
85
1,657
<methods>public non-sealed void <init>() ,public java.lang.String getAccessSecret() ,public void removeLoginData() ,public void setAccessSecret(java.lang.String) <variables>private static final transient java.lang.String ACCESS_SECRET,private static final long serialVersionUID
pac4j_pac4j
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/profile/yahoo/YahooProfileCreator.java
YahooProfileCreator
retrieveUserProfileFromToken
class YahooProfileCreator extends OAuth10ProfileCreator { /** * <p>Constructor for YahooProfileCreator.</p> * * @param configuration a {@link OAuth10Configuration} object * @param client a {@link IndirectClient} object */ public YahooProfileCreator(final OAuth10Configuration configuration, final IndirectClient client) { super(configuration, client); } /** {@inheritDoc} */ @Override protected Optional<UserProfile> retrieveUserProfileFromToken(final WebContext context, final Token accessToken) {<FILL_FUNCTION_BODY>} }
// get the guid: https://developer.yahoo.com/social/rest_api_guide/introspective-guid-resource.html val profileDefinition = configuration.getProfileDefinition(); val profileUrl = profileDefinition.getProfileUrl(accessToken, this.configuration); val service = (OAuth10aService) configuration.buildService(context, client); var body = sendRequestForData(service, accessToken, profileUrl, profileDefinition.getProfileVerb()); val guid = CommonHelper.substringBetween(body, "<value>", "</value>"); logger.debug("guid : {}", guid); if (CommonHelper.isBlank(guid)) { throw new HttpCommunicationException("Cannot find guid from body : " + body); } body = sendRequestForData(service, accessToken, "https://social.yahooapis.com/v1/user/" + guid + "/profile?format=json", Verb.GET); UserProfile profile = (YahooProfile) configuration.getProfileDefinition().extractUserProfile(body); addTokenToProfile(profile, accessToken); return Optional.of(profile);
162
285
447
<methods>public void <init>(org.pac4j.oauth.config.OAuth10Configuration, org.pac4j.core.client.IndirectClient) <variables>
pac4j_pac4j
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/profile/yahoo/YahooProfileDefinition.java
YahooProfileDefinition
extractUserProfile
class YahooProfileDefinition extends OAuthProfileDefinition { /** Constant <code>ABOUT_ME="aboutMe"</code> */ public static final String ABOUT_ME = "aboutMe"; /** Constant <code>AGE_CATEGORY="ageCategory"</code> */ public static final String AGE_CATEGORY = "ageCategory"; /** Constant <code>ADDRESSES="addresses"</code> */ public static final String ADDRESSES = "addresses"; /** Constant <code>BIRTH_YEAR="birthYear"</code> */ public static final String BIRTH_YEAR = "birthYear"; /** Constant <code>BIRTHDATE="birthdate"</code> */ public static final String BIRTHDATE = "birthdate"; /** Constant <code>CREATED="created"</code> */ public static final String CREATED = "created"; /** Constant <code>DISPLAY_AGE="displayAge"</code> */ public static final String DISPLAY_AGE = "displayAge"; /** Constant <code>DISCLOSURES="disclosures"</code> */ public static final String DISCLOSURES = "disclosures"; /** Constant <code>EMAILS="emails"</code> */ public static final String EMAILS = "emails"; /** Constant <code>FAMILY_NAME="familyName"</code> */ public static final String FAMILY_NAME = "familyName"; /** Constant <code>GIVEN_NAME="givenName"</code> */ public static final String GIVEN_NAME = "givenName"; /** Constant <code>IMAGE="image"</code> */ public static final String IMAGE = "image"; /** Constant <code>INTERESTS="interests"</code> */ public static final String INTERESTS = "interests"; /** Constant <code>IS_CONNECTED="isConnected"</code> */ public static final String IS_CONNECTED = "isConnected"; /** Constant <code>LANG="lang"</code> */ public static final String LANG = "lang"; /** Constant <code>MEMBER_SINCE="memberSince"</code> */ public static final String MEMBER_SINCE = "memberSince"; /** Constant <code>NICKNAME="nickname"</code> */ public static final String NICKNAME = "nickname"; /** Constant <code>PROFILE_URL="profileUrl"</code> */ public static final String PROFILE_URL = "profileUrl"; /** Constant <code>TIME_ZONE="timeZone"</code> */ public static final String TIME_ZONE = "timeZone"; /** Constant <code>UPDATED="updated"</code> */ public static final String UPDATED = "updated"; /** Constant <code>URI="uri"</code> */ public static final String URI = "uri"; /** * <p>Constructor for YahooProfileDefinition.</p> */ public YahooProfileDefinition() { super(x -> new YahooProfile()); Arrays.stream(new String[] {ABOUT_ME, FAMILY_NAME, GIVEN_NAME, NICKNAME, TIME_ZONE, URI, AGE_CATEGORY}) .forEach(a -> primary(a, Converters.STRING)); primary(IS_CONNECTED, Converters.BOOLEAN); primary(BIRTH_YEAR, Converters.INTEGER); primary(LANG, Converters.LOCALE); primary(DISPLAY_AGE, Converters.INTEGER); primary(BIRTHDATE, new DateConverter("MM/dd")); primary(ADDRESSES, new JsonConverter(List.class, new TypeReference<List<YahooAddress>>() {})); primary(DISCLOSURES, new JsonConverter(List.class, new TypeReference<List<YahooDisclosure>>() {})); primary(EMAILS, new JsonConverter(List.class, new TypeReference<List<YahooEmail>>() {})); primary(IMAGE, new JsonConverter(YahooImage.class)); primary(INTERESTS, new JsonConverter(List.class, new TypeReference<List<YahooInterest>>() {})); primary(CREATED, Converters.DATE_TZ_RFC822); primary(MEMBER_SINCE, Converters.DATE_TZ_RFC822); primary(UPDATED, Converters.DATE_TZ_RFC822); primary(PROFILE_URL, Converters.URL); } /** {@inheritDoc} */ @Override public String getProfileUrl(final Token accessToken, final OAuthConfiguration configuration) { return "https://social.yahooapis.com/v1/me/guid?format=xml"; } /** {@inheritDoc} */ @Override public YahooProfile extractUserProfile(final String body) {<FILL_FUNCTION_BODY>} }
val profile = (YahooProfile) newProfile(); var json = JsonHelper.getFirstNode(body); if (json != null) { json = json.get("profile"); if (json != null) { profile.setId(ProfileHelper.sanitizeIdentifier(JsonHelper.getElement(json, "guid"))); for (val attribute : getPrimaryAttributes()) { convertAndAdd(profile, PROFILE_ATTRIBUTE, attribute, JsonHelper.getElement(json, attribute)); } } else { raiseProfileExtractionJsonError(body, "profile"); } } else { raiseProfileExtractionJsonError(body); } return profile;
1,323
176
1,499
<methods>public void <init>() ,public void <init>(org.pac4j.core.profile.factory.ProfileFactory) ,public abstract org.pac4j.core.profile.CommonProfile extractUserProfile(java.lang.String) ,public abstract java.lang.String getProfileUrl(com.github.scribejava.core.model.Token, org.pac4j.oauth.config.OAuthConfiguration) ,public com.github.scribejava.core.model.Verb getProfileVerb() <variables>
pac4j_pac4j
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/redirect/OAuth10RedirectionActionBuilder.java
OAuth10RedirectionActionBuilder
getRedirectionAction
class OAuth10RedirectionActionBuilder implements RedirectionActionBuilder { protected OAuth10Configuration configuration; protected IndirectClient client; /** * <p>Constructor for OAuth10RedirectionActionBuilder.</p> * * @param configuration a {@link OAuth10Configuration} object * @param client a {@link IndirectClient} object */ public OAuth10RedirectionActionBuilder(final OAuth10Configuration configuration, final IndirectClient client) { CommonHelper.assertNotNull("client", client); CommonHelper.assertNotNull("configuration", configuration); this.configuration = configuration; this.client = client; } /** {@inheritDoc} */ @Override public Optional<RedirectionAction> getRedirectionAction(final CallContext ctx) {<FILL_FUNCTION_BODY>} }
try { val webContext = ctx.webContext(); val service = (OAuth10aService) this.configuration.buildService(webContext, client); final OAuth1RequestToken requestToken; try { requestToken = service.getRequestToken(); } catch (final IOException | InterruptedException | ExecutionException e) { throw new HttpCommunicationException("Error getting token: " + e.getMessage()); } LOGGER.debug("requestToken: {}", requestToken); // save requestToken in user session ctx.sessionStore().set(webContext, configuration.getRequestTokenSessionAttributeName(client.getName()), requestToken); val authorizationUrl = service.getAuthorizationUrl(requestToken); LOGGER.debug("authorizationUrl: {}", authorizationUrl); return Optional.of(HttpActionHelper.buildRedirectUrlAction(webContext, authorizationUrl)); } catch (final OAuthException e) { throw new TechnicalException(e); }
214
247
461
<no_super_class>
pac4j_pac4j
pac4j/pac4j-oauth/src/main/java/org/pac4j/oauth/redirect/OAuth20RedirectionActionBuilder.java
OAuth20RedirectionActionBuilder
getRedirectionAction
class OAuth20RedirectionActionBuilder implements RedirectionActionBuilder { protected OAuth20Configuration configuration; protected IndirectClient client; /** * <p>Constructor for OAuth20RedirectionActionBuilder.</p> * * @param configuration a {@link OAuth20Configuration} object * @param client a {@link IndirectClient} object */ public OAuth20RedirectionActionBuilder(final OAuth20Configuration configuration, final IndirectClient client) { CommonHelper.assertNotNull("client", client); CommonHelper.assertNotNull("configuration", configuration); this.configuration = configuration; this.client = client; } /** {@inheritDoc} */ @Override public Optional<RedirectionAction> getRedirectionAction(final CallContext ctx) {<FILL_FUNCTION_BODY>} }
val webContext = ctx.webContext(); try { final String state; if (configuration.isWithState()) { state = this.configuration.getStateGenerator().generateValue(ctx); LOGGER.debug("save sessionState: {}", state); ctx.sessionStore().set(webContext, client.getStateSessionAttributeName(), state); } else { state = null; } val service = (OAuth20Service) this.configuration.buildService(webContext, client); val authorizationUrl = new AuthorizationUrlBuilder(service) .state(state).additionalParams(this.configuration.getCustomParams()).build(); LOGGER.debug("authorizationUrl: {}", authorizationUrl); return Optional.of(HttpActionHelper.buildRedirectUrlAction(webContext, authorizationUrl)); } catch (final OAuthException e) { throw new TechnicalException(e); }
214
231
445
<no_super_class>
pac4j_pac4j
pac4j/pac4j-oauth/src/main/java/org/pac4j/scribe/builder/api/CasOAuthWrapperApi20.java
CasOAuthWrapperApi20
getAccessTokenExtractor
class CasOAuthWrapperApi20 extends DefaultApi20 { private final String casServerUrl; private final boolean isJsonTokenExtractor; private final Verb accessTokenVerb; /** {@inheritDoc} */ @Override public TokenExtractor<OAuth2AccessToken> getAccessTokenExtractor() {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override public String getAccessTokenEndpoint() { return this.casServerUrl + "/accessToken?"; } /** {@inheritDoc} */ @Override protected String getAuthorizationBaseUrl() { return this.casServerUrl + "/authorize"; } }
if (this.isJsonTokenExtractor) { return OAuth2AccessTokenJsonExtractor.instance(); } else { return OAuth2AccessTokenExtractor.instance(); }
176
51
227
<methods>public void <init>() ,public com.github.scribejava.core.oauth.OAuth20Service createService(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.io.OutputStream, java.lang.String, com.github.scribejava.core.httpclient.HttpClientConfig, com.github.scribejava.core.httpclient.HttpClient) ,public abstract java.lang.String getAccessTokenEndpoint() ,public TokenExtractor<com.github.scribejava.core.model.OAuth2AccessToken> getAccessTokenExtractor() ,public com.github.scribejava.core.model.Verb getAccessTokenVerb() ,public java.lang.String getAuthorizationUrl(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, Map<java.lang.String,java.lang.String>) ,public com.github.scribejava.core.oauth2.bearersignature.BearerSignature getBearerSignature() ,public com.github.scribejava.core.oauth2.clientauthentication.ClientAuthentication getClientAuthentication() ,public java.lang.String getDeviceAuthorizationEndpoint() ,public com.github.scribejava.core.extractors.DeviceAuthorizationJsonExtractor getDeviceAuthorizationExtractor() ,public java.lang.String getRefreshTokenEndpoint() ,public java.lang.String getRevokeTokenEndpoint() <variables>
pac4j_pac4j
pac4j/pac4j-oauth/src/main/java/org/pac4j/scribe/builder/api/CronofyApi20.java
CronofyApi20
computeBaseUrl
class CronofyApi20 extends DefaultApi20 { private final String sdkIdentifier; /** * <p>Constructor for CronofyApi20.</p> * * @param sdkIdentifier a {@link String} object */ public CronofyApi20(final String sdkIdentifier) { this.sdkIdentifier = sdkIdentifier; } /** {@inheritDoc} */ @Override public String getAccessTokenEndpoint() { return computeBaseUrl() + "/oauth/token"; } /** {@inheritDoc} */ @Override protected String getAuthorizationBaseUrl() { return computeBaseUrl() + "/oauth/authorize"; } private String computeBaseUrl() {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override public OAuth20Service createService(String apiKey, String apiSecret, String callback, String defaultScope, String responseType, OutputStream debugStream, String userAgent, HttpClientConfig httpClientConfig, HttpClient httpClient) { return new CronofyService(this, apiKey, apiSecret, callback, defaultScope, responseType, debugStream, userAgent, httpClientConfig, httpClient); } }
if (CommonHelper.isNotBlank(sdkIdentifier)) { return "https://app-" + sdkIdentifier + ".cronofy.com"; } else { return "https://app.cronofy.com"; }
320
63
383
<methods>public void <init>() ,public com.github.scribejava.core.oauth.OAuth20Service createService(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.io.OutputStream, java.lang.String, com.github.scribejava.core.httpclient.HttpClientConfig, com.github.scribejava.core.httpclient.HttpClient) ,public abstract java.lang.String getAccessTokenEndpoint() ,public TokenExtractor<com.github.scribejava.core.model.OAuth2AccessToken> getAccessTokenExtractor() ,public com.github.scribejava.core.model.Verb getAccessTokenVerb() ,public java.lang.String getAuthorizationUrl(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, Map<java.lang.String,java.lang.String>) ,public com.github.scribejava.core.oauth2.bearersignature.BearerSignature getBearerSignature() ,public com.github.scribejava.core.oauth2.clientauthentication.ClientAuthentication getClientAuthentication() ,public java.lang.String getDeviceAuthorizationEndpoint() ,public com.github.scribejava.core.extractors.DeviceAuthorizationJsonExtractor getDeviceAuthorizationExtractor() ,public java.lang.String getRefreshTokenEndpoint() ,public java.lang.String getRevokeTokenEndpoint() <variables>
pac4j_pac4j
pac4j/pac4j-oauth/src/main/java/org/pac4j/scribe/builder/api/FigShareApi20.java
Service
createService
class Service extends OAuth20Service { public Service(DefaultApi20 api, String apiKey, String apiSecret, String callback, String defaultScope, String responseType, OutputStream debugStream, String userAgent, HttpClientConfig httpClientConfig, HttpClient httpClient) { super(api, apiKey, apiSecret, callback, defaultScope, responseType, debugStream, userAgent, httpClientConfig, httpClient); } @Override protected OAuthRequest createAccessTokenRequest(AccessTokenRequestParams params) { val request = super.createAccessTokenRequest(params); request.addParameter(OAuthConstants.CLIENT_ID, getApiKey()); request.addParameter(OAuthConstants.CLIENT_SECRET, getApiSecret()); return request; } } /** {@inheritDoc} */ @Override public OAuth20Service createService(String apiKey, String apiSecret, String callback, String defaultScope, String responseType, OutputStream debugStream, String userAgent, HttpClientConfig httpClientConfig, HttpClient httpClient) {<FILL_FUNCTION_BODY>
return new Service(this, apiKey, apiSecret, callback, defaultScope, responseType, debugStream, userAgent, httpClientConfig, httpClient);
268
40
308
<methods>public void <init>() ,public com.github.scribejava.core.oauth.OAuth20Service createService(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.io.OutputStream, java.lang.String, com.github.scribejava.core.httpclient.HttpClientConfig, com.github.scribejava.core.httpclient.HttpClient) ,public abstract java.lang.String getAccessTokenEndpoint() ,public TokenExtractor<com.github.scribejava.core.model.OAuth2AccessToken> getAccessTokenExtractor() ,public com.github.scribejava.core.model.Verb getAccessTokenVerb() ,public java.lang.String getAuthorizationUrl(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, Map<java.lang.String,java.lang.String>) ,public com.github.scribejava.core.oauth2.bearersignature.BearerSignature getBearerSignature() ,public com.github.scribejava.core.oauth2.clientauthentication.ClientAuthentication getClientAuthentication() ,public java.lang.String getDeviceAuthorizationEndpoint() ,public com.github.scribejava.core.extractors.DeviceAuthorizationJsonExtractor getDeviceAuthorizationExtractor() ,public java.lang.String getRefreshTokenEndpoint() ,public java.lang.String getRevokeTokenEndpoint() <variables>
pac4j_pac4j
pac4j/pac4j-oauth/src/main/java/org/pac4j/scribe/builder/api/GenericApi20.java
GenericApi20
getClientAuthentication
class GenericApi20 extends DefaultApi20 { /** Constant <code>BASIC_AUTH_AUTHENTICATION_METHOD="basicAuth"</code> */ public static final String BASIC_AUTH_AUTHENTICATION_METHOD = "basicAuth"; /** Constant <code>REQUEST_BODY_AUTHENTICATION_METHOD="requestBody"</code> */ public static final String REQUEST_BODY_AUTHENTICATION_METHOD = "requestBody"; protected final String authUrl; protected final String tokenUrl; protected Verb accessTokenVerb = Verb.POST; protected String clientAuthenticationMethod = BASIC_AUTH_AUTHENTICATION_METHOD; /** * <p>Constructor for GenericApi20.</p> * * @param authUrl a {@link String} object * @param tokenUrl a {@link String} object */ public GenericApi20(final String authUrl, final String tokenUrl) { this.authUrl = authUrl; this.tokenUrl = tokenUrl; } /** {@inheritDoc} */ @Override public Verb getAccessTokenVerb() { return accessTokenVerb; } /** * <p>Setter for the field <code>accessTokenVerb</code>.</p> * * @param verb a {@link Verb} object */ public void setAccessTokenVerb(final Verb verb) { accessTokenVerb = verb; } /** {@inheritDoc} */ @Override public String getAccessTokenEndpoint() { return tokenUrl; } /** {@inheritDoc} */ @Override protected String getAuthorizationBaseUrl() { return authUrl; } /** * <p>Getter for the field <code>clientAuthenticationMethod</code>.</p> * * @return a {@link String} object */ public String getClientAuthenticationMethod() { return clientAuthenticationMethod; } /** * <p>Setter for the field <code>clientAuthenticationMethod</code>.</p> * * @param clientAuthenticationMethod a {@link String} object */ public void setClientAuthenticationMethod(final String clientAuthenticationMethod) { this.clientAuthenticationMethod = clientAuthenticationMethod; } /** {@inheritDoc} */ @Override public ClientAuthentication getClientAuthentication() {<FILL_FUNCTION_BODY>} }
if (BASIC_AUTH_AUTHENTICATION_METHOD.equalsIgnoreCase(clientAuthenticationMethod)) { return HttpBasicAuthenticationScheme.instance(); } else if (REQUEST_BODY_AUTHENTICATION_METHOD.equalsIgnoreCase(clientAuthenticationMethod)) { return RequestBodyAuthenticationScheme.instance(); } else { throw new TechnicalException("Unsupported client authentication method: " + clientAuthenticationMethod); }
631
107
738
<methods>public void <init>() ,public com.github.scribejava.core.oauth.OAuth20Service createService(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.io.OutputStream, java.lang.String, com.github.scribejava.core.httpclient.HttpClientConfig, com.github.scribejava.core.httpclient.HttpClient) ,public abstract java.lang.String getAccessTokenEndpoint() ,public TokenExtractor<com.github.scribejava.core.model.OAuth2AccessToken> getAccessTokenExtractor() ,public com.github.scribejava.core.model.Verb getAccessTokenVerb() ,public java.lang.String getAuthorizationUrl(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, Map<java.lang.String,java.lang.String>) ,public com.github.scribejava.core.oauth2.bearersignature.BearerSignature getBearerSignature() ,public com.github.scribejava.core.oauth2.clientauthentication.ClientAuthentication getClientAuthentication() ,public java.lang.String getDeviceAuthorizationEndpoint() ,public com.github.scribejava.core.extractors.DeviceAuthorizationJsonExtractor getDeviceAuthorizationExtractor() ,public java.lang.String getRefreshTokenEndpoint() ,public java.lang.String getRevokeTokenEndpoint() <variables>
pac4j_pac4j
pac4j/pac4j-oauth/src/main/java/org/pac4j/scribe/builder/api/PayPalApi20.java
PayPalApi20
getAuthorizationUrl
class PayPalApi20 extends DefaultApi20 { /** {@inheritDoc} */ @Override public String getAuthorizationUrl(String responseType, String apiKey, String callback, String scope, String state, Map<String, String> additionalParams) {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override protected String getAuthorizationBaseUrl() { return "https://www.paypal.com/webapps/auth/protocol/openidconnect/v1/authorize"; } /** {@inheritDoc} */ @Override public String getAccessTokenEndpoint() { return "https://api.paypal.com/v1/identity/openidconnect/tokenservice"; } }
CommonHelper.assertNotBlank("callback", callback, "Must provide a valid url as callback. PayPal does not support OOB"); if (additionalParams == null) { additionalParams = new HashMap<>(); } val nonce = System.currentTimeMillis() + CommonHelper.randomString(10); additionalParams.put("nonce", nonce); return super.getAuthorizationUrl(responseType, apiKey, callback, scope, state, additionalParams);
187
122
309
<methods>public void <init>() ,public com.github.scribejava.core.oauth.OAuth20Service createService(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.io.OutputStream, java.lang.String, com.github.scribejava.core.httpclient.HttpClientConfig, com.github.scribejava.core.httpclient.HttpClient) ,public abstract java.lang.String getAccessTokenEndpoint() ,public TokenExtractor<com.github.scribejava.core.model.OAuth2AccessToken> getAccessTokenExtractor() ,public com.github.scribejava.core.model.Verb getAccessTokenVerb() ,public java.lang.String getAuthorizationUrl(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, Map<java.lang.String,java.lang.String>) ,public com.github.scribejava.core.oauth2.bearersignature.BearerSignature getBearerSignature() ,public com.github.scribejava.core.oauth2.clientauthentication.ClientAuthentication getClientAuthentication() ,public java.lang.String getDeviceAuthorizationEndpoint() ,public com.github.scribejava.core.extractors.DeviceAuthorizationJsonExtractor getDeviceAuthorizationExtractor() ,public java.lang.String getRefreshTokenEndpoint() ,public java.lang.String getRevokeTokenEndpoint() <variables>
pac4j_pac4j
pac4j/pac4j-oauth/src/main/java/org/pac4j/scribe/builder/api/StravaApi20.java
StravaApi20
getAuthorizationUrl
class StravaApi20 extends DefaultApi20 { /** * Strava authorization URL */ private static final String AUTHORIZE_BASE_URL = "https://www.strava.com/oauth/authorize"; private static final String ACCESS_TOKEN_URL = "https://www.strava.com/oauth/token"; /** * possible values: auto or force. If force, the authorisation dialog is always displayed by Strava. */ private String approvalPrompt; /** * <p>Constructor for StravaApi20.</p> * * @param approvalPrompt a {@link String} object */ public StravaApi20(String approvalPrompt) { this.approvalPrompt = approvalPrompt; } /** {@inheritDoc} */ @Override public String getAccessTokenEndpoint() { return ACCESS_TOKEN_URL; } /** {@inheritDoc} */ @Override public Verb getAccessTokenVerb() { return Verb.POST; } /** {@inheritDoc} */ @Override public String getAuthorizationUrl(String responseType, String apiKey, String callback, String scope, String state, Map<String, String> additionalParams) {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override protected String getAuthorizationBaseUrl() { return AUTHORIZE_BASE_URL; } }
CommonHelper.assertNotBlank("callback", callback, "Must provide a valid callback url."); if (additionalParams == null) { additionalParams = new HashMap<>(); } additionalParams.put("approval_prompt=", this.approvalPrompt); return super.getAuthorizationUrl(responseType, apiKey, callback, scope, state, additionalParams);
382
96
478
<methods>public void <init>() ,public com.github.scribejava.core.oauth.OAuth20Service createService(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.io.OutputStream, java.lang.String, com.github.scribejava.core.httpclient.HttpClientConfig, com.github.scribejava.core.httpclient.HttpClient) ,public abstract java.lang.String getAccessTokenEndpoint() ,public TokenExtractor<com.github.scribejava.core.model.OAuth2AccessToken> getAccessTokenExtractor() ,public com.github.scribejava.core.model.Verb getAccessTokenVerb() ,public java.lang.String getAuthorizationUrl(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, Map<java.lang.String,java.lang.String>) ,public com.github.scribejava.core.oauth2.bearersignature.BearerSignature getBearerSignature() ,public com.github.scribejava.core.oauth2.clientauthentication.ClientAuthentication getClientAuthentication() ,public java.lang.String getDeviceAuthorizationEndpoint() ,public com.github.scribejava.core.extractors.DeviceAuthorizationJsonExtractor getDeviceAuthorizationExtractor() ,public java.lang.String getRefreshTokenEndpoint() ,public java.lang.String getRevokeTokenEndpoint() <variables>
pac4j_pac4j
pac4j/pac4j-oauth/src/main/java/org/pac4j/scribe/builder/api/WechatApi20.java
InstanceHolder
createService
class InstanceHolder { private static final WechatApi20 INSTANCE = new WechatApi20(); } /** * <p>instance.</p> * * @return a {@link WechatApi20} object */ public static WechatApi20 instance() { return WechatApi20.InstanceHolder.INSTANCE; } /** {@inheritDoc} */ @Override public String getAccessTokenEndpoint() { return TOKEN_ENDPOINT_URL + "?grant_type=authorization_code"; } /** {@inheritDoc} */ @Override public String getAuthorizationUrl(String responseType, String apiKey, String callback, String scope, String state, Map<String, String> additionalParams) { var authorizationUrl = super.getAuthorizationUrl(responseType, apiKey, callback, scope, state, additionalParams); authorizationUrl = authorizationUrl.replace(OAuthConstants.CLIENT_ID, APPID); if (scope != null && scope.contains( WechatClient.WechatScope.SNSAPI_LOGIN.toString().toLowerCase())) { authorizationUrl = AUTHORIZE_ENDPOINT_URL_1 + authorizationUrl; } else { authorizationUrl = AUTHORIZE_ENDPOINT_URL_2 + authorizationUrl; } return authorizationUrl; } /** {@inheritDoc} */ @Override protected String getAuthorizationBaseUrl() { return Pac4jConstants.EMPTY_STRING; } /** {@inheritDoc} */ @Override public Verb getAccessTokenVerb() { return Verb.GET; } /** {@inheritDoc} */ @Override public TokenExtractor<OAuth2AccessToken> getAccessTokenExtractor() { return WechatJsonExtractor.instance(); } /** {@inheritDoc} */ @Override public OAuth20Service createService(String apiKey, String apiSecret, String callback, String defaultScope, String responseType, OutputStream debugStream, String userAgent, HttpClientConfig httpClientConfig, HttpClient httpClient) {<FILL_FUNCTION_BODY>
return new WechatService(this, apiKey, apiSecret, callback, defaultScope, responseType, userAgent, httpClientConfig, httpClient);
562
37
599
<methods>public void <init>() ,public com.github.scribejava.core.oauth.OAuth20Service createService(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.io.OutputStream, java.lang.String, com.github.scribejava.core.httpclient.HttpClientConfig, com.github.scribejava.core.httpclient.HttpClient) ,public abstract java.lang.String getAccessTokenEndpoint() ,public TokenExtractor<com.github.scribejava.core.model.OAuth2AccessToken> getAccessTokenExtractor() ,public com.github.scribejava.core.model.Verb getAccessTokenVerb() ,public java.lang.String getAuthorizationUrl(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, Map<java.lang.String,java.lang.String>) ,public com.github.scribejava.core.oauth2.bearersignature.BearerSignature getBearerSignature() ,public com.github.scribejava.core.oauth2.clientauthentication.ClientAuthentication getClientAuthentication() ,public java.lang.String getDeviceAuthorizationEndpoint() ,public com.github.scribejava.core.extractors.DeviceAuthorizationJsonExtractor getDeviceAuthorizationExtractor() ,public java.lang.String getRefreshTokenEndpoint() ,public java.lang.String getRevokeTokenEndpoint() <variables>
pac4j_pac4j
pac4j/pac4j-oauth/src/main/java/org/pac4j/scribe/extractors/WechatJsonExtractor.java
InstanceHolder
createToken
class InstanceHolder { private static final WechatJsonExtractor INSTANCE = new WechatJsonExtractor(); } /** * <p>instance.</p> * * @return a {@link WechatJsonExtractor} object */ public static WechatJsonExtractor instance() { return WechatJsonExtractor.InstanceHolder.INSTANCE; } /** {@inheritDoc} */ @Override protected OAuth2AccessToken createToken(String accessToken, String tokenType, Integer expiresIn, String refreshToken, String scope, JsonNode response, String rawResponse) {<FILL_FUNCTION_BODY>
var openid = extractRequiredParameter(response, "openid", rawResponse).asText(); var unionid = extractRequiredParameter(response, "unionid", rawResponse).asText(); var token = new WechatToken(accessToken, tokenType, expiresIn, refreshToken, scope, rawResponse, openid, unionid); return token;
164
86
250
<methods>public com.github.scribejava.core.model.OAuth2AccessToken extract(com.github.scribejava.core.model.Response) throws java.io.IOException,public void generateError(com.github.scribejava.core.model.Response) throws java.io.IOException,public static com.github.scribejava.core.extractors.OAuth2AccessTokenJsonExtractor instance() <variables>
pac4j_pac4j
pac4j/pac4j-oauth/src/main/java/org/pac4j/scribe/extractors/WeiboJsonExtractor.java
InstanceHolder
createToken
class InstanceHolder { private static final WeiboJsonExtractor INSTANCE = new WeiboJsonExtractor(); } /** * <p>instance.</p> * * @return a {@link WeiboJsonExtractor} object */ public static WeiboJsonExtractor instance() { return WeiboJsonExtractor.InstanceHolder.INSTANCE; } /** {@inheritDoc} */ @Override protected OAuth2AccessToken createToken(String accessToken, String tokenType, Integer expiresIn, String refreshToken, String scope, JsonNode response, String rawResponse) {<FILL_FUNCTION_BODY>
var token = super.createToken(accessToken, tokenType, expiresIn, refreshToken, scope, response, rawResponse); var uid = extractRequiredParameter(response, "uid", rawResponse).asText(); if (uid == null || Pac4jConstants.EMPTY_STRING.equals(uid)) { throw new OAuthException( "There is no required UID in the response of the AssessToken endpoint."); } return new WeiboToken(token, uid);
168
124
292
<methods>public com.github.scribejava.core.model.OAuth2AccessToken extract(com.github.scribejava.core.model.Response) throws java.io.IOException,public void generateError(com.github.scribejava.core.model.Response) throws java.io.IOException,public static com.github.scribejava.core.extractors.OAuth2AccessTokenJsonExtractor instance() <variables>
pac4j_pac4j
pac4j/pac4j-oauth/src/main/java/org/pac4j/scribe/model/WeiboToken.java
WeiboToken
hashCode
class WeiboToken extends OAuth2AccessToken { @Serial private static final long serialVersionUID = 1489916603771001585L; private String uid; /** * <p>Constructor for WeiboToken.</p> * * @param accessToken a {@link OAuth2AccessToken} object * @param uid a {@link String} object */ public WeiboToken(OAuth2AccessToken accessToken, String uid) { super(accessToken.getAccessToken(), accessToken.getTokenType(), accessToken.getExpiresIn(), accessToken.getRefreshToken(), accessToken.getScope(), accessToken.getRawResponse()); this.uid = uid; } /** * <p>Getter for the field <code>uid</code>.</p> * * @return a {@link String} object */ public String getUid() { return uid; } /** * <p>Setter for the field <code>uid</code>.</p> * * @param uid a {@link String} object */ public void setUid(String uid) { this.uid = uid; } /** {@inheritDoc} */ @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof WeiboToken that)) return false; if (!super.equals(o)) return false; return uid != null ? uid.equals(that.uid) : that.uid == null; } /** {@inheritDoc} */ @Override public int hashCode() {<FILL_FUNCTION_BODY>} }
var result = super.hashCode(); result = 31 * result + (uid != null ? uid.hashCode() : 0); return result;
460
43
503
<methods>public void <init>(java.lang.String) ,public void <init>(java.lang.String, java.lang.String) ,public void <init>(java.lang.String, java.lang.String, java.lang.Integer, java.lang.String, java.lang.String, java.lang.String) ,public boolean equals(java.lang.Object) ,public java.lang.String getAccessToken() ,public java.lang.Integer getExpiresIn() ,public java.lang.String getRefreshToken() ,public java.lang.String getScope() ,public java.lang.String getTokenType() ,public int hashCode() <variables>private java.lang.String accessToken,private java.lang.Integer expiresIn,private java.lang.String refreshToken,private java.lang.String scope,private static final long serialVersionUID,private java.lang.String tokenType
pac4j_pac4j
pac4j/pac4j-oauth/src/main/java/org/pac4j/scribe/service/CronofyService.java
CronofyService
createAccessTokenRequest
class CronofyService extends OAuth20Service { private final DefaultApi20 api; /** * <p>Constructor for CronofyService.</p> * * @param api a {@link DefaultApi20} object * @param apiKey a {@link String} object * @param apiSecret a {@link String} object * @param callback a {@link String} object * @param defaultScope a {@link String} object * @param responseType a {@link String} object * @param debugStream a {@link OutputStream} object * @param userAgent a {@link String} object * @param httpClientConfig a {@link HttpClientConfig} object * @param httpClient a {@link HttpClient} object */ public CronofyService(final DefaultApi20 api, final String apiKey, final String apiSecret, final String callback, final String defaultScope, final String responseType, final OutputStream debugStream, final String userAgent, final HttpClientConfig httpClientConfig, final HttpClient httpClient) { super(api, apiKey, apiSecret, callback, defaultScope, responseType, debugStream, userAgent, httpClientConfig, httpClient); this.api = api; } /** {@inheritDoc} */ protected OAuthRequest createAccessTokenRequest(AccessTokenRequestParams params) {<FILL_FUNCTION_BODY>} }
final OAuthRequest request = new OAuthRequest(api.getAccessTokenVerb(), api.getAccessTokenEndpoint()); final Map<String, String> map = new HashMap<>(); map.put("client_id", getApiKey()); map.put("client_secret", getApiSecret()); map.put(OAuthConstants.GRANT_TYPE, OAuthConstants.AUTHORIZATION_CODE); map.put(OAuthConstants.CODE, params.getCode()); map.put(OAuthConstants.REDIRECT_URI, getCallback()); final String json; try { json = JsonHelper.getMapper().writeValueAsString(map); } catch (final JsonProcessingException e) { throw new TechnicalException(e); } request.setPayload(json); request.addHeader("Content-Type", "application/json; charset=utf-8"); logRequestWithParams("access token", request); return request;
344
241
585
<methods>public void <init>(com.github.scribejava.core.builder.api.DefaultApi20, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.io.OutputStream, java.lang.String, com.github.scribejava.core.httpclient.HttpClientConfig, com.github.scribejava.core.httpclient.HttpClient) ,public com.github.scribejava.core.oauth.AuthorizationUrlBuilder createAuthorizationUrlBuilder() ,public com.github.scribejava.core.model.OAuth2Authorization extractAuthorization(java.lang.String) ,public com.github.scribejava.core.model.OAuth2AccessToken getAccessToken(java.lang.String) throws java.io.IOException, java.lang.InterruptedException, java.util.concurrent.ExecutionException,public com.github.scribejava.core.model.OAuth2AccessToken getAccessToken(com.github.scribejava.core.oauth.AccessTokenRequestParams) throws java.io.IOException, java.lang.InterruptedException, java.util.concurrent.ExecutionException,public Future<com.github.scribejava.core.model.OAuth2AccessToken> getAccessToken(com.github.scribejava.core.oauth.AccessTokenRequestParams, OAuthAsyncRequestCallback<com.github.scribejava.core.model.OAuth2AccessToken>) ,public Future<com.github.scribejava.core.model.OAuth2AccessToken> getAccessToken(java.lang.String, OAuthAsyncRequestCallback<com.github.scribejava.core.model.OAuth2AccessToken>) ,public Future<com.github.scribejava.core.model.OAuth2AccessToken> getAccessTokenAsync(java.lang.String) ,public Future<com.github.scribejava.core.model.OAuth2AccessToken> getAccessTokenAsync(com.github.scribejava.core.oauth.AccessTokenRequestParams) ,public com.github.scribejava.core.model.OAuth2AccessToken getAccessTokenClientCredentialsGrant() throws java.io.IOException, java.lang.InterruptedException, java.util.concurrent.ExecutionException,public com.github.scribejava.core.model.OAuth2AccessToken getAccessTokenClientCredentialsGrant(java.lang.String) throws java.io.IOException, java.lang.InterruptedException, java.util.concurrent.ExecutionException,public Future<com.github.scribejava.core.model.OAuth2AccessToken> getAccessTokenClientCredentialsGrant(OAuthAsyncRequestCallback<com.github.scribejava.core.model.OAuth2AccessToken>) ,public Future<com.github.scribejava.core.model.OAuth2AccessToken> getAccessTokenClientCredentialsGrant(java.lang.String, OAuthAsyncRequestCallback<com.github.scribejava.core.model.OAuth2AccessToken>) ,public Future<com.github.scribejava.core.model.OAuth2AccessToken> getAccessTokenClientCredentialsGrantAsync() ,public Future<com.github.scribejava.core.model.OAuth2AccessToken> getAccessTokenClientCredentialsGrantAsync(java.lang.String) ,public com.github.scribejava.core.model.OAuth2AccessToken getAccessTokenDeviceAuthorizationGrant(com.github.scribejava.core.model.DeviceAuthorization) throws java.lang.InterruptedException, java.util.concurrent.ExecutionException, java.io.IOException,public Future<com.github.scribejava.core.model.OAuth2AccessToken> getAccessTokenDeviceAuthorizationGrant(com.github.scribejava.core.model.DeviceAuthorization, OAuthAsyncRequestCallback<com.github.scribejava.core.model.OAuth2AccessToken>) ,public Future<com.github.scribejava.core.model.OAuth2AccessToken> getAccessTokenDeviceAuthorizationGrantAsync(com.github.scribejava.core.model.DeviceAuthorization) ,public com.github.scribejava.core.model.OAuth2AccessToken getAccessTokenPasswordGrant(java.lang.String, java.lang.String) throws java.io.IOException, java.lang.InterruptedException, java.util.concurrent.ExecutionException,public com.github.scribejava.core.model.OAuth2AccessToken getAccessTokenPasswordGrant(java.lang.String, java.lang.String, java.lang.String) throws java.io.IOException, java.lang.InterruptedException, java.util.concurrent.ExecutionException,public Future<com.github.scribejava.core.model.OAuth2AccessToken> getAccessTokenPasswordGrantAsync(java.lang.String, java.lang.String) ,public Future<com.github.scribejava.core.model.OAuth2AccessToken> getAccessTokenPasswordGrantAsync(java.lang.String, java.lang.String, java.lang.String) ,public Future<com.github.scribejava.core.model.OAuth2AccessToken> getAccessTokenPasswordGrantAsync(java.lang.String, java.lang.String, OAuthAsyncRequestCallback<com.github.scribejava.core.model.OAuth2AccessToken>) ,public Future<com.github.scribejava.core.model.OAuth2AccessToken> getAccessTokenPasswordGrantAsync(java.lang.String, java.lang.String, java.lang.String, OAuthAsyncRequestCallback<com.github.scribejava.core.model.OAuth2AccessToken>) ,public com.github.scribejava.core.builder.api.DefaultApi20 getApi() ,public java.lang.String getAuthorizationUrl() ,public java.lang.String getAuthorizationUrl(java.lang.String) ,public java.lang.String getAuthorizationUrl(Map<java.lang.String,java.lang.String>) ,public java.lang.String getAuthorizationUrl(com.github.scribejava.core.pkce.PKCE) ,public java.lang.String getDefaultScope() ,public com.github.scribejava.core.model.DeviceAuthorization getDeviceAuthorizationCodes() throws java.lang.InterruptedException, java.util.concurrent.ExecutionException, java.io.IOException,public com.github.scribejava.core.model.DeviceAuthorization getDeviceAuthorizationCodes(java.lang.String) throws java.lang.InterruptedException, java.util.concurrent.ExecutionException, java.io.IOException,public Future<com.github.scribejava.core.model.DeviceAuthorization> getDeviceAuthorizationCodes(OAuthAsyncRequestCallback<com.github.scribejava.core.model.DeviceAuthorization>) ,public Future<com.github.scribejava.core.model.DeviceAuthorization> getDeviceAuthorizationCodes(java.lang.String, OAuthAsyncRequestCallback<com.github.scribejava.core.model.DeviceAuthorization>) ,public Future<com.github.scribejava.core.model.DeviceAuthorization> getDeviceAuthorizationCodesAsync() ,public Future<com.github.scribejava.core.model.DeviceAuthorization> getDeviceAuthorizationCodesAsync(java.lang.String) ,public java.lang.String getResponseType() ,public java.lang.String getVersion() ,public com.github.scribejava.core.model.OAuth2AccessToken pollAccessTokenDeviceAuthorizationGrant(com.github.scribejava.core.model.DeviceAuthorization) throws java.lang.InterruptedException, java.util.concurrent.ExecutionException, java.io.IOException,public com.github.scribejava.core.model.OAuth2AccessToken refreshAccessToken(java.lang.String) throws java.io.IOException, java.lang.InterruptedException, java.util.concurrent.ExecutionException,public com.github.scribejava.core.model.OAuth2AccessToken refreshAccessToken(java.lang.String, java.lang.String) throws java.io.IOException, java.lang.InterruptedException, java.util.concurrent.ExecutionException,public Future<com.github.scribejava.core.model.OAuth2AccessToken> refreshAccessToken(java.lang.String, OAuthAsyncRequestCallback<com.github.scribejava.core.model.OAuth2AccessToken>) ,public Future<com.github.scribejava.core.model.OAuth2AccessToken> refreshAccessToken(java.lang.String, java.lang.String, OAuthAsyncRequestCallback<com.github.scribejava.core.model.OAuth2AccessToken>) ,public Future<com.github.scribejava.core.model.OAuth2AccessToken> refreshAccessTokenAsync(java.lang.String) ,public Future<com.github.scribejava.core.model.OAuth2AccessToken> refreshAccessTokenAsync(java.lang.String, java.lang.String) ,public void revokeToken(java.lang.String) throws java.io.IOException, java.lang.InterruptedException, java.util.concurrent.ExecutionException,public void revokeToken(java.lang.String, com.github.scribejava.core.revoke.TokenTypeHint) throws java.io.IOException, java.lang.InterruptedException, java.util.concurrent.ExecutionException,public Future<java.lang.Void> revokeToken(java.lang.String, OAuthAsyncRequestCallback<java.lang.Void>) ,public Future<java.lang.Void> revokeToken(java.lang.String, OAuthAsyncRequestCallback<java.lang.Void>, com.github.scribejava.core.revoke.TokenTypeHint) ,public Future<java.lang.Void> revokeTokenAsync(java.lang.String) ,public Future<java.lang.Void> revokeTokenAsync(java.lang.String, com.github.scribejava.core.revoke.TokenTypeHint) ,public void signRequest(java.lang.String, com.github.scribejava.core.model.OAuthRequest) ,public void signRequest(com.github.scribejava.core.model.OAuth2AccessToken, com.github.scribejava.core.model.OAuthRequest) <variables>private static final java.lang.String VERSION,private final com.github.scribejava.core.builder.api.DefaultApi20 api,private final java.lang.String defaultScope,private final java.lang.String responseType
pac4j_pac4j
pac4j/pac4j-oidc/src/main/java/org/pac4j/oidc/authorization/generator/KeycloakRolesAuthorizationGenerator.java
KeycloakRolesAuthorizationGenerator
generate
class KeycloakRolesAuthorizationGenerator implements AuthorizationGenerator { private String clientId; /** * <p>Constructor for KeycloakRolesAuthorizationGenerator.</p> */ public KeycloakRolesAuthorizationGenerator() { } /** * <p>Constructor for KeycloakRolesAuthorizationGenerator.</p> * * @param clientId a {@link String} object */ public KeycloakRolesAuthorizationGenerator(final String clientId) { this.clientId = clientId; } /** {@inheritDoc} */ @Override public Optional<UserProfile> generate(final CallContext ctx, final UserProfile profile) {<FILL_FUNCTION_BODY>} }
if (profile instanceof KeycloakOidcProfile) { try { val jwt = SignedJWT.parse(((KeycloakOidcProfile) profile).getAccessToken().getValue()); val jwtClaimsSet = jwt.getJWTClaimsSet(); val realmRolesJsonObject = jwtClaimsSet.getJSONObjectClaim("realm_access"); if (realmRolesJsonObject != null) { Iterable<String> realmRolesJsonArray = (List<String>) realmRolesJsonObject.get("roles"); if (realmRolesJsonArray != null) { realmRolesJsonArray.forEach(role -> profile.addRole(role)); } } if (clientId != null) { val resourceAccess = jwtClaimsSet.getJSONObjectClaim("resource_access"); if (resourceAccess != null) { val clientRolesJsonObject = (Map) resourceAccess.get(clientId); if (clientRolesJsonObject != null) { Iterable<String> clientRolesJsonArray = (List<String>) clientRolesJsonObject.get("roles"); if (clientRolesJsonArray != null) { clientRolesJsonArray.forEach(profile::addRole); } } } } } catch (final Exception e) { LOGGER.warn("Cannot parse Keycloak roles", e); } } return Optional.of(profile);
195
382
577
<no_super_class>
pac4j_pac4j
pac4j/pac4j-oidc/src/main/java/org/pac4j/oidc/client/AppleClient.java
AppleClient
internalInit
class AppleClient extends OidcClient { /** * <p>Constructor for AppleClient.</p> */ public AppleClient() { } /** * <p>Constructor for AppleClient.</p> * * @param configuration a {@link AppleOidcConfiguration} object */ public AppleClient(AppleOidcConfiguration configuration) { super(configuration); } /** {@inheritDoc} */ @Override protected void internalInit(final boolean forceReinit) {<FILL_FUNCTION_BODY>} }
val profileCreator = new OidcProfileCreator(getConfiguration(), this); profileCreator.setProfileDefinition(new OidcProfileDefinition(x -> new AppleProfile())); setProfileCreatorIfUndefined(profileCreator); super.internalInit(forceReinit);
147
73
220
<methods>public void <init>() ,public void <init>(org.pac4j.oidc.config.OidcConfiguration) ,public void notifySessionRenewal(CallContext, java.lang.String) ,public Optional<org.pac4j.core.profile.UserProfile> renewUserProfile(CallContext, org.pac4j.core.profile.UserProfile) <variables>private org.pac4j.oidc.config.OidcConfiguration configuration
pac4j_pac4j
pac4j/pac4j-oidc/src/main/java/org/pac4j/oidc/client/AzureAd2Client.java
AzureAd2Client
getAccessTokenFromRefreshToken
class AzureAd2Client extends OidcClient { protected ObjectMapper objectMapper; /** Constant <code>typeRef</code> */ protected static final TypeReference<HashMap<String,Object>> typeRef = new TypeReference<>() {}; /** * <p>Constructor for AzureAd2Client.</p> */ public AzureAd2Client() { objectMapper = new ObjectMapper(); } /** * <p>Constructor for AzureAd2Client.</p> * * @param configuration a {@link AzureAd2OidcConfiguration} object */ public AzureAd2Client(AzureAd2OidcConfiguration configuration) { super(configuration); objectMapper = new ObjectMapper(); } /** {@inheritDoc} */ @Override protected void internalInit(final boolean forceReinit) { getConfiguration().setResourceRetriever(new AzureAdResourceRetriever()); setProfileCreatorIfUndefined(new AzureAdProfileCreator(getConfiguration(), this)); super.internalInit(forceReinit); } /** {@inheritDoc} */ @Override protected CallbackUrlResolver newDefaultCallbackUrlResolver() { return new PathParameterCallbackUrlResolver(); } /** * <p>Refresh the access token</p> * <p>https://docs.microsoft.com/azure/active-directory/develop/v2-oauth2-auth-code-flow#refresh-the-access-token</p> * * @param azureAdProfile a {@link AzureAdProfile} object * @return a {@link String} object */ public String getAccessTokenFromRefreshToken(final AzureAdProfile azureAdProfile) {<FILL_FUNCTION_BODY>} }
val azureConfig = (AzureAd2OidcConfiguration) getConfiguration(); HttpURLConnection connection = null; try { final Map<String, String> headers = new HashMap<>(); headers.put(HttpConstants.CONTENT_TYPE_HEADER, HttpConstants.APPLICATION_FORM_ENCODED_HEADER_VALUE); headers.put(HttpConstants.ACCEPT_HEADER, HttpConstants.APPLICATION_JSON); // get the token endpoint from discovery URI val tokenEndpointURL = azureConfig.getOpMetadataResolver().load().getTokenEndpointURI().toURL(); connection = HttpUtils.openPostConnection(tokenEndpointURL, headers); val out = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8)); out.write(azureConfig.makeOauth2TokenRequest(azureAdProfile.getRefreshToken().getValue())); out.close(); val responseCode = connection.getResponseCode(); if (responseCode != 200) { throw new OidcTokenException("request for access token failed: " + HttpUtils.buildHttpErrorMessage(connection)); } var body = HttpUtils.readBody(connection); final Map<String, Object> res = objectMapper.readValue(body, typeRef); return (String) res.get("access_token"); } catch (final IOException e) { throw new OidcException(e); } finally { HttpUtils.closeConnection(connection); }
447
376
823
<methods>public void <init>() ,public void <init>(org.pac4j.oidc.config.OidcConfiguration) ,public void notifySessionRenewal(CallContext, java.lang.String) ,public Optional<org.pac4j.core.profile.UserProfile> renewUserProfile(CallContext, org.pac4j.core.profile.UserProfile) <variables>private org.pac4j.oidc.config.OidcConfiguration configuration
pac4j_pac4j
pac4j/pac4j-oidc/src/main/java/org/pac4j/oidc/client/GoogleOidcClient.java
GoogleOidcClient
internalInit
class GoogleOidcClient extends OidcClient { /** * <p>Constructor for GoogleOidcClient.</p> */ public GoogleOidcClient() { } /** * <p>Constructor for GoogleOidcClient.</p> * * @param configuration a {@link OidcConfiguration} object */ public GoogleOidcClient(final OidcConfiguration configuration) { super(configuration); } /** {@inheritDoc} */ @Override protected void internalInit(final boolean forceReinit) {<FILL_FUNCTION_BODY>} }
getConfiguration().setDiscoveryURIIfUndefined("https://accounts.google.com/.well-known/openid-configuration"); val profileCreator = new OidcProfileCreator(getConfiguration(), this); profileCreator.setProfileDefinition(new OidcProfileDefinition(x -> new GoogleOidcProfile())); setProfileCreatorIfUndefined(profileCreator); setLogoutActionBuilderIfUndefined(new GoogleLogoutActionBuilder()); super.internalInit(forceReinit);
161
128
289
<methods>public void <init>() ,public void <init>(org.pac4j.oidc.config.OidcConfiguration) ,public void notifySessionRenewal(CallContext, java.lang.String) ,public Optional<org.pac4j.core.profile.UserProfile> renewUserProfile(CallContext, org.pac4j.core.profile.UserProfile) <variables>private org.pac4j.oidc.config.OidcConfiguration configuration
pac4j_pac4j
pac4j/pac4j-oidc/src/main/java/org/pac4j/oidc/client/KeycloakOidcClient.java
KeycloakOidcClient
internalInit
class KeycloakOidcClient extends OidcClient { /** * <p>Constructor for KeycloakOidcClient.</p> */ public KeycloakOidcClient() { } /** * <p>Constructor for KeycloakOidcClient.</p> * * @param configuration a {@link KeycloakOidcConfiguration} object */ public KeycloakOidcClient(final KeycloakOidcConfiguration configuration) { super(configuration); } /** {@inheritDoc} */ @Override protected void internalInit(final boolean forceReinit) {<FILL_FUNCTION_BODY>} }
val profileCreator = new OidcProfileCreator(getConfiguration(), this); profileCreator.setProfileDefinition(new OidcProfileDefinition(x -> new KeycloakOidcProfile())); setProfileCreatorIfUndefined(profileCreator); addAuthorizationGenerator(new KeycloakRolesAuthorizationGenerator(getConfiguration().getClientId())); super.internalInit(forceReinit);
184
106
290
<methods>public void <init>() ,public void <init>(org.pac4j.oidc.config.OidcConfiguration) ,public void notifySessionRenewal(CallContext, java.lang.String) ,public Optional<org.pac4j.core.profile.UserProfile> renewUserProfile(CallContext, org.pac4j.core.profile.UserProfile) <variables>private org.pac4j.oidc.config.OidcConfiguration configuration
pac4j_pac4j
pac4j/pac4j-oidc/src/main/java/org/pac4j/oidc/client/OidcClient.java
OidcClient
renewUserProfile
class OidcClient extends IndirectClient { @Getter @Setter private OidcConfiguration configuration; /** * <p>Constructor for OidcClient.</p> */ public OidcClient() { } /** * <p>Constructor for OidcClient.</p> * * @param configuration a {@link OidcConfiguration} object */ public OidcClient(final OidcConfiguration configuration) { setConfiguration(configuration); } /** {@inheritDoc} */ @Override protected void beforeInternalInit(final boolean forceReinit) { super.beforeInternalInit(forceReinit); assertNotNull("configuration", configuration); } /** {@inheritDoc} */ @Override protected void internalInit(final boolean forceReinit) { configuration.init(forceReinit); setRedirectionActionBuilderIfUndefined(new OidcRedirectionActionBuilder(this)); setCredentialsExtractorIfUndefined(new OidcCredentialsExtractor(configuration, this)); setAuthenticatorIfUndefined(new OidcAuthenticator(configuration, this)); setProfileCreatorIfUndefined(new OidcProfileCreator(configuration, this)); setLogoutProcessorIfUndefined(new OidcLogoutProcessor(configuration, findSessionLogoutHandler())); setLogoutActionBuilderIfUndefined(new OidcLogoutActionBuilder(configuration)); } /** {@inheritDoc} */ @Override public Optional<UserProfile> renewUserProfile(final CallContext ctx, final UserProfile profile) {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override public void notifySessionRenewal(final CallContext ctx, final String oldSessionId) { val sessionLogoutHandler = findSessionLogoutHandler(); if (sessionLogoutHandler != null) { sessionLogoutHandler.renewSession(ctx, oldSessionId); } } }
val oidcProfile = (OidcProfile) profile; val refreshToken = oidcProfile.getRefreshToken(); if (refreshToken != null) { val credentials = new OidcCredentials(); credentials.setRefreshTokenObject(refreshToken); val authenticator = (OidcAuthenticator)getAuthenticator(); authenticator.refresh(credentials); // Create a profile if the refresh grant was successful if (credentials.getAccessToken() != null) { return getUserProfile(ctx, credentials); } } return Optional.empty();
506
157
663
<methods>public non-sealed void <init>() ,public java.lang.String computeFinalCallbackUrl(org.pac4j.core.context.WebContext) ,public java.lang.String getCodeVerifierSessionAttributeName() ,public final Optional<org.pac4j.core.exception.http.RedirectionAction> getLogoutAction(CallContext, org.pac4j.core.profile.UserProfile, java.lang.String) ,public java.lang.String getNonceSessionAttributeName() ,public final Optional<org.pac4j.core.exception.http.RedirectionAction> getRedirectionAction(CallContext) ,public java.lang.String getStateSessionAttributeName() ,public org.pac4j.core.exception.http.HttpAction processLogout(CallContext, org.pac4j.core.credentials.Credentials) <variables>public static final java.lang.String ATTEMPTED_AUTHENTICATION_SUFFIX,private static final java.lang.String CODE_VERIFIER_SESSION_PARAMETER,private static final java.lang.String NONCE_SESSION_PARAMETER,private static final java.lang.String STATE_SESSION_PARAMETER,private org.pac4j.core.http.ajax.AjaxRequestResolver ajaxRequestResolver,protected java.lang.String callbackUrl,protected org.pac4j.core.http.callback.CallbackUrlResolver callbackUrlResolver,private boolean checkAuthenticationAttempt,private org.pac4j.core.logout.LogoutActionBuilder logoutActionBuilder,private org.pac4j.core.logout.processor.LogoutProcessor logoutProcessor,private org.pac4j.core.redirect.RedirectionActionBuilder redirectionActionBuilder,protected org.pac4j.core.http.url.UrlResolver urlResolver
pac4j_pac4j
pac4j/pac4j-oidc/src/main/java/org/pac4j/oidc/client/azuread/AzureAdIdTokenValidator.java
AzureAdIdTokenValidator
validate
class AzureAdIdTokenValidator extends IDTokenValidator { private IDTokenValidator base; private String originalIssuer; /** * <p>Constructor for AzureAdIdTokenValidator.</p> * * @param base a {@link IDTokenValidator} object */ public AzureAdIdTokenValidator(final IDTokenValidator base) { super(base.getExpectedIssuer(), base.getClientID()); this.base = base; this.originalIssuer = base.getExpectedIssuer().getValue(); } /** {@inheritDoc} */ @Override public IDTokenClaimsSet validate(final JWT idToken, final Nonce expectedNonce) throws BadJOSEException, JOSEException {<FILL_FUNCTION_BODY>} }
try { if (originalIssuer.contains("%7Btenantid%7D")) { var tid = idToken.getJWTClaimsSet().getClaim("tid"); if (tid == null) { throw new BadJWTException("ID token does not contain the 'tid' claim"); } base = new IDTokenValidator(new Issuer(originalIssuer.replace("%7Btenantid%7D", tid.toString())), base.getClientID(), base.getJWSKeySelector(), base.getJWEKeySelector()); base.setMaxClockSkew(getMaxClockSkew()); } } catch (ParseException e) { throw new BadJWTException(e.getMessage(), e); } return base.validate(idToken, expectedNonce);
192
210
402
<methods>public void <init>(com.nimbusds.oauth2.sdk.id.Issuer, com.nimbusds.oauth2.sdk.id.ClientID) ,public void <init>(com.nimbusds.oauth2.sdk.id.Issuer, com.nimbusds.oauth2.sdk.id.ClientID, com.nimbusds.jose.JWSAlgorithm, com.nimbusds.jose.jwk.JWKSet) ,public void <init>(com.nimbusds.oauth2.sdk.id.Issuer, com.nimbusds.oauth2.sdk.id.ClientID, com.nimbusds.jose.JWSAlgorithm, java.net.URL) ,public void <init>(com.nimbusds.oauth2.sdk.id.Issuer, com.nimbusds.oauth2.sdk.id.ClientID, com.nimbusds.jose.JWSAlgorithm, com.nimbusds.oauth2.sdk.auth.Secret) ,public void <init>(com.nimbusds.oauth2.sdk.id.Issuer, com.nimbusds.oauth2.sdk.id.ClientID, JWSKeySelector#RAW, JWEKeySelector#RAW) ,public void <init>(com.nimbusds.oauth2.sdk.id.Issuer, com.nimbusds.oauth2.sdk.id.ClientID, com.nimbusds.jose.JWSAlgorithm, java.net.URL, com.nimbusds.jose.util.ResourceRetriever) ,public void <init>(com.nimbusds.jose.JOSEObjectType, com.nimbusds.oauth2.sdk.id.Issuer, com.nimbusds.oauth2.sdk.id.ClientID, JWSKeySelector#RAW, JWEKeySelector#RAW) ,public static com.nimbusds.openid.connect.sdk.validators.IDTokenValidator create(com.nimbusds.openid.connect.sdk.op.OIDCProviderMetadata, com.nimbusds.openid.connect.sdk.rp.OIDCClientInformation) throws com.nimbusds.oauth2.sdk.GeneralException,public static com.nimbusds.openid.connect.sdk.validators.IDTokenValidator create(com.nimbusds.oauth2.sdk.id.Issuer, com.nimbusds.openid.connect.sdk.rp.OIDCClientInformation) throws com.nimbusds.oauth2.sdk.GeneralException, java.io.IOException,public static com.nimbusds.openid.connect.sdk.validators.IDTokenValidator create(com.nimbusds.openid.connect.sdk.op.OIDCProviderMetadata, com.nimbusds.openid.connect.sdk.rp.OIDCClientInformation, JWKSource#RAW) throws com.nimbusds.oauth2.sdk.GeneralException,public static com.nimbusds.openid.connect.sdk.validators.IDTokenValidator create(com.nimbusds.oauth2.sdk.id.Issuer, com.nimbusds.openid.connect.sdk.rp.OIDCClientInformation, JWKSource#RAW, int, int) throws com.nimbusds.oauth2.sdk.GeneralException, java.io.IOException,public com.nimbusds.openid.connect.sdk.claims.IDTokenClaimsSet validate(com.nimbusds.jwt.JWT, com.nimbusds.openid.connect.sdk.Nonce) throws com.nimbusds.jose.proc.BadJOSEException, com.nimbusds.jose.JOSEException<variables>
pac4j_pac4j
pac4j/pac4j-oidc/src/main/java/org/pac4j/oidc/client/azuread/AzureAdResourceRetriever.java
AzureAdResourceRetriever
retrieveResource
class AzureAdResourceRetriever extends DefaultResourceRetriever implements ResourceRetriever { /** {@inheritDoc} */ @Override public Resource retrieveResource(final URL url) throws IOException {<FILL_FUNCTION_BODY>} }
val ret = super.retrieveResource(url); return new Resource(ret.getContent().replace("{tenantid}", "%7Btenantid%7D"), ret.getContentType());
60
51
111
<methods>public void <init>() ,public void <init>(int, int) ,public void <init>(int, int, int) ,public void <init>(int, int, int, boolean) ,public void <init>(int, int, int, boolean, javax.net.ssl.SSLSocketFactory) ,public boolean disconnectsAfterUse() ,public java.net.Proxy getProxy() ,public com.nimbusds.jose.util.Resource retrieveResource(java.net.URL) throws java.io.IOException,public void setDisconnectsAfterUse(boolean) ,public void setProxy(java.net.Proxy) <variables>private boolean disconnectAfterUse,private java.net.Proxy proxy,private final javax.net.ssl.SSLSocketFactory sslSocketFactory
pac4j_pac4j
pac4j/pac4j-oidc/src/main/java/org/pac4j/oidc/config/AppleOidcConfiguration.java
AppleOidcConfiguration
internalInit
class AppleOidcConfiguration extends OidcConfiguration { /** * Max expiration timeout for client secret (6 months in seconds) */ private final static Duration MAX_TIMEOUT = Duration.ofSeconds(15777000); /** * Apple Auth Key */ private ECPrivateKey privateKey; /** * Apple Auth Key ID */ private String privateKeyID; /** * Apple Team ID */ private String teamID; /** * Client secret cache store */ private Store<String, String> store; /** * Client secret expiration timeout */ private Duration timeout = MAX_TIMEOUT; /** {@inheritDoc} */ @Override protected void internalInit(final boolean forceReinit) {<FILL_FUNCTION_BODY>} /** * {@inheritDoc} * * Generate client secret (JWT) and cache it until expiration timeout */ @Override public String getSecret() { if (store != null) { var cache = store.get(getClientId()); if (cache.isPresent()) { return cache.get(); } } // https://developer.apple.com/documentation/sign_in_with_apple/generate_and_validate_tokens#3262048 var claimsSet = new JWTClaimsSet.Builder() .issuer(getTeamID()) .audience("https://appleid.apple.com") .subject(getClientId()) .issueTime(Date.from(Instant.now())) .expirationTime(Date.from(Instant.now().plusSeconds(timeout.toSeconds()))) .build(); var signedJWT = new SignedJWT( new JWSHeader.Builder(JWSAlgorithm.ES256).keyID(privateKeyID).build(), claimsSet); JWSSigner signer; try { signer = new ECDSASigner(privateKey); signedJWT.sign(signer); } catch (JOSEException e) { throw new OidcException(e); } var secret = signedJWT.serialize(); if (store != null) { store.set(getClientId(), secret); } return secret; } }
// checks CommonHelper.assertNotBlank("privateKeyID", privateKeyID); CommonHelper.assertNotNull("privateKey", privateKey); CommonHelper.assertNotBlank("teamID", teamID); if (timeout.compareTo(MAX_TIMEOUT) > 0) { throw new IllegalArgumentException(String.format("timeout must not be greater then %d seconds", MAX_TIMEOUT.toSeconds())); } if (store == null) { store = new GuavaStore<>(1000, (int) timeout.toSeconds(), TimeUnit.SECONDS); } val providerMetadata = new OIDCProviderMetadata( new Issuer("https://appleid.apple.com"), Collections.singletonList(SubjectType.PAIRWISE), // https://developer.apple.com/documentation/signinwithapplerestapi/fetch_apple_s_public_key_for_verifying_token_signature URI.create("https://appleid.apple.com/auth/keys")); // https://developer.apple.com/documentation/sign_in_with_apple/sign_in_with_apple_js/incorporating_sign_in_with_apple_into_other_platforms providerMetadata.setAuthorizationEndpointURI(URI.create("https://appleid.apple.com/auth/authorize")); // https://developer.apple.com/documentation/sign_in_with_apple/generate_and_validate_tokens providerMetadata.setTokenEndpointURI(URI.create("https://appleid.apple.com/auth/token")); providerMetadata.setIDTokenJWSAlgs(Collections.singletonList(JWSAlgorithm.RS256)); this.opMetadataResolver = new StaticOidcOpMetadataResolver(this, providerMetadata); setClientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_POST); super.internalInit(forceReinit);
607
477
1,084
<methods>public non-sealed void <init>() ,public void addCustomParam(java.lang.String, java.lang.String) ,public void configureHttpRequest(com.nimbusds.oauth2.sdk.http.HTTPRequest) ,public java.lang.String findLogoutUrl() ,public com.nimbusds.oauth2.sdk.pkce.CodeChallengeMethod findPkceMethod() ,public com.nimbusds.jose.util.ResourceRetriever findResourceRetriever() ,public java.lang.String getCustomParam(java.lang.String) ,public java.lang.String getResponseType() ,public int getTokenExpirationAdvance() ,public void setClientAuthenticationMethodAsString(java.lang.String) ,public void setCodeVerifierGenerator(org.pac4j.core.util.generator.ValueGenerator) ,public void setCustomParams(Map<java.lang.String,java.lang.String>) ,public void setDiscoveryURIIfUndefined(java.lang.String) ,public void setPreferredJwsAlgorithmAsString(java.lang.String) ,public void setResponseType(java.lang.String) ,public void setStateGenerator(org.pac4j.core.util.generator.ValueGenerator) ,public void setSupportedClientAuthenticationMethods(Set<com.nimbusds.oauth2.sdk.auth.ClientAuthenticationMethod>) ,public void setValueRetriever(org.pac4j.oidc.util.ValueRetriever) <variables>public static final List<com.nimbusds.oauth2.sdk.ResponseType> AUTHORIZATION_CODE_FLOWS,public static final java.lang.String CLIENT_ID,public static final java.lang.String CODE_CHALLENGE,public static final java.lang.String CODE_CHALLENGE_METHOD,public static final java.lang.String CUSTOM_PARAMS,public static final int DEFAULT_MAX_CLOCK_SKEW,public static final int DEFAULT_TOKEN_EXPIRATION_ADVANCE,public static final List<com.nimbusds.oauth2.sdk.ResponseType> HYBRID_CODE_FLOWS,public static final List<com.nimbusds.oauth2.sdk.ResponseType> IMPLICIT_FLOWS,public static final java.lang.String MAX_AGE,public static final java.lang.String NONCE,public static final java.lang.String PROMPT,public static final java.lang.String REDIRECT_URI,public static final java.lang.String RESPONSE_MODE,public static final java.lang.String RESPONSE_TYPE,public static final java.lang.String SCOPE,public static final java.lang.String STATE,private boolean allowUnsignedIdTokens,private boolean callUserInfoEndpoint,private com.nimbusds.oauth2.sdk.auth.ClientAuthenticationMethod clientAuthenticationMethod,private java.lang.String clientId,private org.pac4j.core.util.generator.ValueGenerator codeVerifierGenerator,private int connectTimeout,private Map<java.lang.String,java.lang.String> customParams,private boolean disablePkce,private java.lang.String discoveryURI,private boolean expireSessionWithToken,private javax.net.ssl.HostnameVerifier hostnameVerifier,private boolean includeAccessTokenClaimsInProfile,private java.lang.String logoutUrl,private Map<java.lang.String,java.lang.String> mappedClaims,private java.lang.Integer maxAge,private int maxClockSkew,protected org.pac4j.oidc.metadata.OidcOpMetadataResolver opMetadataResolver,private com.nimbusds.oauth2.sdk.pkce.CodeChallengeMethod pkceMethod,private com.nimbusds.jose.JWSAlgorithm preferredJwsAlgorithm,private org.pac4j.oidc.config.PrivateKeyJWTClientAuthnMethodConfig privateKeyJWTClientAuthnMethodConfig,private int readTimeout,private com.nimbusds.jose.util.ResourceRetriever resourceRetriever,private java.lang.String responseMode,private com.nimbusds.oauth2.sdk.ResponseType responseType,private java.lang.String scope,private java.lang.String secret,private javax.net.ssl.SSLSocketFactory sslSocketFactory,private org.pac4j.core.util.generator.ValueGenerator stateGenerator,private Set<com.nimbusds.oauth2.sdk.auth.ClientAuthenticationMethod> supportedClientAuthenticationMethods,private int tokenExpirationAdvance,private boolean useNonce,private org.pac4j.oidc.util.ValueRetriever valueRetriever,private boolean withState
pac4j_pac4j
pac4j/pac4j-oidc/src/main/java/org/pac4j/oidc/config/AzureAd2OidcConfiguration.java
AzureAd2OidcConfiguration
internalInit
class AzureAd2OidcConfiguration extends OidcConfiguration { /** AzureAd tenant **/ private String tenant; /** * <p>Constructor for AzureAd2OidcConfiguration.</p> */ public AzureAd2OidcConfiguration() { } /** * <p>Constructor for AzureAd2OidcConfiguration.</p> * * @param oidcConfiguration a {@link OidcConfiguration} object */ public AzureAd2OidcConfiguration(final OidcConfiguration oidcConfiguration) { this.setOpMetadataResolver(oidcConfiguration.getOpMetadataResolver()); this.setClientId(oidcConfiguration.getClientId()); this.setSecret(oidcConfiguration.getSecret()); this.setScope(oidcConfiguration.getScope()); this.setCustomParams(oidcConfiguration.getCustomParams()); this.setClientAuthenticationMethod(oidcConfiguration.getClientAuthenticationMethod()); this.setUseNonce(oidcConfiguration.isUseNonce()); this.setPreferredJwsAlgorithm(oidcConfiguration.getPreferredJwsAlgorithm()); this.setMaxClockSkew(oidcConfiguration.getMaxClockSkew()); this.setConnectTimeout(oidcConfiguration.getConnectTimeout()); this.setReadTimeout(oidcConfiguration.getReadTimeout()); this.setDiscoveryURI(oidcConfiguration.getDiscoveryURI()); this.setResourceRetriever(oidcConfiguration.getResourceRetriever()); this.setResponseType(oidcConfiguration.getResponseType()); this.setResponseMode(oidcConfiguration.getResponseMode()); this.setLogoutUrl(oidcConfiguration.getLogoutUrl()); if (oidcConfiguration instanceof AzureAd2OidcConfiguration azureAd2OidcConfiguration) { this.setTenant(azureAd2OidcConfiguration.getTenant()); } } /** {@inheritDoc} */ @Override protected void internalInit(final boolean forceReinit) {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override public String getDiscoveryURI() { return "https://login.microsoftonline.com/" + getTenant() + "/v2.0/.well-known/openid-configuration"; } /** * <p>makeOauth2TokenRequest.</p> * * @param refreshToken a {@link String} object * @return a {@link String} object */ public String makeOauth2TokenRequest(String refreshToken) { var scope = this.getScope(); if (isBlank(scope)){ // default values scope = "openid profile email"; } val payload = HttpUtils.encodeQueryParam("client_id",this.getClientId()) + "&" + HttpUtils.encodeQueryParam("client_secret",this.getSecret()) + "&" + HttpUtils.encodeQueryParam("grant_type","refresh_token") + "&" + HttpUtils.encodeQueryParam("refresh_token",refreshToken) + "&" + HttpUtils.encodeQueryParam("tenant", this.getTenant()) + "&" + HttpUtils.encodeQueryParam("scope", scope); return payload; } }
if (isBlank(getTenant())){ // default value setTenant("common"); } if (this.getOpMetadataResolver() == null) { assertNotBlank("discoveryURI", getDiscoveryURI()); this.opMetadataResolver = new AzureAdOpMetadataResolver(this); this.opMetadataResolver.init(); } super.internalInit(forceReinit);
824
106
930
<methods>public non-sealed void <init>() ,public void addCustomParam(java.lang.String, java.lang.String) ,public void configureHttpRequest(com.nimbusds.oauth2.sdk.http.HTTPRequest) ,public java.lang.String findLogoutUrl() ,public com.nimbusds.oauth2.sdk.pkce.CodeChallengeMethod findPkceMethod() ,public com.nimbusds.jose.util.ResourceRetriever findResourceRetriever() ,public java.lang.String getCustomParam(java.lang.String) ,public java.lang.String getResponseType() ,public int getTokenExpirationAdvance() ,public void setClientAuthenticationMethodAsString(java.lang.String) ,public void setCodeVerifierGenerator(org.pac4j.core.util.generator.ValueGenerator) ,public void setCustomParams(Map<java.lang.String,java.lang.String>) ,public void setDiscoveryURIIfUndefined(java.lang.String) ,public void setPreferredJwsAlgorithmAsString(java.lang.String) ,public void setResponseType(java.lang.String) ,public void setStateGenerator(org.pac4j.core.util.generator.ValueGenerator) ,public void setSupportedClientAuthenticationMethods(Set<com.nimbusds.oauth2.sdk.auth.ClientAuthenticationMethod>) ,public void setValueRetriever(org.pac4j.oidc.util.ValueRetriever) <variables>public static final List<com.nimbusds.oauth2.sdk.ResponseType> AUTHORIZATION_CODE_FLOWS,public static final java.lang.String CLIENT_ID,public static final java.lang.String CODE_CHALLENGE,public static final java.lang.String CODE_CHALLENGE_METHOD,public static final java.lang.String CUSTOM_PARAMS,public static final int DEFAULT_MAX_CLOCK_SKEW,public static final int DEFAULT_TOKEN_EXPIRATION_ADVANCE,public static final List<com.nimbusds.oauth2.sdk.ResponseType> HYBRID_CODE_FLOWS,public static final List<com.nimbusds.oauth2.sdk.ResponseType> IMPLICIT_FLOWS,public static final java.lang.String MAX_AGE,public static final java.lang.String NONCE,public static final java.lang.String PROMPT,public static final java.lang.String REDIRECT_URI,public static final java.lang.String RESPONSE_MODE,public static final java.lang.String RESPONSE_TYPE,public static final java.lang.String SCOPE,public static final java.lang.String STATE,private boolean allowUnsignedIdTokens,private boolean callUserInfoEndpoint,private com.nimbusds.oauth2.sdk.auth.ClientAuthenticationMethod clientAuthenticationMethod,private java.lang.String clientId,private org.pac4j.core.util.generator.ValueGenerator codeVerifierGenerator,private int connectTimeout,private Map<java.lang.String,java.lang.String> customParams,private boolean disablePkce,private java.lang.String discoveryURI,private boolean expireSessionWithToken,private javax.net.ssl.HostnameVerifier hostnameVerifier,private boolean includeAccessTokenClaimsInProfile,private java.lang.String logoutUrl,private Map<java.lang.String,java.lang.String> mappedClaims,private java.lang.Integer maxAge,private int maxClockSkew,protected org.pac4j.oidc.metadata.OidcOpMetadataResolver opMetadataResolver,private com.nimbusds.oauth2.sdk.pkce.CodeChallengeMethod pkceMethod,private com.nimbusds.jose.JWSAlgorithm preferredJwsAlgorithm,private org.pac4j.oidc.config.PrivateKeyJWTClientAuthnMethodConfig privateKeyJWTClientAuthnMethodConfig,private int readTimeout,private com.nimbusds.jose.util.ResourceRetriever resourceRetriever,private java.lang.String responseMode,private com.nimbusds.oauth2.sdk.ResponseType responseType,private java.lang.String scope,private java.lang.String secret,private javax.net.ssl.SSLSocketFactory sslSocketFactory,private org.pac4j.core.util.generator.ValueGenerator stateGenerator,private Set<com.nimbusds.oauth2.sdk.auth.ClientAuthenticationMethod> supportedClientAuthenticationMethods,private int tokenExpirationAdvance,private boolean useNonce,private org.pac4j.oidc.util.ValueRetriever valueRetriever,private boolean withState
pac4j_pac4j
pac4j/pac4j-oidc/src/main/java/org/pac4j/oidc/config/OidcConfigurationContext.java
OidcConfigurationContext
getScope
class OidcConfigurationContext { private final WebContext context; private final OidcConfiguration configuration; /** * <p>Constructor for OidcConfigurationContext.</p> * * @param webContext a {@link WebContext} object * @param oidcConfiguration a {@link OidcConfiguration} object */ public OidcConfigurationContext(final WebContext webContext, final OidcConfiguration oidcConfiguration) { this.context = webContext; this.configuration = oidcConfiguration; } /** * <p>getMaxAge.</p> * * @return a {@link Integer} object */ public Integer getMaxAge() { return (Integer) context.getRequestAttribute(OidcConfiguration.MAX_AGE) .orElse(configuration.getMaxAge()); } /** * <p>isForceAuthn.</p> * * @return a {@link Boolean} object */ public Boolean isForceAuthn() { return context.getRequestAttribute(RedirectionActionBuilder.ATTRIBUTE_FORCE_AUTHN) .isPresent(); } /** * <p>isPassive.</p> * * @return a {@link Boolean} object */ public Boolean isPassive() { return context.getRequestAttribute(RedirectionActionBuilder.ATTRIBUTE_PASSIVE) .isPresent(); } /** * <p>getScope.</p> * * @return a {@link String} object */ public String getScope() {<FILL_FUNCTION_BODY>} /** * <p>getResponseType.</p> * * @return a {@link String} object */ public String getResponseType() { return (String) context.getRequestAttribute(OidcConfiguration.RESPONSE_TYPE) .orElse(configuration.getResponseType()); } /** * <p>getResponseMode.</p> * * @return a {@link String} object */ public String getResponseMode() { return (String) context.getRequestAttribute(OidcConfiguration.RESPONSE_MODE) .orElse(configuration.getResponseMode()); } /** * <p>getCustomParams.</p> * * @return a {@link Map} object */ public Map<String, String> getCustomParams() { return (Map<String, String>) context.getRequestAttribute(OidcConfiguration.CUSTOM_PARAMS) .orElse(configuration.getCustomParams()); } /** * <p>Getter for the field <code>configuration</code>.</p> * * @return a {@link OidcConfiguration} object */ public OidcConfiguration getConfiguration() { return configuration; } }
return (String) context.getRequestAttribute(OidcConfiguration.SCOPE) .or(() -> Optional.ofNullable(configuration.getScope())) .orElse("openid profile email");
760
53
813
<no_super_class>
pac4j_pac4j
pac4j/pac4j-oidc/src/main/java/org/pac4j/oidc/credentials/OidcCredentials.java
OidcCredentials
toRefreshToken
class OidcCredentials extends Credentials { @Serial private static final long serialVersionUID = 6772331801527223938L; @EqualsAndHashCode.Include private String code; private Map<String, ?> accessToken; private Map<String, ?> refreshToken; private String idToken; @JsonIgnore public AuthorizationCode toAuthorizationCode() { return code != null ? new AuthorizationCode(this.code) : null; } @JsonIgnore public AccessToken toAccessToken() { try { return accessToken != null ? AccessToken.parse(new JSONObject(accessToken)) : null; } catch (final Exception e) { throw new IllegalArgumentException(e); } } @JsonIgnore public RefreshToken toRefreshToken() {<FILL_FUNCTION_BODY>} @JsonIgnore public JWT toIdToken() { try { return idToken != null ? JWTParser.parse(this.idToken) : null; } catch (final Exception e) { throw new IllegalArgumentException(e); } } @JsonIgnore public void setAccessTokenObject(final AccessToken accessToken) { setAccessToken(accessToken.toJSONObject()); } @JsonIgnore public void setRefreshTokenObject(final RefreshToken refreshToken) { setRefreshToken(refreshToken.toJSONObject()); } }
try { return refreshToken != null ? RefreshToken.parse(new JSONObject(refreshToken)) : null; } catch (final Exception e) { throw new IllegalArgumentException(e); }
391
55
446
<methods>public non-sealed void <init>() ,public boolean isForAuthentication() <variables>protected org.pac4j.core.logout.LogoutType logoutType,private static final long serialVersionUID,protected java.lang.String source,private org.pac4j.core.profile.UserProfile userProfile
pac4j_pac4j
pac4j/pac4j-oidc/src/main/java/org/pac4j/oidc/credentials/authenticator/OidcAuthenticator.java
OidcAuthenticator
validate
class OidcAuthenticator implements Authenticator { protected OidcConfiguration configuration; protected OidcClient client; /** * <p>Constructor for OidcAuthenticator.</p> * * @param configuration a {@link OidcConfiguration} object * @param client a {@link OidcClient} object */ public OidcAuthenticator(final OidcConfiguration configuration, final OidcClient client) { assertNotNull("configuration", configuration); assertNotNull("client", client); this.configuration = configuration; this.client = client; } /** {@inheritDoc} */ @Override public Optional<Credentials> validate(final CallContext ctx, final Credentials cred) {<FILL_FUNCTION_BODY>} /** * <p>refresh.</p> * * @param credentials a {@link OidcCredentials} object */ public void refresh(final OidcCredentials credentials) { val refreshToken = credentials.toRefreshToken(); if (refreshToken != null) { try { val request = createTokenRequest(new RefreshTokenGrant(refreshToken)); executeTokenRequest(request, credentials); } catch (final IOException | ParseException e) { throw new OidcException(e); } } } /** * <p>createTokenRequest.</p> * * @param grant a {@link AuthorizationGrant} object * @return a {@link TokenRequest} object */ protected TokenRequest createTokenRequest(final AuthorizationGrant grant) { val metadataResolver = configuration.getOpMetadataResolver(); val tokenEndpointUri = metadataResolver.load().getTokenEndpointURI(); val clientAuthentication = metadataResolver.getClientAuthentication(); if (clientAuthentication != null) { return new TokenRequest(tokenEndpointUri, clientAuthentication, grant); } else { return new TokenRequest(tokenEndpointUri, new ClientID(configuration.getClientId()), grant); } } private void executeTokenRequest(Request request, OidcCredentials credentials) throws IOException, ParseException { val tokenHttpRequest = request.toHTTPRequest(); configuration.configureHttpRequest(tokenHttpRequest); val httpResponse = tokenHttpRequest.send(); LOGGER.debug("Token response: status={}, content={}", httpResponse.getStatusCode(), httpResponse.getContent()); val response = OIDCTokenResponseParser.parse(httpResponse); if (response instanceof TokenErrorResponse tokenErrorResponse) { val errorObject = tokenErrorResponse.getErrorObject(); throw new OidcTokenException("Bad token response, error=" + errorObject.getCode() + "," + " description=" + errorObject.getDescription() + ", status=" + errorObject.getHTTPStatusCode()); } LOGGER.debug("Token response successful"); val tokenSuccessResponse = (OIDCTokenResponse) response; val oidcTokens = tokenSuccessResponse.getOIDCTokens(); if (oidcTokens.getAccessToken() != null) { credentials.setAccessToken(oidcTokens.getAccessToken().toJSONObject()); } if (oidcTokens.getRefreshToken() != null) { credentials.setRefreshToken(oidcTokens.getRefreshToken().toJSONObject()); } if (oidcTokens.getIDToken() != null) { credentials.setIdToken(oidcTokens.getIDToken().serialize()); } } }
if (cred instanceof OidcCredentials credentials) { val code = credentials.toAuthorizationCode(); // if we have a code if (code != null) { try { val computedCallbackUrl = client.computeFinalCallbackUrl(ctx.webContext()); var verifier = (CodeVerifier) configuration.getValueRetriever() .retrieve(ctx, client.getCodeVerifierSessionAttributeName(), client).orElse(null); // Token request val request = createTokenRequest(new AuthorizationCodeGrant(code, new URI(computedCallbackUrl), verifier)); executeTokenRequest(request, credentials); } catch (final URISyntaxException | IOException | ParseException e) { throw new OidcException(e); } } } return Optional.ofNullable(cred);
907
209
1,116
<no_super_class>
pac4j_pac4j
pac4j/pac4j-oidc/src/main/java/org/pac4j/oidc/credentials/extractor/OidcCredentialsExtractor.java
OidcCredentialsExtractor
extract
class OidcCredentialsExtractor implements CredentialsExtractor { protected OidcConfiguration configuration; protected OidcClient client; /** * <p>Constructor for OidcCredentialsExtractor.</p> * * @param configuration a {@link OidcConfiguration} object * @param client a {@link OidcClient} object */ public OidcCredentialsExtractor(final OidcConfiguration configuration, final OidcClient client) { CommonHelper.assertNotNull("configuration", configuration); CommonHelper.assertNotNull("client", client); this.configuration = configuration; this.client = client; } /** {@inheritDoc} */ @Override public Optional<Credentials> extract(final CallContext ctx) {<FILL_FUNCTION_BODY>} /** * <p>retrieveParameters.</p> * * @param context a {@link WebContext} object * @return a {@link Map} object */ protected Map<String, List<String>> retrieveParameters(final WebContext context) { val requestParameters = context.getRequestParameters(); final Map<String, List<String>> map = new HashMap<>(); for (val entry : requestParameters.entrySet()) { map.put(entry.getKey(), Arrays.asList(entry.getValue())); } return map; } }
val webContext = ctx.webContext(); val logoutToken = webContext.getRequestParameter("logout_token"); val sid = webContext.getRequestParameter(Pac4jConstants.OIDC_CLAIM_SESSIONID); // back-channel logout if (logoutToken.isPresent()) { try { val jwt = JWTParser.parse(logoutToken.get()); // we should use the tokenValidator, but we can't as validation fails on missing claims: exp, iat... //final IDTokenClaimsSet claims = configuration.findTokenValidator().validate(jwt, null); //final String sid = (String) claims.getClaim(Pac4jConstants.OIDC_CLAIM_SESSIONID); val sessionId = (String) jwt.getJWTClaimsSet().getClaim(Pac4jConstants.OIDC_CLAIM_SESSIONID); LOGGER.debug("Handling back-channel logout for sessionId: {}", sessionId); return Optional.of(new SessionKeyCredentials(LogoutType.BACK, sessionId)); } catch (final java.text.ParseException e) { LOGGER.error("Cannot validate JWT logout token", e); throw new BadRequestAction(); } // front channel logout } else if (sid.isPresent()) { val sessionId = sid.get(); LOGGER.debug("Handling front-channel logout for sessionId: {}", sessionId); return Optional.of(new SessionKeyCredentials(LogoutType.FRONT, sessionId)); // authentication } else { val computedCallbackUrl = client.computeFinalCallbackUrl(webContext); val parameters = retrieveParameters(webContext); AuthenticationResponse response; try { response = AuthenticationResponseParser.parse(new URI(computedCallbackUrl), parameters); } catch (final URISyntaxException | ParseException e) { throw new OidcException(e); } if (response instanceof AuthenticationErrorResponse) { LOGGER.error("Bad authentication response, error={}", ((AuthenticationErrorResponse) response).getErrorObject()); return Optional.empty(); } LOGGER.debug("Authentication response successful"); var successResponse = (AuthenticationSuccessResponse) response; var metadata = configuration.getOpMetadataResolver().load(); if (metadata.supportsAuthorizationResponseIssuerParam() && !metadata.getIssuer().equals(successResponse.getIssuer())) { throw new OidcIssuerMismatchException("Issuer mismatch, possible mix-up attack."); } if (configuration.isWithState()) { // Validate state for CSRF mitigation val requestState = (State) configuration.getValueRetriever() .retrieve(ctx, client.getStateSessionAttributeName(), client) .orElseThrow(() -> new OidcMissingSessionStateException("State cannot be determined")); val responseState = successResponse.getState(); if (responseState == null) { throw new OidcMissingStateParameterException("Missing state parameter"); } LOGGER.debug("Request state: {}/response state: {}", requestState, responseState); if (!requestState.equals(responseState)) { throw new OidcStateMismatchException( "State parameter is different from the one sent in authentication request."); } } val credentials = new OidcCredentials(); // get authorization code val code = successResponse.getAuthorizationCode(); if (code != null) { credentials.setCode(code.getValue()); } // get ID token val idToken = successResponse.getIDToken(); if (idToken != null) { credentials.setIdToken(idToken.serialize()); } // get access token val accessToken = successResponse.getAccessToken(); if (accessToken != null) { credentials.setAccessTokenObject(accessToken); } return Optional.of(credentials); }
352
1,011
1,363
<no_super_class>
pac4j_pac4j
pac4j/pac4j-oidc/src/main/java/org/pac4j/oidc/logout/OidcLogoutActionBuilder.java
OidcLogoutActionBuilder
getLogoutAction
class OidcLogoutActionBuilder implements LogoutActionBuilder { protected OidcConfiguration configuration; private AjaxRequestResolver ajaxRequestResolver = new DefaultAjaxRequestResolver(); /** * <p>Constructor for OidcLogoutActionBuilder.</p> * * @param configuration a {@link OidcConfiguration} object */ public OidcLogoutActionBuilder(final OidcConfiguration configuration) { CommonHelper.assertNotNull("configuration", configuration); this.configuration = configuration; } /** {@inheritDoc} */ @Override public Optional<RedirectionAction> getLogoutAction(final CallContext ctx, final UserProfile currentProfile, final String targetUrl) {<FILL_FUNCTION_BODY>} /** * <p>Getter for the field <code>ajaxRequestResolver</code>.</p> * * @return a {@link AjaxRequestResolver} object */ public AjaxRequestResolver getAjaxRequestResolver() { return ajaxRequestResolver; } /** * <p>Setter for the field <code>ajaxRequestResolver</code>.</p> * * @param ajaxRequestResolver a {@link AjaxRequestResolver} object */ public void setAjaxRequestResolver(final AjaxRequestResolver ajaxRequestResolver) { CommonHelper.assertNotNull("ajaxRequestResolver", ajaxRequestResolver); this.ajaxRequestResolver = ajaxRequestResolver; } }
val logoutUrl = configuration.findLogoutUrl(); if (CommonHelper.isNotBlank(logoutUrl) && currentProfile instanceof OidcProfile) { try { val endSessionEndpoint = new URI(logoutUrl); val idToken = ((OidcProfile) currentProfile).getIdToken(); LogoutRequest logoutRequest; if (CommonHelper.isNotBlank(targetUrl)) { logoutRequest = new LogoutRequest(endSessionEndpoint, idToken, new URI(targetUrl), null); } else { logoutRequest = new LogoutRequest(endSessionEndpoint, idToken); } val webContext = ctx.webContext(); if (ajaxRequestResolver.isAjax(ctx)) { ctx.sessionStore().set(webContext, Pac4jConstants.REQUESTED_URL, null); webContext.setResponseHeader(HttpConstants.LOCATION_HEADER, logoutRequest.toURI().toString()); throw new ForbiddenAction(); } return Optional.of(HttpActionHelper.buildRedirectUrlAction(webContext, logoutRequest.toURI().toString())); } catch (final URISyntaxException e) { throw new OidcException(e); } } return Optional.empty();
373
316
689
<no_super_class>
pac4j_pac4j
pac4j/pac4j-oidc/src/main/java/org/pac4j/oidc/logout/processor/OidcLogoutProcessor.java
OidcLogoutProcessor
processLogout
class OidcLogoutProcessor implements LogoutProcessor { protected final OidcConfiguration configuration; protected final SessionLogoutHandler sessionLogoutHandler; /** * <p>Constructor for OidcLogoutProcessor.</p> * * @param configuration a {@link OidcConfiguration} object */ public OidcLogoutProcessor(final OidcConfiguration configuration, final SessionLogoutHandler sessionLogoutHandler) { CommonHelper.assertNotNull("configuration", configuration); this.configuration = configuration; this.sessionLogoutHandler = sessionLogoutHandler; } /** {@inheritDoc} */ @Override public HttpAction processLogout(final CallContext ctx, final Credentials logoutCredentials) {<FILL_FUNCTION_BODY>} }
assertTrue(logoutCredentials instanceof SessionKeyCredentials, "credentials must be of type SessionKeyCredentials"); val credentials = (SessionKeyCredentials) logoutCredentials; val sessionKey = credentials.getSessionKey(); if (sessionLogoutHandler != null) { sessionLogoutHandler.destroySession(ctx, sessionKey); } val webContext = ctx.webContext(); webContext.setResponseHeader("Cache-Control", "no-cache, no-store"); webContext.setResponseHeader("Pragma", "no-cache"); return new OkAction(Pac4jConstants.EMPTY_STRING);
198
160
358
<no_super_class>
pac4j_pac4j
pac4j/pac4j-oidc/src/main/java/org/pac4j/oidc/metadata/AzureAdOpMetadataResolver.java
AzureAdOpMetadataResolver
internalLoad
class AzureAdOpMetadataResolver extends OidcOpMetadataResolver { /** * <p>Constructor for AzureAdOpMetadataResolver.</p> * * @param configuration a {@link OidcConfiguration} object */ public AzureAdOpMetadataResolver(final OidcConfiguration configuration) { super(configuration); } /** {@inheritDoc} */ @Override protected void internalLoad() {<FILL_FUNCTION_BODY>} }
this.loaded = retrieveMetadata(); this.clientAuthentication = computeClientAuthentication(); this.tokenValidator = new AzureAdTokenValidator(configuration, this.loaded);
119
44
163
<methods>public void <init>(org.pac4j.oidc.config.OidcConfiguration) <variables>private static final Collection<com.nimbusds.oauth2.sdk.auth.ClientAuthenticationMethod> SUPPORTED_METHODS,protected com.nimbusds.oauth2.sdk.auth.ClientAuthentication clientAuthentication,protected final non-sealed org.pac4j.oidc.config.OidcConfiguration configuration,protected org.pac4j.oidc.profile.creator.TokenValidator tokenValidator
pac4j_pac4j
pac4j/pac4j-oidc/src/main/java/org/pac4j/oidc/metadata/OidcOpMetadataResolver.java
OidcOpMetadataResolver
computeClientAuthentication
class OidcOpMetadataResolver extends SpringResourceLoader<OIDCProviderMetadata> { private static final Collection<ClientAuthenticationMethod> SUPPORTED_METHODS = Arrays.asList( ClientAuthenticationMethod.CLIENT_SECRET_POST, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, ClientAuthenticationMethod.PRIVATE_KEY_JWT, ClientAuthenticationMethod.NONE); protected final OidcConfiguration configuration; @Getter protected ClientAuthentication clientAuthentication; @Getter protected TokenValidator tokenValidator; /** * <p>Constructor for OidcOpMetadataResolver.</p> * * @param configuration a {@link OidcConfiguration} object */ public OidcOpMetadataResolver(final OidcConfiguration configuration) { super(buildResource(configuration)); this.configuration = configuration; } private static Resource buildResource(final OidcConfiguration configuration) { if (configuration != null) { return SpringResourceHelper.buildResourceFromPath(configuration.getDiscoveryURI()); } return null; } /** {@inheritDoc} */ @Override protected void internalLoad() { this.loaded = retrieveMetadata(); this.clientAuthentication = computeClientAuthentication(); this.tokenValidator = new TokenValidator(configuration, this.loaded); } /** * <p>retrieveMetadata.</p> * * @return a {@link OIDCProviderMetadata} object */ protected OIDCProviderMetadata retrieveMetadata() { try (val in = SpringResourceHelper.getResourceInputStream( resource, null, configuration.getSslSocketFactory(), configuration.getHostnameVerifier(), configuration.getConnectTimeout(), configuration.getReadTimeout() )) { val metadata = IOUtils.readInputStreamToString(in); return OIDCProviderMetadata.parse(metadata); } catch (final IOException | ParseException e) { throw new OidcException("Error getting OP metadata", e); } } /** * <p>computeClientAuthentication.</p> * * @return a {@link ClientAuthentication} object */ protected ClientAuthentication computeClientAuthentication() {<FILL_FUNCTION_BODY>} private static ClientAuthenticationMethod getPreferredAuthenticationMethod(OidcConfiguration config) { val configurationMethod = config.getClientAuthenticationMethod(); if (configurationMethod == null) { return null; } if (!SUPPORTED_METHODS.contains(configurationMethod)) { throw new OidcUnsupportedClientAuthMethodException("Configured authentication method (" + configurationMethod + ") is not supported."); } return configurationMethod; } private static ClientAuthenticationMethod firstSupportedMethod( final Collection<ClientAuthenticationMethod> serverSupportedAuthMethods, Collection<ClientAuthenticationMethod> clientSupportedAuthMethods) { Collection<ClientAuthenticationMethod> supportedMethods = clientSupportedAuthMethods != null ? clientSupportedAuthMethods : SUPPORTED_METHODS; var firstSupported = serverSupportedAuthMethods.stream().filter(supportedMethods::contains).findFirst(); if (firstSupported.isPresent()) { return firstSupported.get(); } else { throw new OidcUnsupportedClientAuthMethodException("None of the Token endpoint provider metadata authentication methods are " + "supported: " + serverSupportedAuthMethods); } } }
val _clientID = new ClientID(configuration.getClientId()); if (configuration.getSecret() != null) { // check authentication methods val serverSupportedAuthMethods = this.loaded.getTokenEndpointAuthMethods(); val preferredMethod = getPreferredAuthenticationMethod(configuration); final ClientAuthenticationMethod chosenMethod; if (isNotEmpty(serverSupportedAuthMethods)) { if (preferredMethod != null) { if (serverSupportedAuthMethods.contains(preferredMethod)) { chosenMethod = preferredMethod; } else { throw new OidcUnsupportedClientAuthMethodException( "Preferred authentication method (" + preferredMethod + ") not supported " + "by provider according to provider metadata (" + serverSupportedAuthMethods + ")."); } } else { chosenMethod = firstSupportedMethod(serverSupportedAuthMethods, configuration.getSupportedClientAuthenticationMethods()); } } else { chosenMethod = preferredMethod != null ? preferredMethod : ClientAuthenticationMethod.getDefault(); LOGGER.info("Provider metadata does not provide Token endpoint authentication methods. Using: {}", chosenMethod); } if (ClientAuthenticationMethod.CLIENT_SECRET_POST.equals(chosenMethod)) { val _secret = new Secret(configuration.getSecret()); return new ClientSecretPost(_clientID, _secret); } else if (ClientAuthenticationMethod.CLIENT_SECRET_BASIC.equals(chosenMethod)) { val _secret = new Secret(configuration.getSecret()); return new ClientSecretBasic(_clientID, _secret); } else if (ClientAuthenticationMethod.PRIVATE_KEY_JWT.equals(chosenMethod)) { val privateKeyJwtConfig = configuration.getPrivateKeyJWTClientAuthnMethodConfig(); assertNotNull("privateKeyJwtConfig", privateKeyJwtConfig); val jwsAlgo = privateKeyJwtConfig.getJwsAlgorithm(); assertNotNull("privateKeyJwtConfig.getJwsAlgorithm()", jwsAlgo); val privateKey = privateKeyJwtConfig.getPrivateKey(); assertNotNull("privateKeyJwtConfig.getPrivateKey()", privateKey); val keyID = privateKeyJwtConfig.getKeyID(); try { return new PrivateKeyJWT(_clientID, this.loaded.getTokenEndpointURI(), jwsAlgo, privateKey, keyID, null); } catch (final JOSEException e) { throw new OidcException("Cannot instantiate private key JWT client authentication method", e); } } else { throw new OidcUnsupportedClientAuthMethodException("Unsupported client authentication method: " + chosenMethod); } } return null;
876
674
1,550
<methods>public non-sealed void <init>() ,public boolean hasChanged() ,public final com.nimbusds.openid.connect.sdk.op.OIDCProviderMetadata load() <variables>private static final long NO_LAST_MODIFIED,private final java.util.concurrent.atomic.AtomicBoolean byteArrayHasChanged,private long lastModified,protected com.nimbusds.openid.connect.sdk.op.OIDCProviderMetadata loaded,private final java.util.concurrent.locks.Lock lock,protected final non-sealed org.springframework.core.io.Resource resource
pac4j_pac4j
pac4j/pac4j-oidc/src/main/java/org/pac4j/oidc/metadata/StaticOidcOpMetadataResolver.java
StaticOidcOpMetadataResolver
internalLoad
class StaticOidcOpMetadataResolver extends OidcOpMetadataResolver { private final OIDCProviderMetadata staticMetadata; /** * <p>Constructor for StaticOidcOpMetadataResolver.</p> * * @param configuration a {@link OidcConfiguration} object * @param staticMetadata a {@link OIDCProviderMetadata} object */ public StaticOidcOpMetadataResolver(final OidcConfiguration configuration, final OIDCProviderMetadata staticMetadata) { super(configuration); this.staticMetadata = staticMetadata; } /** {@inheritDoc} */ @Override protected void internalLoad() {<FILL_FUNCTION_BODY>} }
this.loaded = staticMetadata; this.clientAuthentication = computeClientAuthentication(); this.tokenValidator = new TokenValidator(configuration, this.loaded);
177
43
220
<methods>public void <init>(org.pac4j.oidc.config.OidcConfiguration) <variables>private static final Collection<com.nimbusds.oauth2.sdk.auth.ClientAuthenticationMethod> SUPPORTED_METHODS,protected com.nimbusds.oauth2.sdk.auth.ClientAuthentication clientAuthentication,protected final non-sealed org.pac4j.oidc.config.OidcConfiguration configuration,protected org.pac4j.oidc.profile.creator.TokenValidator tokenValidator
pac4j_pac4j
pac4j/pac4j-oidc/src/main/java/org/pac4j/oidc/profile/OidcProfile.java
OidcProfile
getAccessToken
class OidcProfile extends AbstractJwtProfile { @Serial private static final long serialVersionUID = -52855988661742374L; @Override @JsonIgnore public String getFirstName() { return (String) getAttribute(OidcProfileDefinition.GIVEN_NAME); } @JsonIgnore public String getMiddleName() { return (String) getAttribute(OidcProfileDefinition.MIDDLE_NAME); } @Override @JsonIgnore public String getDisplayName() { return (String) getAttribute(OidcProfileDefinition.NAME); } @JsonIgnore public String getNickname() { return (String) getAttribute(OidcProfileDefinition.NICKNAME); } @Override @JsonIgnore public String getUsername() { return (String) getAttribute(OidcProfileDefinition.PREFERRED_USERNAME); } @Override @JsonIgnore public URI getPictureUrl() { return (URI) getAttribute(OidcProfileDefinition.PICTURE); } @Override @JsonIgnore public URI getProfileUrl() { return (URI) getAttribute(OidcProfileDefinition.PROFILE); } @Override @JsonIgnore public String getLocation() { return (String) getAttribute(OidcProfileDefinition.ZONEINFO); } @JsonIgnore public Boolean getEmailVerified() { return (Boolean) getAttribute(OidcProfileDefinition.EMAIL_VERIFIED); } @JsonIgnore public String getPhoneNumber() { return (String) getAttribute(OidcProfileDefinition.PHONE_NUMBER); } @JsonIgnore public Boolean getPhoneNumberVerified() { return (Boolean) getAttribute(OidcProfileDefinition.PHONE_NUMBER_VERIFIED); } @JsonIgnore public Date getUpdatedAt() { return getAttributeAsDate(OidcProfileDefinition.UPDATED_AT); } @JsonIgnore public Date getAuthTime() { return (Date) getAttribute(OidcProfileDefinition.AUTH_TIME); } @JsonIgnore public String getNonce() { return (String) getAttribute(OidcProfileDefinition.NONCE); } @JsonIgnore public String getAcr() { return (String) getAttribute(OidcProfileDefinition.ACR); } @JsonIgnore public Object getAmr() { return getAttribute(OidcProfileDefinition.AMR); } @JsonIgnore public String getAzp() { return (String) getAttribute(OidcProfileDefinition.AZP); } public void setAccessToken(final AccessToken accessToken) { if (accessToken != null) { val accessTokenBase64 = Base64.getEncoder().encodeToString( accessToken.toJSONString().getBytes(StandardCharsets.UTF_8)); addAttribute(OidcProfileDefinition.ACCESS_TOKEN, accessTokenBase64); if (accessToken.getLifetime() != 0) { setExpiration(Date.from(Instant.now().plusSeconds(accessToken.getLifetime()))); } else { Date exp = null; try { val jwtClaimsSet = JWTParser.parse(accessToken.getValue()).getJWTClaimsSet(); if (jwtClaimsSet != null) { exp = jwtClaimsSet.getExpirationTime(); } } catch (ParseException e) { logger.trace(e.getMessage(), e); } setExpiration(exp); } } } @JsonIgnore public AccessToken getAccessToken() {<FILL_FUNCTION_BODY>} @JsonIgnore public String getIdTokenString() { return (String) getAttribute(OidcProfileDefinition.ID_TOKEN); } public void setIdTokenString(final String idToken) { addAttribute(OidcProfileDefinition.ID_TOKEN, idToken); } @JsonIgnore public JWT getIdToken() { if (getIdTokenString() != null) { try { return JWTParser.parse(getIdTokenString()); } catch (final ParseException e) { throw new OidcException(e); } } else { return null; } } @JsonIgnore public RefreshToken getRefreshToken() { try { val refreshTokenObject = getAttribute(OidcProfileDefinition.REFRESH_TOKEN); if (refreshTokenObject != null) { return new RefreshToken(refreshTokenObject.toString()); } return null; } catch (final Exception e) { throw new IllegalArgumentException(e); } } public void setRefreshToken(final RefreshToken refreshToken) { if (refreshToken != null) { addAttribute(OidcProfileDefinition.REFRESH_TOKEN, refreshToken.getValue()); } } @Override public void removeLoginData() { removeAttribute(OidcProfileDefinition.ID_TOKEN); removeAttribute(OidcProfileDefinition.ACCESS_TOKEN); removeAttribute(OidcProfileDefinition.REFRESH_TOKEN); } @JsonIgnore public int getTokenExpirationAdvance() { var tokenExpirationAdvance = getAttribute(OidcProfileDefinition.TOKEN_EXPIRATION_ADVANCE); if (tokenExpirationAdvance != null) { if (tokenExpirationAdvance instanceof Long) { return ((Long) tokenExpirationAdvance).intValue(); } else if (tokenExpirationAdvance instanceof Integer) { return (int) tokenExpirationAdvance; } } return 0; } @JsonIgnore public void setTokenExpirationAdvance(int tokenExpirationAdvance) { addAttribute(OidcProfileDefinition.TOKEN_EXPIRATION_ADVANCE, tokenExpirationAdvance); } @JsonIgnore public Date getExpiration() { return getAttributeAsDate(OidcProfileDefinition.EXPIRATION); } public void setExpiration(final Date expiration) { if (expiration != null) { addAttribute(OidcProfileDefinition.EXPIRATION, expiration.getTime()); } else { removeAttribute(OidcProfileDefinition.EXPIRATION); } } @JsonIgnore public boolean isExpired() { var tokenExpirationAdvance = getTokenExpirationAdvance(); if (tokenExpirationAdvance < 0) { return false; } var expiration = getExpiration(); return expiration != null && expiration.toInstant().isBefore(Instant.now().plusSeconds(tokenExpirationAdvance)); } }
try { val accessTokenObject = getAttribute(OidcProfileDefinition.ACCESS_TOKEN); if (accessTokenObject != null) { val accessTokenBase64 = accessTokenObject.toString(); val base64Decoded = new String(Base64.getDecoder().decode(accessTokenBase64), StandardCharsets.UTF_8); val accessTokenJSON = new JSONObject(new ObjectMapper().readValue(base64Decoded, Map.class)); return AccessToken.parse(accessTokenJSON); } return null; } catch (final Exception e) { throw new IllegalArgumentException(e); }
1,816
163
1,979
<methods>public non-sealed void <init>() ,public List<java.lang.String> getAudience() ,public java.util.Date getExpirationDate() ,public java.util.Date getIssuedAt() ,public java.lang.String getIssuer() ,public java.util.Date getNotBefore() ,public java.lang.String getSubject() <variables>private static final long serialVersionUID
pac4j_pac4j
pac4j/pac4j-oidc/src/main/java/org/pac4j/oidc/profile/converter/OidcLongTimeConverter.java
OidcLongTimeConverter
convert
class OidcLongTimeConverter implements AttributeConverter { /** {@inheritDoc} */ @Override public Date convert(final Object attribute) {<FILL_FUNCTION_BODY>} }
if (attribute instanceof Long) { final long seconds = (Long) attribute; return new Date(seconds * 1000); } return null;
51
45
96
<no_super_class>
pac4j_pac4j
pac4j/pac4j-oidc/src/main/java/org/pac4j/oidc/profile/creator/OidcProfileCreator.java
OidcProfileCreator
create
class OidcProfileCreator extends ProfileDefinitionAware implements ProfileCreator { protected OidcConfiguration configuration; protected OidcClient client; /** * <p>Constructor for OidcProfileCreator.</p> * * @param configuration a {@link OidcConfiguration} object * @param client a {@link OidcClient} object */ public OidcProfileCreator(final OidcConfiguration configuration, final OidcClient client) { this.configuration = configuration; this.client = client; } /** {@inheritDoc} */ @Override protected void internalInit(final boolean forceReinit) { assertNotNull("configuration", configuration); setProfileDefinitionIfUndefined(new OidcProfileDefinition()); } /** {@inheritDoc} */ @Override @SuppressWarnings("unchecked") public Optional<UserProfile> create(final CallContext ctx, final Credentials credentials) {<FILL_FUNCTION_BODY>} public void callUserInfoEndpoint(final URI userInfoEndpointUri, final AccessToken accessToken, final UserProfile profile) throws IOException, ParseException, java.text.ParseException, UserInfoErrorResponseException { val opMetadata = configuration.getOpMetadataResolver().load(); if (opMetadata.getUserInfoEndpointURI() != null && accessToken != null) { Request userInfoRequest = new UserInfoRequest(opMetadata.getUserInfoEndpointURI(), accessToken); val userInfoHttpRequest = userInfoRequest.toHTTPRequest(); configuration.configureHttpRequest(userInfoHttpRequest); val httpResponse = userInfoHttpRequest.send(); LOGGER.debug("User info response: status={}, content={}", httpResponse.getStatusCode(), httpResponse.getContent()); val userInfoResponse = UserInfoResponse.parse(httpResponse); if (userInfoResponse instanceof UserInfoErrorResponse) { final var error = ((UserInfoErrorResponse) userInfoResponse).getErrorObject(); LOGGER.error("Bad User Info response, error={}", error); throw new UserInfoErrorResponseException(error.toString()); } else { val userInfoSuccessResponse = (UserInfoSuccessResponse) userInfoResponse; final JWTClaimsSet userInfoClaimsSet; if (userInfoSuccessResponse.getUserInfo() != null) { userInfoClaimsSet = userInfoSuccessResponse.getUserInfo().toJWTClaimsSet(); } else { userInfoClaimsSet = userInfoSuccessResponse.getUserInfoJWT().getJWTClaimsSet(); } if (userInfoClaimsSet != null) { getProfileDefinition().convertAndAdd(profile, userInfoClaimsSet.getClaims(), null); } else { LOGGER.warn("Cannot retrieve claims from user info"); } } } } private void collectClaimsFromAccessTokenIfAny(final OidcCredentials credentials, final Nonce nonce, UserProfile profile) { try { var accessToken = credentials.toAccessToken(); if (accessToken != null) { var accessTokenJwt = JWTParser.parse(accessToken.getValue()); var accessTokenClaims = configuration.getOpMetadataResolver().getTokenValidator().validate(accessTokenJwt, nonce); // add attributes of the access token if they don't already exist for (val entry : accessTokenClaims.toJWTClaimsSet().getClaims().entrySet()) { val key = entry.getKey(); val value = entry.getValue(); if (!JwtClaims.SUBJECT.equals(key) && profile.getAttribute(key) == null) { getProfileDefinition().convertAndAdd(profile, PROFILE_ATTRIBUTE, key, value); } } } } catch (final ParseException | java.text.ParseException | JOSEException | BadJOSEException e) { LOGGER.debug(e.getMessage(), e); } catch (final Exception e) { throw new OidcException(e); } } }
init(); OidcCredentials oidcCredentials = null; AccessToken accessToken = null; val regularOidcFlow = credentials instanceof OidcCredentials; if (regularOidcFlow) { oidcCredentials = (OidcCredentials) credentials; accessToken = oidcCredentials.toAccessToken(); } else { // we assume the access token only has been passed: it can be a bearer call (HTTP client) val token = ((TokenCredentials) credentials).getToken(); accessToken = new BearerAccessToken(token); } // Create profile val profile = (OidcProfile) getProfileDefinition().newProfile(); profile.setAccessToken(accessToken); if (oidcCredentials != null) { if (oidcCredentials.getIdToken() != null) { profile.setIdTokenString(oidcCredentials.toIdToken().getParsedString()); } // Check if there is a refresh token val refreshToken = oidcCredentials.toRefreshToken(); if (refreshToken != null && !refreshToken.getValue().isEmpty()) { profile.setRefreshToken(refreshToken); LOGGER.debug("Refresh Token successful retrieved"); } } try { final Nonce nonce; if (configuration.isUseNonce()) { nonce = new Nonce((String) ctx.sessionStore().get(ctx.webContext(), client.getNonceSessionAttributeName()).orElse(null)); } else { nonce = null; } // Check ID Token if (oidcCredentials != null && oidcCredentials.getIdToken() != null) { val claimsSet = configuration.getOpMetadataResolver().getTokenValidator().validate(oidcCredentials.toIdToken(), nonce); assertNotNull("claimsSet", claimsSet); profile.setId(ProfileHelper.sanitizeIdentifier(claimsSet.getSubject())); // keep the session ID if provided val sid = (String) claimsSet.getClaim(Pac4jConstants.OIDC_CLAIM_SESSIONID); val sessionLogoutHandler = client.findSessionLogoutHandler(); if (isNotBlank(sid) && sessionLogoutHandler != null) { sessionLogoutHandler.recordSession(ctx, sid); } } if (configuration.isCallUserInfoEndpoint()) { final var uri = configuration.getOpMetadataResolver().load().getUserInfoEndpointURI(); try { callUserInfoEndpoint(uri, accessToken, profile); } catch (final UserInfoErrorResponseException e) { // bearer call -> no profile returned if (!regularOidcFlow) { return Optional.empty(); } } } // add attributes of the ID token if they don't already exist if (oidcCredentials != null && oidcCredentials.getIdToken() != null) { for (val entry : oidcCredentials.toIdToken().getJWTClaimsSet().getClaims().entrySet()) { val key = entry.getKey(); val value = entry.getValue(); // it's not the subject and this attribute does not already exist, add it if (!JwtClaims.SUBJECT.equals(key) && profile.getAttribute(key) == null) { getProfileDefinition().convertAndAdd(profile, PROFILE_ATTRIBUTE, key, value); } } } if (oidcCredentials != null && configuration.isIncludeAccessTokenClaimsInProfile()) { collectClaimsFromAccessTokenIfAny(oidcCredentials, nonce, profile); } // session expiration with token behavior profile.setTokenExpirationAdvance(configuration.getTokenExpirationAdvance()); return Optional.of(profile); } catch (final IOException | ParseException | JOSEException | BadJOSEException | java.text.ParseException e) { throw new OidcException(e); }
1,022
1,020
2,042
<methods>public non-sealed void <init>() ,public org.pac4j.core.profile.definition.ProfileDefinition getProfileDefinition() ,public void setProfileDefinition(org.pac4j.core.profile.definition.ProfileDefinition) <variables>private org.pac4j.core.profile.definition.ProfileDefinition profileDefinition
pac4j_pac4j
pac4j/pac4j-oidc/src/main/java/org/pac4j/oidc/profile/creator/TokenValidator.java
TokenValidator
validate
class TokenValidator { private final List<IDTokenValidator> idTokenValidators; private final OidcConfiguration configuration; private final OIDCProviderMetadata metadata; /** * <p>Constructor for TokenValidator.</p> * * @param configuration a {@link OidcConfiguration} object * @param metadata a {@link OIDCProviderMetadata} object */ public TokenValidator(final OidcConfiguration configuration, final OIDCProviderMetadata metadata) { CommonHelper.assertNotNull("configuration", configuration); CommonHelper.assertNotNull("metadata", metadata); this.configuration = configuration; this.metadata = metadata; // check algorithms val metadataAlgorithms = metadata.getIDTokenJWSAlgs(); CommonHelper.assertTrue(CommonHelper.isNotEmpty(metadataAlgorithms), "There must at least one JWS algorithm supported on the OpenID Connect provider side"); List<JWSAlgorithm> jwsAlgorithms = new ArrayList<>(); val preferredAlgorithm = configuration.getPreferredJwsAlgorithm(); if (metadataAlgorithms.contains(preferredAlgorithm)) { jwsAlgorithms.add(preferredAlgorithm); } else { jwsAlgorithms = metadataAlgorithms; LOGGER.warn("Preferred JWS algorithm: {} not available. Using all metadata algorithms: {}", preferredAlgorithm, metadataAlgorithms); } idTokenValidators = new ArrayList<>(); val _clientID = new ClientID(configuration.getClientId()); for (var jwsAlgorithm : jwsAlgorithms) { // build validator final IDTokenValidator idTokenValidator; if ("none".equals(jwsAlgorithm.getName())) { final String responseType = configuration.getResponseType(); final boolean responseTypeContainsIdToken = responseType != null && responseType.contains(OIDCResponseTypeValue.ID_TOKEN.toString()); if (!configuration.isAllowUnsignedIdTokens() || responseTypeContainsIdToken) { throw new OidcTokenException("Unsigned ID tokens are not allowed: " + "they must be explicitly enabled on client side and " + "the response_type used must return no ID Token from the authorization endpoint"); } LOGGER.warn("Allowing unsigned ID tokens"); idTokenValidator = new IDTokenValidator(metadata.getIssuer(), _clientID); } else if (CommonHelper.isNotBlank(configuration.getSecret()) && (JWSAlgorithm.HS256.equals(jwsAlgorithm) || JWSAlgorithm.HS384.equals(jwsAlgorithm) || JWSAlgorithm.HS512.equals(jwsAlgorithm))) { val _secret = new Secret(configuration.getSecret()); idTokenValidator = createHMACTokenValidator(jwsAlgorithm, _clientID, _secret); } else { idTokenValidator = createRSATokenValidator(jwsAlgorithm, _clientID); } idTokenValidator.setMaxClockSkew(configuration.getMaxClockSkew()); idTokenValidators.add(idTokenValidator); } } /** * <p>createRSATokenValidator.</p> * * @param jwsAlgorithm a {@link JWSAlgorithm} object * @param clientID a {@link ClientID} object * @return a {@link IDTokenValidator} object */ protected IDTokenValidator createRSATokenValidator(final JWSAlgorithm jwsAlgorithm, final ClientID clientID) { try { return new IDTokenValidator(metadata.getIssuer(), clientID, jwsAlgorithm, metadata.getJWKSetURI().toURL(), configuration.findResourceRetriever()); } catch (final MalformedURLException e) { throw new OidcException(e); } } /** * <p>createHMACTokenValidator.</p> * * @param jwsAlgorithm a {@link JWSAlgorithm} object * @param clientID a {@link ClientID} object * @param secret a {@link Secret} object * @return a {@link IDTokenValidator} object */ protected IDTokenValidator createHMACTokenValidator(final JWSAlgorithm jwsAlgorithm, final ClientID clientID, final Secret secret) { return new IDTokenValidator(metadata.getIssuer(), clientID, jwsAlgorithm, secret); } /** * <p>validate.</p> * * @param idToken a {@link JWT} object * @param expectedNonce a {@link Nonce} object * @return a {@link IDTokenClaimsSet} object * @throws BadJOSEException if any. * @throws JOSEException if any. */ public IDTokenClaimsSet validate(final JWT idToken, final Nonce expectedNonce) throws BadJOSEException, JOSEException {<FILL_FUNCTION_BODY>} // for tests List<IDTokenValidator> getIdTokenValidators() { return idTokenValidators; } }
BadJOSEException badJOSEException = null; JOSEException joseException = null; for (val idTokenValidator : idTokenValidators) { LOGGER.debug("Trying IDToken validator: {}", idTokenValidator); try { return idTokenValidator.validate(idToken, expectedNonce); } catch (final BadJOSEException e1) { LOGGER.debug(e1.getMessage(), e1); badJOSEException = e1; } catch (final JOSEException e2) { LOGGER.debug(e2.getMessage(), e2); joseException = e2; } } if (badJOSEException != null) { throw badJOSEException; } else if (joseException != null) { throw joseException; } else { throw new OidcTokenException("Unable to validate the ID token"); }
1,273
234
1,507
<no_super_class>
pac4j_pac4j
pac4j/pac4j-oidc/src/main/java/org/pac4j/oidc/redirect/OidcRedirectionActionBuilder.java
OidcRedirectionActionBuilder
addStateAndNonceParameters
class OidcRedirectionActionBuilder implements RedirectionActionBuilder { protected OidcClient client; /** * <p>Constructor for OidcRedirectionActionBuilder.</p> * * @param client a {@link OidcClient} object */ public OidcRedirectionActionBuilder(final OidcClient client) { CommonHelper.assertNotNull("client", client); this.client = client; } @Override public Optional<RedirectionAction> getRedirectionAction(final CallContext ctx) { val webContext = ctx.webContext(); val configContext = new OidcConfigurationContext(webContext, client.getConfiguration()); val params = buildParams(webContext); val computedCallbackUrl = client.computeFinalCallbackUrl(webContext); params.put(OidcConfiguration.REDIRECT_URI, computedCallbackUrl); addStateAndNonceParameters(ctx, params); var maxAge = configContext.getMaxAge(); if (maxAge != null) { params.put(OidcConfiguration.MAX_AGE, maxAge.toString()); } if (configContext.isForceAuthn()) { params.put(OidcConfiguration.PROMPT, "login"); params.put(OidcConfiguration.MAX_AGE, "0"); } if (configContext.isPassive()) { params.put(OidcConfiguration.PROMPT, "none"); } val location = buildAuthenticationRequestUrl(params); LOGGER.debug("Authentication request url: {}", location); return Optional.of(HttpActionHelper.buildRedirectUrlAction(webContext, location)); } /** * <p>buildParams.</p> * * @param webContext a {@link WebContext} object * @return a {@link Map} object */ protected Map<String, String> buildParams(final WebContext webContext) { val configContext = new OidcConfigurationContext(webContext, client.getConfiguration()); val authParams = new HashMap<String, String>(); authParams.put(OidcConfiguration.SCOPE, configContext.getScope().replace(",", " ")); authParams.put(OidcConfiguration.RESPONSE_TYPE, configContext.getResponseType()); authParams.put(OidcConfiguration.RESPONSE_MODE, configContext.getResponseMode()); authParams.putAll(configContext.getCustomParams()); authParams.put(OidcConfiguration.CLIENT_ID, configContext.getConfiguration().getClientId()); return new HashMap<>(authParams); } protected void addStateAndNonceParameters(final CallContext ctx, final Map<String, String> params) {<FILL_FUNCTION_BODY>} protected String buildAuthenticationRequestUrl(final Map<String, String> params) { // Build authentication request query string String queryString; try { val parameters = params.entrySet().stream().collect( Collectors.toMap(Map.Entry::getKey, e -> Collections.singletonList(e.getValue()))); queryString = AuthenticationRequest.parse(parameters).toQueryString(); queryString = queryString.replaceAll("\\+", "%20"); } catch (final Exception e) { throw new OidcException(e); } return client.getConfiguration().getOpMetadataResolver().load().getAuthorizationEndpointURI().toString() + '?' + queryString; } }
val webContext = ctx.webContext(); val sessionStore = ctx.sessionStore(); // Init state for CSRF mitigation if (client.getConfiguration().isWithState()) { val state = new State(client.getConfiguration().getStateGenerator().generateValue(ctx)); params.put(OidcConfiguration.STATE, state.getValue()); sessionStore.set(webContext, client.getStateSessionAttributeName(), state); } // Init nonce for replay attack mitigation if (client.getConfiguration().isUseNonce()) { val nonce = new Nonce(); params.put(OidcConfiguration.NONCE, nonce.getValue()); sessionStore.set(webContext, client.getNonceSessionAttributeName(), nonce.getValue()); } var pkceMethod = client.getConfiguration().findPkceMethod(); if (pkceMethod != null) { val verifier = new CodeVerifier(client.getConfiguration().getCodeVerifierGenerator().generateValue(ctx)); sessionStore.set(webContext, client.getCodeVerifierSessionAttributeName(), verifier); params.put(OidcConfiguration.CODE_CHALLENGE, CodeChallenge.compute(pkceMethod, verifier).getValue()); params.put(OidcConfiguration.CODE_CHALLENGE_METHOD, pkceMethod.getValue()); }
882
346
1,228
<no_super_class>
pac4j_pac4j
pac4j/pac4j-saml/src/main/java/org/pac4j/saml/context/SAML2ContextProvider.java
SAML2ContextProvider
addContext
class SAML2ContextProvider implements SAMLContextProvider { private static final String SAML2_WEBSSO_PROFILE_URI = "urn:oasis:names:tc:SAML:2.0:profiles:SSO:browser"; protected final SAML2MetadataResolver idpEntityId; protected final SAML2MetadataResolver spEntityId; protected final SAMLMessageStoreFactory samlMessageStoreFactory; /** {@inheritDoc} */ @Override public final SAML2MessageContext buildServiceProviderContext(final CallContext ctx, final SAML2Client client) { val context = new SAML2MessageContext(ctx); context.setSaml2Configuration(client.getConfiguration()); addTransportContext(ctx.webContext(), ctx.sessionStore(), context); addSPContext(context); return context; } /** {@inheritDoc} */ @Override public SAML2MessageContext buildContext(final CallContext ctx, final SAML2Client client) { val context = buildServiceProviderContext(ctx, client); addIDPContext(context); return context; } /** * <p>addTransportContext.</p> * * @param webContext a {@link WebContext} object * @param sessionStore a {@link SessionStore} object * @param context a {@link SAML2MessageContext} object */ protected final void addTransportContext(final WebContext webContext, final SessionStore sessionStore, final SAML2MessageContext context) { val profile = context.getProfileRequestContext(); profile.setOutboundMessageContext(prepareOutboundMessageContext(webContext)); context.getSAMLProtocolContext().setProtocol(SAMLConstants.SAML20P_NS); val request = context.getProfileRequestContext(); request.setProfileId(SAML2_WEBSSO_PROFILE_URI); if (this.samlMessageStoreFactory != null) { LOGGER.debug("Creating message store by {}", this.samlMessageStoreFactory.getClass().getName()); context.setSamlMessageStore(this.samlMessageStoreFactory.getMessageStore(webContext, sessionStore)); } } /** * <p>prepareOutboundMessageContext.</p> * * @param webContext a {@link WebContext} object * @return a {@link MessageContext} object */ protected MessageContext prepareOutboundMessageContext(final WebContext webContext) { final Pac4jSAMLResponse outTransport = new DefaultPac4jSAMLResponse(webContext); val outCtx = new MessageContext(); outCtx.setMessage(outTransport); return outCtx; } /** * <p>addSPContext.</p> * * @param context a {@link SAML2MessageContext} object */ protected final void addSPContext(final SAML2MessageContext context) { val selfContext = context.getSAMLSelfEntityContext(); selfContext.setEntityId(this.spEntityId.getEntityId()); selfContext.setRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME); addContext(this.spEntityId, selfContext, SPSSODescriptor.DEFAULT_ELEMENT_NAME); } /** * <p>addIDPContext.</p> * * @param context a {@link SAML2MessageContext} object */ protected final void addIDPContext(final SAML2MessageContext context) { val peerContext = context.getSAMLPeerEntityContext(); peerContext.setEntityId(this.idpEntityId.getEntityId()); peerContext.setRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME); addContext(this.idpEntityId, peerContext, IDPSSODescriptor.DEFAULT_ELEMENT_NAME); } /** * <p>addContext.</p> * * @param metadata a {@link SAML2MetadataResolver} object * @param parentContext a {@link BaseContext} object * @param elementName a {@link QName} object */ protected final void addContext(final SAML2MetadataResolver metadata, final BaseContext parentContext, final QName elementName) {<FILL_FUNCTION_BODY>} }
final EntityDescriptor entityDescriptor; final RoleDescriptor roleDescriptor; try { val set = new CriteriaSet(); val entityId = metadata.getEntityId(); set.add(new EntityIdCriterion(entityId)); entityDescriptor = SAML2Utils.buildChainingMetadataResolver(this.idpEntityId, this.spEntityId).resolveSingle(set); if (entityDescriptor == null) { throw new SAMLException("Cannot find entity " + entityId + " in metadata provider"); } val list = entityDescriptor.getRoleDescriptors(elementName, SAMLConstants.SAML20P_NS); roleDescriptor = CommonHelper.isNotEmpty(list) ? list.get(0) : null; if (roleDescriptor == null) { throw new SAMLException("Cannot find entity " + entityId + " or role " + elementName + " in metadata provider"); } } catch (final ResolverException e) { throw new SAMLException("An error occurred while getting IDP descriptors", e); } val mdCtx = parentContext.getSubcontext(SAMLMetadataContext.class, true); mdCtx.setEntityDescriptor(entityDescriptor); mdCtx.setRoleDescriptor(roleDescriptor);
1,104
325
1,429
<no_super_class>
pac4j_pac4j
pac4j/pac4j-saml/src/main/java/org/pac4j/saml/credentials/SAML2AuthenticationCredentials.java
SAMLAttribute
from
class SAMLAttribute implements Serializable { @Serial private static final long serialVersionUID = 2532838901563948260L; private String friendlyName; private String name; private String nameFormat; private List<String> attributeValues = new ArrayList<>(); public static List<SAMLAttribute> from(final AttributeConverter samlAttributeConverter, final Iterable<Attribute> samlAttributes) {<FILL_FUNCTION_BODY>} }
List<SAMLAttribute> attributes = new ArrayList<>(); samlAttributes.forEach(attribute -> { val result = samlAttributeConverter.convert(attribute); if (result instanceof Collection) { attributes.addAll((Collection<? extends SAMLAttribute>) result); } else { attributes.add((SAMLAttribute) result); } }); return attributes;
130
107
237
<methods>public non-sealed void <init>() ,public boolean isForAuthentication() <variables>protected org.pac4j.core.logout.LogoutType logoutType,private static final long serialVersionUID,protected java.lang.String source,private org.pac4j.core.profile.UserProfile userProfile
pac4j_pac4j
pac4j/pac4j-saml/src/main/java/org/pac4j/saml/crypto/DefaultSignatureSigningParametersProvider.java
DefaultSignatureSigningParametersProvider
build
class DefaultSignatureSigningParametersProvider implements SignatureSigningParametersProvider { private final SAML2Configuration configuration; /** * <p>Constructor for DefaultSignatureSigningParametersProvider.</p> * * @param configuration a {@link SAML2Configuration} object */ public DefaultSignatureSigningParametersProvider(final SAML2Configuration configuration) { this.configuration = configuration; } /** {@inheritDoc} */ @Override public SignatureSigningParameters build(final SSODescriptor descriptor) {<FILL_FUNCTION_BODY>} /** * <p>getSignatureSigningConfiguration.</p> * * @return a {@link SignatureSigningConfiguration} object */ protected SignatureSigningConfiguration getSignatureSigningConfiguration() { val config = DefaultSecurityConfigurationBootstrap.buildDefaultSignatureSigningConfiguration(); if (this.configuration.getBlackListedSignatureSigningAlgorithms() != null) { config.setExcludedAlgorithms(this.configuration.getBlackListedSignatureSigningAlgorithms()); } if (this.configuration.getSignatureAlgorithms() != null){ config.setSignatureAlgorithms(this.configuration.getSignatureAlgorithms()); } if (this.configuration.getSignatureCanonicalizationAlgorithm() != null) { config.setSignatureCanonicalizationAlgorithm(this.configuration.getSignatureCanonicalizationAlgorithm()); } if (this.configuration.getSignatureReferenceDigestMethods() != null) { config.setSignatureReferenceDigestMethods(this.configuration.getSignatureReferenceDigestMethods()); } final List<Credential> creds = new ArrayList<>(); creds.add(configuration.getCredentialProvider().getCredential()); config.setSigningCredentials(creds); return config; } /** * <p>augmentSignatureSigningParameters.</p> * * @param params a {@link SignatureSigningParameters} object * @return a {@link SignatureSigningParameters} object */ protected SignatureSigningParameters augmentSignatureSigningParameters(final SignatureSigningParameters params) { return params; } }
try { val criteria = new CriteriaSet(); criteria.add(new SignatureSigningConfigurationCriterion( getSignatureSigningConfiguration())); criteria.add(new RoleDescriptorCriterion(descriptor)); Resolver<SignatureSigningParameters, CriteriaSet> resolver = new SAMLMetadataSignatureSigningParametersResolver(); val params = resolver.resolveSingle(criteria); augmentSignatureSigningParameters(params); if (params == null) { throw new SAMLException("Could not determine the signature parameters"); } LOGGER.info("Created signature signing parameters." + "\nSignature algorithm: {}" + "\nSignature canonicalization algorithm: {}" + "\nSignature reference digest methods: {}", params.getSignatureAlgorithm(), params.getSignatureCanonicalizationAlgorithm(), params.getSignatureReferenceDigestMethod()); return params; } catch (final Exception e) { throw new SAMLException(e); }
550
249
799
<no_super_class>
pac4j_pac4j
pac4j/pac4j-saml/src/main/java/org/pac4j/saml/crypto/ExplicitSignatureTrustEngineProvider.java
ExplicitSignatureTrustEngineProvider
build
class ExplicitSignatureTrustEngineProvider implements SAML2SignatureTrustEngineProvider { private final SAML2MetadataResolver idpMetadataResolver; private final SAML2MetadataResolver spMetadataResolver; /** * <p>Constructor for ExplicitSignatureTrustEngineProvider.</p> * * @param idpMetadataResolver a {@link SAML2MetadataResolver} object * @param spMetadataResolver a {@link SAML2MetadataResolver} object */ public ExplicitSignatureTrustEngineProvider(final SAML2MetadataResolver idpMetadataResolver, final SAML2MetadataResolver spMetadataResolver) { this.idpMetadataResolver = idpMetadataResolver; this.spMetadataResolver = spMetadataResolver; } /** {@inheritDoc} */ @Override public SignatureTrustEngine build() {<FILL_FUNCTION_BODY>} }
val metadataCredentialResolver = new MetadataCredentialResolver(); final MetadataResolver metadataResolver = SAML2Utils.buildChainingMetadataResolver(idpMetadataResolver, spMetadataResolver); val roleResolver = new PredicateRoleDescriptorResolver(metadataResolver); val keyResolver = DefaultSecurityConfigurationBootstrap.buildBasicInlineKeyInfoCredentialResolver(); metadataCredentialResolver.setKeyInfoCredentialResolver(keyResolver); metadataCredentialResolver.setRoleDescriptorResolver(roleResolver); try { metadataCredentialResolver.initialize(); roleResolver.initialize(); } catch (final ComponentInitializationException e) { throw new SAMLException(e); } return new ExplicitKeySignatureTrustEngine(metadataCredentialResolver, keyResolver);
224
193
417
<no_super_class>
pac4j_pac4j
pac4j/pac4j-saml/src/main/java/org/pac4j/saml/crypto/KeyStoreCredentialProvider.java
KeyStoreCredentialProvider
getPrivateKeyAlias
class KeyStoreCredentialProvider implements CredentialProvider { private static final String DEFAULT_KEYSTORE_TYPE = "JKS"; private final CredentialResolver credentialResolver; private final String privateKeyAlias; /** * <p>Constructor for KeyStoreCredentialProvider.</p> * * @param configuration a {@link SAML2Configuration} object */ public KeyStoreCredentialProvider(final SAML2Configuration configuration) { CommonHelper.assertNotBlank("keystorePassword", configuration.getKeystorePassword()); CommonHelper.assertNotBlank("privateKeyPassword", configuration.getPrivateKeyPassword()); try (var inputStream = configuration.getKeystoreGenerator().retrieve()) { val keyStoreType = configuration.getKeyStoreType() == null ? DEFAULT_KEYSTORE_TYPE : configuration.getKeyStoreType(); val keyStore = loadKeyStore(inputStream, configuration.getKeystorePassword(), keyStoreType); this.privateKeyAlias = getPrivateKeyAlias(keyStore, configuration.getKeyStoreAlias()); val passwords = new HashMap<String, String>(); passwords.put(this.privateKeyAlias, configuration.getPrivateKeyPassword()); this.credentialResolver = new KeyStoreCredentialResolver(keyStore, passwords); } catch (final Exception e) { throw new SAMLException("Error loading keystore", e); } } private static KeyStore loadKeyStore(final InputStream inputStream, final String storePasswd, final String keyStoreType) { try { LOGGER.debug("Loading keystore with type {}", keyStoreType); val ks = KeyStore.getInstance(keyStoreType); ks.load(inputStream, storePasswd == null ? null : storePasswd.toCharArray()); LOGGER.debug("Loaded keystore with type {} with size {}", keyStoreType, ks.size()); return ks; } catch (final Exception e) { throw new SAMLException("Error loading keystore", e); } } /** * <p>Getter for the field <code>privateKeyAlias</code>.</p> * * @param keyStore a {@link KeyStore} object * @param keyStoreAlias a {@link String} object * @return a {@link String} object */ protected static String getPrivateKeyAlias(final KeyStore keyStore, final String keyStoreAlias) {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override public KeyInfo getKeyInfo() { val serverCredential = getCredential(); return generateKeyInfoForCredential(serverCredential); } /** {@inheritDoc} */ @Override public final CredentialResolver getCredentialResolver() { return credentialResolver; } /** {@inheritDoc} */ @Override public KeyInfoCredentialResolver getKeyInfoCredentialResolver() { return DefaultSecurityConfigurationBootstrap.buildBasicInlineKeyInfoCredentialResolver(); } /** {@inheritDoc} */ @Override public final KeyInfoGenerator getKeyInfoGenerator() { val mgmr = DefaultSecurityConfigurationBootstrap.buildBasicKeyInfoGeneratorManager(); val credential = getCredential(); return mgmr.getDefaultManager().getFactory(credential).newInstance(); } /** {@inheritDoc} */ @Override public final Credential getCredential() { try { val cs = new CriteriaSet(); Criterion criteria = new EntityIdCriterion(this.privateKeyAlias); cs.add(criteria); return this.credentialResolver.resolveSingle(cs); } catch (final ResolverException e) { throw new SAMLException("Can't obtain SP private key", e); } } /** * <p>generateKeyInfoForCredential.</p> * * @param credential a {@link Credential} object * @return a {@link KeyInfo} object */ protected final KeyInfo generateKeyInfoForCredential(final Credential credential) { try { return getKeyInfoGenerator().generate(credential); } catch (final org.opensaml.security.SecurityException e) { throw new SAMLException("Unable to generate keyInfo from given credential", e); } } }
try { val aliases = keyStore.aliases(); while (aliases.hasMoreElements()) { val currentAlias = aliases.nextElement(); if (keyStoreAlias != null) { if (currentAlias.equalsIgnoreCase(keyStoreAlias)) { return currentAlias; } } else if (keyStore.entryInstanceOf(currentAlias, KeyStore.PrivateKeyEntry.class)) { return currentAlias; } } throw new SAMLException("Keystore has no private keys to match the requested key alias " + keyStoreAlias); } catch (final KeyStoreException e) { throw new SAMLException("Unable to get aliases from keyStore", e); }
1,116
190
1,306
<no_super_class>
pac4j_pac4j
pac4j/pac4j-saml/src/main/java/org/pac4j/saml/crypto/KeyStoreDecryptionProvider.java
KeyStoreDecryptionProvider
build
class KeyStoreDecryptionProvider implements DecryptionProvider { private static final ChainingEncryptedKeyResolver encryptedKeyResolver; private final CredentialProvider credentialProvider; static { final List<EncryptedKeyResolver> list = new ArrayList<>(); list.add(new InlineEncryptedKeyResolver()); list.add(new EncryptedElementTypeEncryptedKeyResolver()); list.add(new SimpleRetrievalMethodEncryptedKeyResolver()); encryptedKeyResolver = new ChainingEncryptedKeyResolver(list); } /** * <p>Constructor for KeyStoreDecryptionProvider.</p> * * @param credentialProvider a {@link CredentialProvider} object */ public KeyStoreDecryptionProvider(final CredentialProvider credentialProvider) { this.credentialProvider = credentialProvider; } /** {@inheritDoc} */ @Override public final Decrypter build() {<FILL_FUNCTION_BODY>} }
val encryptionCredential = this.credentialProvider.getCredential(); final KeyInfoCredentialResolver resolver = new StaticKeyInfoCredentialResolver(encryptionCredential); val decrypter = new Decrypter(null, resolver, encryptedKeyResolver); decrypter.setRootInNewDocument(true); return decrypter;
244
92
336
<no_super_class>
pac4j_pac4j
pac4j/pac4j-saml/src/main/java/org/pac4j/saml/crypto/LogOnlySignatureTrustEngineProvider.java
LogOnlySignatureTrustEngine
validate
class LogOnlySignatureTrustEngine implements TrustedCredentialTrustEngine<Signature>, SignatureTrustEngine { private final SignatureTrustEngine wrapped; public LogOnlySignatureTrustEngine(final SignatureTrustEngine wrapped) { LOGGER.error("SIGNATURE VALIDATION DISABLED, DO NOT USE THIS ON PRODUCTION"); this.wrapped = wrapped; } @Override public CredentialResolver getCredentialResolver() { return ((TrustedCredentialTrustEngine<?>) wrapped).getCredentialResolver(); } @Override public KeyInfoCredentialResolver getKeyInfoResolver() { return wrapped.getKeyInfoResolver(); } @Override public boolean validate(final Signature token, final CriteriaSet trustBasisCriteria) throws SecurityException { try { if (!wrapped.validate(token, trustBasisCriteria)) { LOGGER.error("Signature validation failed, continuing anyway. Criteria: " + trustBasisCriteria); } } catch (final SecurityException e) { LOGGER.error("Signature validation failed, continuing anyway. Criteria: " + trustBasisCriteria + ", cause: " + e.getMessage(), e); } return true; } @Override public boolean validate(final byte[] signature, final byte[] content, final String algorithmURI, final CriteriaSet trustBasisCriteria, final Credential candidateCredential) throws SecurityException {<FILL_FUNCTION_BODY>} }
try { if (!wrapped.validate(signature, content, algorithmURI, trustBasisCriteria, candidateCredential)) { LOGGER.error("Signature validation failed, continuing anyway. Criteria: " + trustBasisCriteria); } } catch (final SecurityException e) { LOGGER.error("Signature validation failed, continuing anyway. Criteria: " + trustBasisCriteria + ", cause: " + e.getMessage(), e); } return true;
378
119
497
<no_super_class>
pac4j_pac4j
pac4j/pac4j-saml/src/main/java/org/pac4j/saml/logout/SAML2LogoutActionBuilder.java
SAML2LogoutActionBuilder
getLogoutAction
class SAML2LogoutActionBuilder implements LogoutActionBuilder { protected SAML2LogoutRequestBuilder saml2LogoutRequestBuilder; protected final SAML2LogoutRequestMessageSender saml2LogoutRequestMessageSender; protected final SAMLContextProvider contextProvider; protected final SAML2Configuration configuration; protected final ValueGenerator stateGenerator; protected final SAML2Client saml2Client; /** * <p>Constructor for SAML2LogoutActionBuilder.</p> * * @param client a {@link SAML2Client} object */ public SAML2LogoutActionBuilder(final SAML2Client client) { this.saml2Client = client; this.saml2LogoutRequestMessageSender = client.getLogoutRequestMessageSender(); this.contextProvider = client.getContextProvider(); this.configuration = client.getConfiguration(); this.stateGenerator = client.getStateGenerator(); this.saml2LogoutRequestBuilder = new SAML2LogoutRequestBuilder(configuration); } /** {@inheritDoc} */ @Override public Optional<RedirectionAction> getLogoutAction(final CallContext ctx, final UserProfile currentProfile, final String targetUrl) {<FILL_FUNCTION_BODY>} }
try { if (currentProfile instanceof SAML2Profile saml2Profile) { val samlContext = this.contextProvider.buildContext(ctx, this.saml2Client); val relayState = this.stateGenerator.generateValue(ctx); val logoutRequest = this.saml2LogoutRequestBuilder.build(samlContext, saml2Profile); saml2LogoutRequestMessageSender.sendMessage(samlContext, logoutRequest, relayState); val webContext = ctx.webContext(); val adapter = samlContext.getProfileRequestContextOutboundMessageTransportResponse(); if (this.configuration.getSpLogoutRequestBindingType().equalsIgnoreCase(SAMLConstants.SAML2_POST_BINDING_URI)) { val content = adapter.getOutgoingContent(); return Optional.of(HttpActionHelper.buildFormPostContentAction(webContext, content)); } val location = adapter.getRedirectUrl(); return Optional.of(HttpActionHelper.buildRedirectUrlAction(webContext, location)); } } catch (final Exception e) { if (LOGGER.isDebugEnabled()) { LOGGER.debug(e.getMessage(), e); } else { LOGGER.warn(e.getMessage()); } } return Optional.empty();
336
329
665
<no_super_class>
pac4j_pac4j
pac4j/pac4j-saml/src/main/java/org/pac4j/saml/logout/impl/SAML2LogoutRequestBuilder.java
SAML2LogoutRequestBuilder
buildLogoutRequest
class SAML2LogoutRequestBuilder { private final XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory(); private String bindingType; private boolean useNameQualifier; private int issueInstantSkewSeconds = 0; /** * Instantiates a new Saml 2 logout request builder. * * @param cfg a {@link SAML2Configuration} object */ public SAML2LogoutRequestBuilder(final SAML2Configuration cfg) { this.bindingType = cfg.getSpLogoutRequestBindingType(); this.useNameQualifier = cfg.isUseNameQualifier(); } /** * <p>build.</p> * * @param context a {@link SAML2MessageContext} object * @param profile a {@link SAML2Profile} object * @return a {@link LogoutRequest} object */ public LogoutRequest build(final SAML2MessageContext context, final SAML2Profile profile) { val ssoService = context.getIDPSingleLogoutService(this.bindingType); return buildLogoutRequest(context, ssoService, profile); } /** * <p>buildLogoutRequest.</p> * * @param context a {@link SAML2MessageContext} object * @param ssoService a {@link org.opensaml.saml.saml2.metadata.SingleLogoutService} object * @param profile a {@link SAML2Profile} object * @return a {@link LogoutRequest} object */ @SuppressWarnings("unchecked") protected final LogoutRequest buildLogoutRequest(final SAML2MessageContext context, final Endpoint ssoService, final SAML2Profile profile) {<FILL_FUNCTION_BODY>} /** * <p>getIssuer.</p> * * @param spEntityId a {@link String} object * @return a {@link Issuer} object */ @SuppressWarnings("unchecked") protected final Issuer getIssuer(final String spEntityId) { val issuerBuilder = (SAMLObjectBuilder<Issuer>) this.builderFactory .getBuilder(Issuer.DEFAULT_ELEMENT_NAME); val issuer = issuerBuilder.buildObject(); issuer.setValue(spEntityId); return issuer; } /** * <p>Setter for the field <code>issueInstantSkewSeconds</code>.</p> * * @param issueInstantSkewSeconds a int */ public void setIssueInstantSkewSeconds(final int issueInstantSkewSeconds) { this.issueInstantSkewSeconds = issueInstantSkewSeconds; } }
val builder = (SAMLObjectBuilder<LogoutRequest>) this.builderFactory .getBuilder(LogoutRequest.DEFAULT_ELEMENT_NAME); val request = builder.buildObject(); val selfContext = context.getSAMLSelfEntityContext(); request.setID(SAML2Utils.generateID()); request.setIssuer(getIssuer(selfContext.getEntityId())); request.setIssueInstant(ZonedDateTime.now(ZoneOffset.UTC).plusSeconds(this.issueInstantSkewSeconds).toInstant()); request.setVersion(SAMLVersion.VERSION_20); request.setDestination(ssoService.getLocation()); // name id added (id of profile) val nameIdBuilder = (SAMLObjectBuilder<NameID>) this.builderFactory .getBuilder(NameID.DEFAULT_ELEMENT_NAME); val nameId = nameIdBuilder.buildObject(); nameId.setValue(profile.getId()); nameId.setFormat(profile.getSamlNameIdFormat()); if (this.useNameQualifier) { nameId.setNameQualifier(profile.getSamlNameIdNameQualifier()); nameId.setSPNameQualifier(profile.getSamlNameIdSpNameQualifier()); nameId.setSPProvidedID(profile.getSamlNameIdSpProviderId()); } request.setNameID(nameId); // session index added val sessIdx = profile.getSessionIndex(); if (sessIdx != null) { val sessionIndexBuilder = (SAMLObjectBuilder<SessionIndex>) this.builderFactory .getBuilder(SessionIndex.DEFAULT_ELEMENT_NAME); val sessionIdx = sessionIndexBuilder.buildObject(); sessionIdx.setValue(sessIdx); request.getSessionIndexes().add(sessionIdx); } return request;
737
489
1,226
<no_super_class>
pac4j_pac4j
pac4j/pac4j-saml/src/main/java/org/pac4j/saml/logout/impl/SAML2LogoutResponseBuilder.java
SAML2LogoutResponseBuilder
buildLogoutResponse
class SAML2LogoutResponseBuilder { private String bindingType; private int issueInstantSkewSeconds = 0; private final XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory(); /** * <p>Constructor for SAML2LogoutResponseBuilder.</p> * * @param bindingType a {@link String} object */ public SAML2LogoutResponseBuilder(final String bindingType) { this.bindingType = bindingType; } /** * <p>build.</p> * * @param context a {@link SAML2MessageContext} object * @return a {@link LogoutResponse} object */ public LogoutResponse build(final SAML2MessageContext context) { val ssoService = context.getIDPSingleLogoutService(this.bindingType); return buildLogoutResponse(context, ssoService); } /** * <p>buildLogoutResponse.</p> * * @param context a {@link SAML2MessageContext} object * @param ssoService a {@link org.opensaml.saml.saml2.metadata.SingleLogoutService} object * @return a {@link LogoutResponse} object */ @SuppressWarnings("unchecked") protected final LogoutResponse buildLogoutResponse(final SAML2MessageContext context, final Endpoint ssoService) {<FILL_FUNCTION_BODY>} /** * <p>getSuccess.</p> * * @return a {@link Status} object */ protected Status getSuccess() { val statusBuilder = (SAMLObjectBuilder<Status>) this.builderFactory .getBuilder(Status.DEFAULT_ELEMENT_NAME); val status = statusBuilder.buildObject(); val statusCode = new StatusCodeBuilder().buildObject(); statusCode.setValue(StatusCode.SUCCESS); status.setStatusCode(statusCode); return status; } /** * <p>getIssuer.</p> * * @param spEntityId a {@link String} object * @return a {@link Issuer} object */ @SuppressWarnings("unchecked") protected final Issuer getIssuer(final String spEntityId) { val issuerBuilder = (SAMLObjectBuilder<Issuer>) this.builderFactory .getBuilder(Issuer.DEFAULT_ELEMENT_NAME); val issuer = issuerBuilder.buildObject(); issuer.setValue(spEntityId); return issuer; } /** * <p>Setter for the field <code>bindingType</code>.</p> * * @param bindingType a {@link String} object */ public void setBindingType(final String bindingType) { this.bindingType = bindingType; } /** * <p>Setter for the field <code>issueInstantSkewSeconds</code>.</p> * * @param issueInstantSkewSeconds a int */ public void setIssueInstantSkewSeconds(final int issueInstantSkewSeconds) { this.issueInstantSkewSeconds = issueInstantSkewSeconds; } }
val builder = (SAMLObjectBuilder<LogoutResponse>) this.builderFactory .getBuilder(LogoutResponse.DEFAULT_ELEMENT_NAME); val response = builder.buildObject(); val selfContext = context.getSAMLSelfEntityContext(); response.setID(SAML2Utils.generateID()); response.setIssuer(getIssuer(selfContext.getEntityId())); response.setIssueInstant(ZonedDateTime.now(ZoneOffset.UTC).plusSeconds(this.issueInstantSkewSeconds).toInstant()); response.setVersion(SAMLVersion.VERSION_20); response.setDestination(ssoService.getLocation()); response.setStatus(getSuccess()); val originalMessage = (SAMLObject) context.getMessageContext().getMessage(); if (originalMessage instanceof RequestAbstractTypeImpl) { response.setInResponseTo(((RequestAbstractTypeImpl) originalMessage).getID()); } return response;
852
250
1,102
<no_super_class>
pac4j_pac4j
pac4j/pac4j-saml/src/main/java/org/pac4j/saml/logout/impl/SAML2LogoutValidator.java
SAML2LogoutValidator
validateSuccess
class SAML2LogoutValidator extends AbstractSAML2ResponseValidator { /** * Logouts are only successful if the IdP was able to inform all services, otherwise it will * respond with PartialLogout. This setting allows clients to ignore such server-side problems. */ private boolean isPartialLogoutTreatedAsSuccess = false; /** * Expected destination endpoint when validating saml2 logout responses. * If left blank, will use the SLO endpoint from metadata context. */ private String expectedDestination; /** * <p>Constructor for SAML2LogoutValidator.</p> * * @param engine a {@link SAML2SignatureTrustEngineProvider} object * @param decrypter a {@link Decrypter} object * @param logoutHandler a {@link SessionLogoutHandler} object * @param replayCache a {@link ReplayCacheProvider} object * @param uriComparator a {@link URIComparator} object */ public SAML2LogoutValidator(final SAML2SignatureTrustEngineProvider engine, final Decrypter decrypter, final SessionLogoutHandler logoutHandler, final ReplayCacheProvider replayCache, final URIComparator uriComparator) { super(engine, decrypter, logoutHandler, replayCache, uriComparator); } /** * {@inheritDoc} * * Validates the SAML protocol logout request/response. */ @Override public Credentials validate(final SAML2MessageContext context) { val message = (SAMLObject) context.getMessageContext().getMessage(); // IDP-initiated if (message instanceof LogoutRequest logoutRequest) { val engine = this.signatureTrustEngineProvider.build(); validateLogoutRequest(logoutRequest, context, engine); return new SAML2Credentials(LogoutType.UNDEFINED, context); // SP-initiated } else if (message instanceof LogoutResponse logoutResponse) { val engine = this.signatureTrustEngineProvider.build(); validateLogoutResponse(logoutResponse, context, engine); return new SAML2Credentials(LogoutType.UNDEFINED, context); } throw new SAMLException("SAML message must be a LogoutRequest or LogoutResponse type"); } /** * Validates the SAML logout request. * * @param logoutRequest the logout request * @param context the context * @param engine the signature engine */ protected void validateLogoutRequest(final LogoutRequest logoutRequest, final SAML2MessageContext context, final SignatureTrustEngine engine) { logger.trace("Validating logout request:\n{}", Configuration.serializeSamlObject(logoutRequest)); validateSignatureIfItExists(logoutRequest.getSignature(), context, engine); // don't check because of CAS v5 //validateIssueInstant(logoutRequest.getIssueInstant()); validateIssuerIfItExists(logoutRequest.getIssuer(), context); var nameId = logoutRequest.getNameID(); val encryptedID = logoutRequest.getEncryptedID(); if (encryptedID != null) { nameId = decryptEncryptedId(encryptedID, decrypter); } val samlNameId = SAML2AuthenticationCredentials.SAMLNameID.from(nameId); String sessionIndex = null; val sessionIndexes = logoutRequest.getSessionIndexes(); if (sessionIndexes != null && !sessionIndexes.isEmpty()) { val sessionIndexObject = sessionIndexes.get(0); if (sessionIndexObject != null) { sessionIndex = sessionIndexObject.getValue(); } } val sloKey = computeSloKey(sessionIndex, samlNameId); if (sloKey != null && logoutHandler != null) { logoutHandler.destroySession(context.getCallContext(), sloKey); } } /** * Validates the SAML logout response. * * @param logoutResponse the logout response * @param context the context * @param engine the signature engine */ protected void validateLogoutResponse(final LogoutResponse logoutResponse, final SAML2MessageContext context, final SignatureTrustEngine engine) { logger.trace("Validating logout response:\n{}", Configuration.serializeSamlObject(logoutResponse)); validateSuccess(logoutResponse.getStatus()); validateSignatureIfItExists(logoutResponse.getSignature(), context, engine); validateIssueInstant(logoutResponse.getIssueInstant()); validateIssuerIfItExists(logoutResponse.getIssuer(), context); validateDestinationEndpoint(logoutResponse, context); } /** * <p>validateDestinationEndpoint.</p> * * @param logoutResponse a {@link LogoutResponse} object * @param context a {@link SAML2MessageContext} object */ protected void validateDestinationEndpoint(final StatusResponseType logoutResponse, final SAML2MessageContext context) { List<String> expected = new ArrayList<>(); if (CommonHelper.isBlank(this.expectedDestination)) { val endpoint = Objects.requireNonNull(context.getSPSSODescriptor().getSingleLogoutServices().get(0)); if (endpoint.getLocation() != null) { expected.add(endpoint.getLocation()); } if (endpoint.getResponseLocation() != null) { expected.add(endpoint.getResponseLocation()); } } else { expected.add(this.expectedDestination); } val isDestinationMandatory = context.getSaml2Configuration().isResponseDestinationAttributeMandatory(); verifyEndpoint(expected, logoutResponse.getDestination(), isDestinationMandatory); } /** {@inheritDoc} */ @Override protected void validateSuccess(Status status) {<FILL_FUNCTION_BODY>} }
if (isPartialLogoutTreatedAsSuccess && status != null && status.getStatusCode() != null) { if (StatusCode.PARTIAL_LOGOUT.equals(status.getStatusCode().getValue())) { logger.debug( "Response status code is {} and partial logouts are configured to be treated as success => validation successful!", StatusCode.PARTIAL_LOGOUT); return; } logger.debug("Response status code: {}", status.getStatusCode().getValue()); if (StatusCode.RESPONDER.equals(status.getStatusCode().getValue()) && status.getStatusCode().getOrderedChildren().stream().filter(StatusCode.class::isInstance).map(StatusCode.class::cast) .anyMatch(code -> StatusCode.PARTIAL_LOGOUT.equals(code.getValue()))) { logger.debug( "Response sub-status code is {} and partial logouts are configured to be treated as success => validation successful!", StatusCode.PARTIAL_LOGOUT); return; } } super.validateSuccess(status);
1,567
280
1,847
<methods>public final void setAcceptedSkew(long) <variables>protected long acceptedSkew,protected final non-sealed org.opensaml.saml.saml2.encryption.Decrypter decrypter,protected final org.slf4j.Logger logger,protected final non-sealed org.pac4j.core.logout.handler.SessionLogoutHandler logoutHandler,protected final non-sealed org.pac4j.saml.replay.ReplayCacheProvider replayCache,protected final non-sealed org.pac4j.saml.crypto.SAML2SignatureTrustEngineProvider signatureTrustEngineProvider,protected final non-sealed net.shibboleth.shared.net.URIComparator uriComparator
pac4j_pac4j
pac4j/pac4j-saml/src/main/java/org/pac4j/saml/logout/processor/SAML2LogoutProcessor.java
SAML2LogoutProcessor
processLogout
class SAML2LogoutProcessor implements LogoutProcessor { private final SAMLContextProvider contextProvider; private final SAML2Client saml2Client; private final String spLogoutResponseBindingType; private final SAML2LogoutResponseBuilder saml2LogoutResponseBuilder; private final SAML2LogoutResponseMessageSender saml2LogoutResponseMessageSender; @Setter @Getter private String postLogoutURL; /** * When set to false, will cause the validator * to not throw back exceptions and expect adaptations of those exceptions * when the response is successfully validated. Instead, the validator should successfully * move on without throwing {@link OkAction}. */ @Getter @Setter private boolean actionOnSuccess = true; /** * <p>Constructor for SAML2LogoutProcessor.</p> * * @param client a {@link SAML2Client} object */ public SAML2LogoutProcessor(final SAML2Client client) { this.contextProvider = client.getContextProvider(); this.saml2Client = client; this.spLogoutResponseBindingType = client.getConfiguration().getSpLogoutResponseBindingType(); this.saml2LogoutResponseBuilder = new SAML2LogoutResponseBuilder(spLogoutResponseBindingType); this.saml2LogoutResponseMessageSender = new SAML2LogoutResponseMessageSender(client.getSignatureSigningParametersProvider(), spLogoutResponseBindingType, false, client.getConfiguration().isSpLogoutRequestSigned()); this.postLogoutURL = client.getConfiguration().getPostLogoutURL(); } /** {@inheritDoc} */ @Override public HttpAction processLogout(final CallContext ctx, final Credentials credentials) {<FILL_FUNCTION_BODY>} /** * <p>sendLogoutResponse.</p> * * @param samlContext a {@link SAML2MessageContext} object * @param saml2Credentials a {@link SAML2Credentials} object */ protected void sendLogoutResponse(final SAML2MessageContext samlContext, final SAML2Credentials saml2Credentials) { samlContext.getSAMLBindingContext().setRelayState(saml2Credentials.getContext().getSAMLBindingContext().getRelayState()); val logoutResponse = this.saml2LogoutResponseBuilder.build(samlContext); this.saml2LogoutResponseMessageSender.sendMessage(samlContext, logoutResponse, samlContext.getSAMLBindingContext().getRelayState()); } /** * <p>adaptLogoutResponseToBinding.</p> * * @param context a {@link WebContext} object * @param samlContext a {@link SAML2MessageContext} object * @return a {@link HttpAction} object */ protected HttpAction adaptLogoutResponseToBinding(final WebContext context, final SAML2MessageContext samlContext) { val adapter = samlContext.getProfileRequestContextOutboundMessageTransportResponse(); if (spLogoutResponseBindingType.equalsIgnoreCase(SAMLConstants.SAML2_POST_BINDING_URI)) { val content = adapter.getOutgoingContent(); return HttpActionHelper.buildFormPostContentAction(context, content); } else { val location = adapter.getRedirectUrl(); return HttpActionHelper.buildRedirectUrlAction(context, location); } } /** * <p>handlePostLogoutResponse.</p> * * @param context a {@link SAML2MessageContext} object * @return a {@link HttpAction} object */ protected HttpAction handlePostLogoutResponse(final SAML2MessageContext context) { if (CommonHelper.isNotBlank(postLogoutURL)) { // if custom post logout URL is present then redirect to it return new FoundAction(postLogoutURL); } // nothing to reply to the logout response return this.actionOnSuccess ? new OkAction(Pac4jConstants.EMPTY_STRING) : null; } }
val saml2Credentials = (SAML2Credentials) credentials; val message = (SAMLObject) saml2Credentials.getContext().getMessageContext().getMessage(); val samlContext = this.contextProvider.buildContext(ctx, this.saml2Client); // IDP-initiated if (message instanceof LogoutRequest) { sendLogoutResponse(samlContext, saml2Credentials); return adaptLogoutResponseToBinding(ctx.webContext(), samlContext); // SP-initiated } else if (message instanceof LogoutResponse) { val action = handlePostLogoutResponse(samlContext); if (action != null) { return action; } return NoContentAction.INSTANCE; } throw new SAMLException("SAML message must be a LogoutRequest or LogoutResponse type");
1,074
220
1,294
<no_super_class>
pac4j_pac4j
pac4j/pac4j-saml/src/main/java/org/pac4j/saml/metadata/DefaultSAML2MetadataSigner.java
DefaultSAML2MetadataSigner
sign
class DefaultSAML2MetadataSigner implements SAML2MetadataSigner { protected final CredentialProvider credentialProvider; protected final String signatureAlgorithm; protected final String signatureReferenceDigestMethod; protected final SAML2Configuration configuration; /** * <p>Constructor for DefaultSAML2MetadataSigner.</p> * * @param configuration a {@link SAML2Configuration} object */ public DefaultSAML2MetadataSigner(final SAML2Configuration configuration) { this.configuration = configuration; this.credentialProvider = null; this.signatureAlgorithm = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"; this.signatureReferenceDigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256"; } /** * <p>Constructor for DefaultSAML2MetadataSigner.</p> * * @param credentialProvider a {@link CredentialProvider} object * @param signatureAlgorithm a {@link String} object * @param signatureReferenceDigestMethod a {@link String} object */ public DefaultSAML2MetadataSigner(final CredentialProvider credentialProvider, final String signatureAlgorithm, final String signatureReferenceDigestMethod) { this.configuration = null; this.credentialProvider = credentialProvider; this.signatureAlgorithm = signatureAlgorithm; this.signatureReferenceDigestMethod = signatureReferenceDigestMethod; } private byte[] sign(final byte[] metadata) throws Exception { try (val is = new ByteArrayInputStream(metadata)) { val document = Configuration.getParserPool().parse(is); val documentElement = document.getDocumentElement(); val unmarshaller = Configuration.getUnmarshallerFactory().getUnmarshaller(documentElement); val xmlObject = Objects.requireNonNull(unmarshaller).unmarshall(documentElement); if (xmlObject instanceof SignableXMLObject root && !root.isSigned()) { sign(root); try (var writer = Configuration.serializeSamlObject(root)) { return writer.toString().getBytes(StandardCharsets.UTF_8); } } return metadata; } } /** {@inheritDoc} */ @Override public String sign(final String metadata) { try { var input = metadata.getBytes(StandardCharsets.UTF_8); var result = sign(input); return new String(result, StandardCharsets.UTF_8); } catch (final Exception e) { throw new SAMLException(e.getMessage(), e); } } /** {@inheritDoc} */ @Override public void sign(final File metadataFile) {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override public void sign(final SignableXMLObject descriptor) { try { val signingParameters = new SignatureSigningParameters(); val activeProvider = Objects.requireNonNull(Optional.ofNullable(configuration) .map(SAML2Configuration::getCredentialProvider) .orElse(this.credentialProvider)); signingParameters.setKeyInfoGenerator(activeProvider.getKeyInfoGenerator()); signingParameters.setSigningCredential(activeProvider.getCredential()); val signingAlgorithm = Optional.ofNullable(configuration) .map(SAML2Configuration::getSignatureAlgorithms) .filter(algorithms -> !algorithms.isEmpty()) .map(algorithms -> algorithms.get(0)) .orElse(this.signatureAlgorithm); signingParameters.setSignatureAlgorithm(signingAlgorithm); val signingReference = Optional.ofNullable(configuration) .map(SAML2Configuration::getSignatureReferenceDigestMethods) .filter(algorithms -> !algorithms.isEmpty()) .map(algorithms -> algorithms.get(0)) .orElse(this.signatureReferenceDigestMethod); signingParameters.setSignatureReferenceDigestMethod(signingReference); signingParameters.setSignatureCanonicalizationAlgorithm( SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS); SignatureSupport.signObject(descriptor, signingParameters); } catch (final Exception e) { throw new SAMLException(e.getMessage(), e); } } }
try { var input = Files.readAllBytes(metadataFile.toPath()); var result = sign(input); Files.writeString(metadataFile.toPath(), new String(result, StandardCharsets.UTF_8)); } catch (final Exception e) { throw new SAMLException(e.getMessage(), e); }
1,127
87
1,214
<no_super_class>
pac4j_pac4j
pac4j/pac4j-saml/src/main/java/org/pac4j/saml/metadata/SAML2FileSystemMetadataGenerator.java
SAML2FileSystemMetadataGenerator
storeMetadata
class SAML2FileSystemMetadataGenerator extends BaseSAML2MetadataGenerator { private final Resource metadataResource; /** {@inheritDoc} */ @Override protected AbstractMetadataResolver createMetadataResolver() throws Exception { if (metadataResource != null) { return new FilesystemMetadataResolver(metadataResource.getFile()); } return null; } /** {@inheritDoc} */ @Override public boolean storeMetadata(final String metadata, final boolean force) throws Exception {<FILL_FUNCTION_BODY>} }
if (metadataResource == null || CommonHelper.isBlank(metadata)) { logger.info("No metadata or resource is provided"); return false; } if (!(metadataResource instanceof WritableResource)) { logger.warn("Unable to store metadata, as resource is not writable"); return false; } if (metadataResource.exists() && !force) { logger.info("Metadata file already exists at {}.", metadataResource.getFile()); } else { logger.info("Writing metadata to {}", metadataResource.getFilename()); val parent = metadataResource.getFile().getParentFile(); if (parent != null) { logger.debug("Attempting to create directory structure for: {}", parent.getCanonicalPath()); if (!parent.exists() && !parent.mkdirs()) { logger.warn("Could not construct the directory structure for metadata: {}", parent.getCanonicalPath()); } } val transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); val result = new StreamResult(new StringWriter()); Source source = new StreamSource(new StringReader(metadata)); transformer.transform(source, result); val destination = WritableResource.class.cast(metadataResource); try (var spMetadataOutputStream = destination.getOutputStream()) { spMetadataOutputStream.write(result.getWriter().toString().getBytes(StandardCharsets.UTF_8)); } if (destination.exists()) { if (isSignMetadata()) { getMetadataSigner().sign(metadataResource.getFile()); } return true; } } return false;
136
452
588
<methods>public non-sealed void <init>() ,public org.opensaml.saml.saml2.metadata.EntityDescriptor buildEntityDescriptor() ,public org.opensaml.saml.metadata.resolver.MetadataResolver buildMetadataResolver() throws java.lang.Exception,public List<java.lang.String> getBlackListedSignatureSigningAlgorithms() ,public java.lang.String getMetadata(org.opensaml.saml.saml2.metadata.EntityDescriptor) throws java.lang.Exception,public List<java.lang.String> getSignatureAlgorithms() ,public List<java.lang.String> getSignatureReferenceDigestMethods() <variables>protected java.lang.String assertionConsumerServiceUrl,protected boolean authnRequestSigned,protected List<java.lang.String> blackListedSignatureSigningAlgorithms,protected final org.opensaml.core.xml.XMLObjectBuilderFactory builderFactory,private List<org.pac4j.saml.metadata.SAML2MetadataContactPerson> contactPersons,protected org.pac4j.saml.crypto.CredentialProvider credentialProvider,protected int defaultACSIndex,protected org.opensaml.xmlsec.SignatureSigningConfiguration defaultSignatureSigningConfiguration,protected java.lang.String entityId,protected final org.opensaml.xmlsec.algorithm.AlgorithmRegistry globalAlgorithmRegistry,protected final org.slf4j.Logger logger,protected final org.opensaml.core.xml.io.MarshallerFactory marshallerFactory,private org.pac4j.saml.metadata.SAML2MetadataSigner metadataSigner,private List<org.pac4j.saml.metadata.SAML2MetadataUIInfo> metadataUIInfos,protected java.lang.String nameIdPolicyFormat,protected java.lang.String requestInitiatorLocation,protected List<org.pac4j.saml.metadata.SAML2ServiceProviderRequestedAttribute> requestedAttributes,protected java.lang.String responseBindingType,protected boolean signMetadata,protected List<java.lang.String> signatureAlgorithms,protected List<java.lang.String> signatureReferenceDigestMethods,protected java.lang.String singleLogoutServiceUrl,private List<java.lang.String> supportedProtocols,protected boolean wantAssertionSigned
pac4j_pac4j
pac4j/pac4j-saml/src/main/java/org/pac4j/saml/metadata/SAML2HttpUrlMetadataGenerator.java
SAML2HttpUrlMetadataGenerator
storeMetadata
class SAML2HttpUrlMetadataGenerator extends BaseSAML2MetadataGenerator { @Getter private final URL metadataUrl; private final HttpClient httpClient; @Getter private float refreshDelayFactor = -1; @Getter @Setter private Duration maxRefreshDelay; @Getter @Setter private Duration minRefreshDelay; /** {@inheritDoc} */ @Override protected AbstractMetadataResolver createMetadataResolver() throws Exception { val resolver = new HTTPMetadataResolver(httpClient, this.metadataUrl.toExternalForm()); if (minRefreshDelay != null) { resolver.setMinRefreshDelay(minRefreshDelay); } if (maxRefreshDelay != null) { resolver.setMaxRefreshDelay(maxRefreshDelay); } if (refreshDelayFactor >= 0) { resolver.setRefreshDelayFactor(refreshDelayFactor); } return resolver; } /** {@inheritDoc} */ @Override public boolean storeMetadata(final String metadata, final boolean force) throws Exception {<FILL_FUNCTION_BODY>} }
HttpResponse response = null; try { logger.debug("Posting metadata to {}", this.metadataUrl.toURI()); val httpPost = new HttpPost(this.metadataUrl.toURI()); httpPost.addHeader("Accept", ContentType.APPLICATION_XML.getMimeType()); httpPost.addHeader("Content-Type", ContentType.APPLICATION_XML.getMimeType()); httpPost.setEntity(new StringEntity(metadata, ContentType.APPLICATION_XML)); response = httpClient.execute(httpPost); if (response != null) { val code = response.getCode(); if (code == HttpStatus.SC_NOT_IMPLEMENTED) { logger.info("Storing metadata is not supported/implemented by {}", metadataUrl); return false; } if (code == HttpStatus.SC_OK || code == HttpStatus.SC_CREATED) { logger.info("Successfully submitted metadata to {}", metadataUrl); return true; } } logger.error("Unable to store metadata successfully via {}", metadataUrl.toExternalForm()); return false; } finally { if (response != null && response instanceof CloseableHttpResponse) { ((CloseableHttpResponse) response).close(); } }
301
327
628
<methods>public non-sealed void <init>() ,public org.opensaml.saml.saml2.metadata.EntityDescriptor buildEntityDescriptor() ,public org.opensaml.saml.metadata.resolver.MetadataResolver buildMetadataResolver() throws java.lang.Exception,public List<java.lang.String> getBlackListedSignatureSigningAlgorithms() ,public java.lang.String getMetadata(org.opensaml.saml.saml2.metadata.EntityDescriptor) throws java.lang.Exception,public List<java.lang.String> getSignatureAlgorithms() ,public List<java.lang.String> getSignatureReferenceDigestMethods() <variables>protected java.lang.String assertionConsumerServiceUrl,protected boolean authnRequestSigned,protected List<java.lang.String> blackListedSignatureSigningAlgorithms,protected final org.opensaml.core.xml.XMLObjectBuilderFactory builderFactory,private List<org.pac4j.saml.metadata.SAML2MetadataContactPerson> contactPersons,protected org.pac4j.saml.crypto.CredentialProvider credentialProvider,protected int defaultACSIndex,protected org.opensaml.xmlsec.SignatureSigningConfiguration defaultSignatureSigningConfiguration,protected java.lang.String entityId,protected final org.opensaml.xmlsec.algorithm.AlgorithmRegistry globalAlgorithmRegistry,protected final org.slf4j.Logger logger,protected final org.opensaml.core.xml.io.MarshallerFactory marshallerFactory,private org.pac4j.saml.metadata.SAML2MetadataSigner metadataSigner,private List<org.pac4j.saml.metadata.SAML2MetadataUIInfo> metadataUIInfos,protected java.lang.String nameIdPolicyFormat,protected java.lang.String requestInitiatorLocation,protected List<org.pac4j.saml.metadata.SAML2ServiceProviderRequestedAttribute> requestedAttributes,protected java.lang.String responseBindingType,protected boolean signMetadata,protected List<java.lang.String> signatureAlgorithms,protected List<java.lang.String> signatureReferenceDigestMethods,protected java.lang.String singleLogoutServiceUrl,private List<java.lang.String> supportedProtocols,protected boolean wantAssertionSigned
pac4j_pac4j
pac4j/pac4j-saml/src/main/java/org/pac4j/saml/metadata/SAML2IdentityProviderMetadataResolver.java
SAML2IdentityProviderMetadataResolver
getMetadata
class SAML2IdentityProviderMetadataResolver extends SpringResourceLoader<MetadataResolver> implements SAML2MetadataResolver { @Setter private Proxy proxy = Proxy.NO_PROXY; @Setter private HostnameVerifier hostnameVerifier; @Setter private SSLSocketFactory sslSocketFactory; private final SAML2Configuration configuration; /** * <p>Constructor for SAML2IdentityProviderMetadataResolver.</p> * * @param configuration a {@link SAML2Configuration} object */ public SAML2IdentityProviderMetadataResolver(final SAML2Configuration configuration) { super(configuration.getIdentityProviderMetadataResource()); if (configuration.getSslSocketFactory() != null) { setSslSocketFactory(configuration.getSslSocketFactory()); } if (configuration.getHostnameVerifier() != null) { setHostnameVerifier(configuration.getHostnameVerifier()); } this.configuration = configuration; } /** {@inheritDoc} */ @Override public final MetadataResolver resolve() { return load(); } /** * <p>internalLoad.</p> */ protected void internalLoad() { this.loaded = initializeMetadataResolver(); } /** * <p>initializeMetadataResolver.</p> * * @return a {@link DOMMetadataResolver} object */ protected DOMMetadataResolver initializeMetadataResolver() { try (var in = SpringResourceHelper.getResourceInputStream( configuration.getIdentityProviderMetadataResource(), proxy, sslSocketFactory, hostnameVerifier, configuration.getIdentityProviderMetadataConnectTimeout(), configuration.getIdentityProviderMetadataReadTimeout() )) { var parsedInput = Configuration.getParserPool().parse(in); var metadataRoot = parsedInput.getDocumentElement(); var resolver = new DOMMetadataResolver(metadataRoot); resolver.setIndexes(Collections.singleton(new RoleMetadataIndex())); resolver.setParserPool(Configuration.getParserPool()); resolver.setFailFastInitialization(true); resolver.setRequireValidMetadata(true); resolver.setId(resolver.getClass().getCanonicalName()); resolver.initialize(); return resolver; } catch (final FileNotFoundException e) { throw new TechnicalException("Error loading idp metadata", e); } catch (final ComponentInitializationException e) { throw new TechnicalException("Error initializing idp metadata resolver", e); } catch (final XMLParserException e) { throw new TechnicalException("Error parsing idp metadata", e); } catch (final IOException e) { throw new TechnicalException("Error getting idp metadata resource", e); } } /** * If no idpEntityId declared, select first EntityDescriptor entityId as our IDP. * * @return entity id of the idp */ protected String determineIdentityProviderEntityId() { var idpEntityId = configuration.getIdentityProviderEntityId(); if (idpEntityId == null) { var it = ((IterableMetadataSource) loaded).iterator(); if (it.hasNext()) { var entityDescriptor = it.next(); idpEntityId = entityDescriptor.getEntityID(); } } if (idpEntityId == null) { throw new SAMLException("No idp entityId found"); } return idpEntityId; } /** {@inheritDoc} */ @Override public String getEntityId() { val md = getEntityDescriptorElement(); if (md instanceof EntitiesDescriptor) { return ((EntitiesDescriptor) md).getEntityDescriptors().get(0).getEntityID(); } if (md instanceof EntityDescriptor) { return ((EntityDescriptor) md).getEntityID(); } throw new SAMLException("No idp entityId found"); } /** {@inheritDoc} */ @Override public String getMetadata() {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override public final XMLObject getEntityDescriptorElement() { try { var idpEntityId = determineIdentityProviderEntityId(); return resolve().resolveSingle(new CriteriaSet(new EntityIdCriterion(idpEntityId))); } catch (final ResolverException e) { throw new SAMLException("Error initializing idpMetadataProvider", e); } } }
if (getEntityDescriptorElement() != null) { return Configuration.serializeSamlObject(getEntityDescriptorElement()).toString(); } throw new TechnicalException("Metadata cannot be retrieved because entity descriptor is null");
1,138
56
1,194
<methods>public non-sealed void <init>() ,public boolean hasChanged() ,public final org.opensaml.saml.metadata.resolver.MetadataResolver load() <variables>private static final long NO_LAST_MODIFIED,private final java.util.concurrent.atomic.AtomicBoolean byteArrayHasChanged,private long lastModified,protected org.opensaml.saml.metadata.resolver.MetadataResolver loaded,private final java.util.concurrent.locks.Lock lock,protected final non-sealed org.springframework.core.io.Resource resource
pac4j_pac4j
pac4j/pac4j-saml/src/main/java/org/pac4j/saml/metadata/SAML2ServiceProviderMetadataResolver.java
SAML2ServiceProviderMetadataResolver
getMetadata
class SAML2ServiceProviderMetadataResolver implements SAML2MetadataResolver { protected final SAML2Configuration configuration; private MetadataResolver metadataResolver; /** * <p>Constructor for SAML2ServiceProviderMetadataResolver.</p> * * @param configuration a {@link SAML2Configuration} object */ public SAML2ServiceProviderMetadataResolver(final SAML2Configuration configuration) { this.configuration = configuration; this.metadataResolver = prepareServiceProviderMetadata(); } /** * <p>destroy.</p> */ public void destroy() { if (this.metadataResolver instanceof FilesystemMetadataResolver) { ((FilesystemMetadataResolver) this.metadataResolver).destroy(); this.metadataResolver = null; } } /** * <p>prepareServiceProviderMetadata.</p> * * @return a {@link MetadataResolver} object */ protected MetadataResolver prepareServiceProviderMetadata() { try { val metadataGenerator = configuration.toMetadataGenerator(); val resource = configuration.getServiceProviderMetadataResource(); if (resource == null || !resource.exists() || configuration.isForceServiceProviderMetadataGeneration()) { val entity = metadataGenerator.buildEntityDescriptor(); val metadata = metadataGenerator.getMetadata(entity); metadataGenerator.storeMetadata(metadata, configuration.isForceServiceProviderMetadataGeneration()); } return metadataGenerator.buildMetadataResolver(); } catch (final Exception e) { throw new SAMLException("Unable to generate metadata for service provider", e); } } /** {@inheritDoc} */ @Override public final MetadataResolver resolve() { return this.metadataResolver; } /** {@inheritDoc} */ @Override public final String getEntityId() { return configuration.getServiceProviderEntityId(); } /** {@inheritDoc} */ @Override public String getMetadata() {<FILL_FUNCTION_BODY>} /** {@inheritDoc} */ @Override public XMLObject getEntityDescriptorElement() { try { return resolve().resolveSingle(new CriteriaSet(new EntityIdCriterion(getEntityId()))); } catch (final ResolverException e) { throw new SAMLException("Unable to resolve metadata", e); } } }
try { val metadataGenerator = configuration.toMetadataGenerator(); val entity = metadataGenerator.buildEntityDescriptor(); return metadataGenerator.getMetadata(entity); } catch (final Exception e) { throw new SAMLException("Unable to fetch metadata", e); }
596
72
668
<no_super_class>
pac4j_pac4j
pac4j/pac4j-saml/src/main/java/org/pac4j/saml/metadata/jdbc/SAML2JdbcMetadataGenerator.java
SAML2JdbcMetadataGenerator
storeMetadata
class SAML2JdbcMetadataGenerator extends BaseSAML2MetadataGenerator { private String tableName = "sp_metadata"; private final JdbcTemplate template; private final String entityId; /** {@inheritDoc} */ @Override @SuppressWarnings("PMD.NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE") public AbstractMetadataResolver createMetadataResolver() throws Exception { var metadata = fetchMetadata(); try (var is = new ByteArrayInputStream(metadata)) { var document = Configuration.getParserPool().parse(is); var root = document.getDocumentElement(); return new DOMMetadataResolver(root); } } /** {@inheritDoc} */ @Override public boolean storeMetadata(final String metadata, final boolean force) {<FILL_FUNCTION_BODY>} /** * <p>updateMetadata.</p> * * @param metadataToUse a {@link String} object * @return a boolean */ protected boolean updateMetadata(final String metadataToUse) { var updateSql = String.format("UPDATE %s SET metadata='%s' WHERE entityId='%s'", this.tableName, encodeMetadata(metadataToUse), this.entityId); var count = template.update(updateSql); return count > 0; } /** * <p>insertMetadata.</p> * * @param metadataToUse a {@link String} object * @return a boolean */ protected boolean insertMetadata(String metadataToUse) { var insert = new SimpleJdbcInsert(this.template) .withTableName(String.format("%s", this.tableName)) .usingColumns("entityId", "metadata"); Map<String, Object> parameters = new HashMap<>(); parameters.put("entityId", this.entityId); parameters.put("metadata", encodeMetadata(metadataToUse)); return insert.execute(parameters) > 0; } /** * <p>fetchMetadata.</p> * * @return an array of {@link byte} objects */ protected byte[] fetchMetadata() { var sql = String.format("SELECT metadata FROM %s WHERE entityId='%s'", this.tableName, this.entityId); return decodeMetadata(template.queryForObject(sql, String.class)); } /** * <p>decodeMetadata.</p> * * @param metadata a {@link String} object * @return an array of {@link byte} objects */ protected byte[] decodeMetadata(final String metadata) { return Base64.getDecoder().decode(metadata); } /** * <p>encodeMetadata.</p> * * @param metadataToUse a {@link String} object * @return a {@link String} object */ protected String encodeMetadata(String metadataToUse) { return Base64.getEncoder().encodeToString(metadataToUse.getBytes(StandardCharsets.UTF_8)); } }
if (CommonHelper.isBlank(metadata)) { logger.info("No metadata is provided"); return false; } var metadataToUse = isSignMetadata() ? getMetadataSigner().sign(metadata) : metadata; CommonHelper.assertNotBlank("metadata", metadataToUse); var metadataEntityId = Configuration.deserializeSamlObject(metadataToUse) .map(EntityDescriptor.class::cast) .map(EntityDescriptor::getEntityID) .orElseThrow(); if (!metadataEntityId.equals(this.entityId)) { throw new SAMLException("Entity id from metadata " + metadataEntityId + " does not match supplied entity id " + this.entityId); } try { var sql = String.format("SELECT entityId FROM %s WHERE entityId='%s'", this.tableName, this.entityId); var entityId = template.queryForObject(sql, String.class); logger.debug("Updating metadata entity [{}]", entityId); return updateMetadata(metadataToUse); } catch (final EmptyResultDataAccessException e) { return insertMetadata(metadataToUse); }
776
297
1,073
<methods>public non-sealed void <init>() ,public org.opensaml.saml.saml2.metadata.EntityDescriptor buildEntityDescriptor() ,public org.opensaml.saml.metadata.resolver.MetadataResolver buildMetadataResolver() throws java.lang.Exception,public List<java.lang.String> getBlackListedSignatureSigningAlgorithms() ,public java.lang.String getMetadata(org.opensaml.saml.saml2.metadata.EntityDescriptor) throws java.lang.Exception,public List<java.lang.String> getSignatureAlgorithms() ,public List<java.lang.String> getSignatureReferenceDigestMethods() <variables>protected java.lang.String assertionConsumerServiceUrl,protected boolean authnRequestSigned,protected List<java.lang.String> blackListedSignatureSigningAlgorithms,protected final org.opensaml.core.xml.XMLObjectBuilderFactory builderFactory,private List<org.pac4j.saml.metadata.SAML2MetadataContactPerson> contactPersons,protected org.pac4j.saml.crypto.CredentialProvider credentialProvider,protected int defaultACSIndex,protected org.opensaml.xmlsec.SignatureSigningConfiguration defaultSignatureSigningConfiguration,protected java.lang.String entityId,protected final org.opensaml.xmlsec.algorithm.AlgorithmRegistry globalAlgorithmRegistry,protected final org.slf4j.Logger logger,protected final org.opensaml.core.xml.io.MarshallerFactory marshallerFactory,private org.pac4j.saml.metadata.SAML2MetadataSigner metadataSigner,private List<org.pac4j.saml.metadata.SAML2MetadataUIInfo> metadataUIInfos,protected java.lang.String nameIdPolicyFormat,protected java.lang.String requestInitiatorLocation,protected List<org.pac4j.saml.metadata.SAML2ServiceProviderRequestedAttribute> requestedAttributes,protected java.lang.String responseBindingType,protected boolean signMetadata,protected List<java.lang.String> signatureAlgorithms,protected List<java.lang.String> signatureReferenceDigestMethods,protected java.lang.String singleLogoutServiceUrl,private List<java.lang.String> supportedProtocols,protected boolean wantAssertionSigned
pac4j_pac4j
pac4j/pac4j-saml/src/main/java/org/pac4j/saml/metadata/keystore/BaseSAML2KeystoreGenerator.java
BaseSAML2KeystoreGenerator
generate
class BaseSAML2KeystoreGenerator implements SAML2KeystoreGenerator { /** Constant <code>CERTIFICATES_PREFIX="saml-signing-cert"</code> */ protected static final String CERTIFICATES_PREFIX = "saml-signing-cert"; protected final Logger logger = LoggerFactory.getLogger(getClass()); protected final SAML2Configuration saml2Configuration; /** * <p>Constructor for BaseSAML2KeystoreGenerator.</p> * * @param saml2Configuration a {@link SAML2Configuration} object */ public BaseSAML2KeystoreGenerator(final SAML2Configuration saml2Configuration) { this.saml2Configuration = saml2Configuration; } /** {@inheritDoc} */ @Override public boolean shouldGenerate() { return saml2Configuration.isForceKeystoreGeneration(); } /** {@inheritDoc} */ @Override public void generate() {<FILL_FUNCTION_BODY>} /** * <p>store.</p> * * @param ks a {@link KeyStore} object * @param certificate a {@link X509Certificate} object * @param privateKey a {@link PrivateKey} object * @throws Exception if any. */ protected abstract void store(KeyStore ks, X509Certificate certificate, PrivateKey privateKey) throws Exception; private static Time time(final ChronoLocalDateTime<LocalDate> localDateTime) { return new Time(Date.from(localDateTime.toInstant(ZoneOffset.UTC))); } /** * Generate a self-signed certificate for dn using the provided signature algorithm and key pair. * * @param dn X.500 name to associate with certificate issuer/subject. * @param sigName name of the signature algorithm to use. * @param sigAlgID algorithm ID associated with the signature algorithm name. * @param keyPair the key pair to associate with the certificate. * @return an X509Certificate containing the public key in keyPair. * @throws Exception */ private X509Certificate createSelfSignedCert(final X500Name dn, final String sigName, final AlgorithmIdentifier sigAlgID, final KeyPair keyPair) throws Exception { val certGen = new V3TBSCertificateGenerator(); certGen.setSerialNumber(new ASN1Integer(BigInteger.valueOf(1))); certGen.setIssuer(dn); certGen.setSubject(dn); val startDate = LocalDateTime.now(Clock.systemUTC()).minusSeconds(1); certGen.setStartDate(time(startDate)); val endDate = startDate.plus(saml2Configuration.getCertificateExpirationPeriod()); certGen.setEndDate(time(endDate)); certGen.setSignature(sigAlgID); certGen.setSubjectPublicKeyInfo(SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded())); val sig = Signature.getInstance(sigName); sig.initSign(keyPair.getPrivate()); sig.update(certGen.generateTBSCertificate().getEncoded(ASN1Encoding.DER)); val tbsCert = certGen.generateTBSCertificate(); val v = new ASN1EncodableVector(); v.add(tbsCert); v.add(sigAlgID); v.add(new DERBitString(sig.sign())); val cert = (X509Certificate) CertificateFactory.getInstance("X.509") .generateCertificate(new ByteArrayInputStream(new DERSequence(v).getEncoded(ASN1Encoding.DER))); // check the certificate - this will confirm the encoded sig algorithm ID is correct. cert.verify(keyPair.getPublic()); return cert; } private void validate() { CommonHelper.assertNotBlank("keystoreAlias", saml2Configuration.getKeyStoreAlias()); CommonHelper.assertNotBlank("keystoreType", saml2Configuration.getKeyStoreType()); CommonHelper.assertNotBlank("privateKeyPassword", saml2Configuration.getPrivateKeyPassword()); } }
try { if (CommonHelper.isBlank(saml2Configuration.getKeyStoreAlias())) { saml2Configuration.setKeyStoreAlias(getClass().getSimpleName()); logger.warn("Defaulting keystore alias {}", saml2Configuration.getKeyStoreAlias()); } if (CommonHelper.isBlank(saml2Configuration.getKeyStoreType())) { saml2Configuration.setKeyStoreType(KeyStore.getDefaultType()); logger.warn("Defaulting keystore type {}", saml2Configuration.getKeyStoreType()); } validate(); val ks = KeyStore.getInstance(saml2Configuration.getKeyStoreType()); val password = saml2Configuration.getKeystorePassword().toCharArray(); ks.load(null, password); val kpg = KeyPairGenerator.getInstance("RSA"); kpg.initialize(saml2Configuration.getPrivateKeySize()); val kp = kpg.genKeyPair(); val sigAlg = saml2Configuration.getCertificateSignatureAlg(); val sigAlgID = new DefaultSignatureAlgorithmIdentifierFinder().find(sigAlg); val dn = InetAddress.getLocalHost().getHostName(); val certificate = createSelfSignedCert(new X500Name("CN=" + dn), sigAlg, sigAlgID, kp); val keyPassword = saml2Configuration.getPrivateKeyPassword().toCharArray(); val signingKey = kp.getPrivate(); ks.setKeyEntry(saml2Configuration.getKeyStoreAlias(), signingKey, keyPassword, new Certificate[]{certificate}); store(ks, certificate, signingKey); logger.info("Created keystore {} with key alias {}", saml2Configuration.getKeystoreResource(), ks.aliases().nextElement()); } catch (final Exception e) { throw new SAMLException("Could not create keystore", e); }
1,098
493
1,591
<no_super_class>
pac4j_pac4j
pac4j/pac4j-saml/src/main/java/org/pac4j/saml/metadata/keystore/SAML2FileSystemKeystoreGenerator.java
SAML2FileSystemKeystoreGenerator
store
class SAML2FileSystemKeystoreGenerator extends BaseSAML2KeystoreGenerator { private static final Pattern NORMALIZE_PATTERN = Pattern.compile("[^a-zA-Z0-9-_\\.]"); /** * <p>Constructor for SAML2FileSystemKeystoreGenerator.</p> * * @param configuration a {@link SAML2Configuration} object */ public SAML2FileSystemKeystoreGenerator(final SAML2Configuration configuration) { super(configuration); } private void writeEncodedCertificateToFile(final File file, final byte[] certificate) { if (file.exists()) { val res = file.delete(); logger.debug("Deleted file [{}]:{}", file, res); } try (var pemWriter = new PemWriter( new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8))) { PemObjectGenerator pemObject = new PemObject(file.getName(), certificate); pemWriter.writeObject(pemObject); } catch (final Exception e) { logger.error(e.getMessage(), e); } } private void writeBinaryCertificateToFile(final File file, final byte[] certificate) { if (file.exists()) { val res = file.delete(); logger.debug("Deleted file [{}]:{}", file, res); } try (OutputStream fos = new FileOutputStream(file)) { fos.write(certificate); fos.flush(); } catch (final Exception e) { logger.error(e.getMessage(), e); } } /** {@inheritDoc} */ @Override public boolean shouldGenerate() { validate(); val keystoreFile = saml2Configuration.getKeystoreResource(); return keystoreFile != null && !keystoreFile.exists() || super.shouldGenerate(); } /** {@inheritDoc} */ @Override public InputStream retrieve() throws Exception { validate(); logger.debug("Retrieving keystore from {}", saml2Configuration.getKeystoreResource()); return saml2Configuration.getKeystoreResource().getInputStream(); } private void validate() { CommonHelper.assertNotNull("keystoreResource", saml2Configuration.getKeystoreResource()); CommonHelper.assertNotBlank("keystorePassword", saml2Configuration.getKeystorePassword()); } /** {@inheritDoc} */ @Override protected void store(final KeyStore ks, final X509Certificate certificate, final PrivateKey privateKey) throws Exception {<FILL_FUNCTION_BODY>} /** * Sanitize String to use it as fileName for Signing Certificate Names */ private String getNormalizedCertificateName() { val certName = new StringBuilder(CERTIFICATES_PREFIX); if (CommonHelper.isNotBlank(saml2Configuration.getCertificateNameToAppend())) { certName.append('-'); certName.append(NORMALIZE_PATTERN.matcher(saml2Configuration.getCertificateNameToAppend()) .replaceAll(Pac4jConstants.EMPTY_STRING)); } return certName.toString(); } private File getSigningBinaryCertificatePath() throws IOException { return new File(saml2Configuration.getKeystoreResource().getFile().getParentFile(), getNormalizedCertificateName() + ".crt"); } private File getSigningBase64CertificatePath() throws IOException { return new File(saml2Configuration.getKeystoreResource().getFile().getParentFile(), getNormalizedCertificateName() + ".pem"); } private File getSigningKeyFile() throws IOException { return new File(saml2Configuration.getKeystoreResource().getFile().getParentFile(), getNormalizedCertificateName() + ".key"); } }
validate(); val keystoreFile = saml2Configuration.getKeystoreResource().getFile(); val parentFile = keystoreFile.getParentFile(); if (parentFile != null && !parentFile.exists() && !parentFile.mkdirs()) { logger.warn("Could not construct the directory structure for keystore: {}", keystoreFile.getCanonicalPath()); } val password = saml2Configuration.getKeystorePassword().toCharArray(); try (OutputStream fos = new FileOutputStream(keystoreFile.getCanonicalPath())) { ks.store(fos, password); fos.flush(); } val signingCertEncoded = getSigningBase64CertificatePath(); writeEncodedCertificateToFile(signingCertEncoded, certificate.getEncoded()); val signingCertBinary = getSigningBinaryCertificatePath(); writeBinaryCertificateToFile(signingCertBinary, certificate.getEncoded()); val signingKeyEncoded = getSigningKeyFile(); writeEncodedCertificateToFile(signingKeyEncoded, privateKey.getEncoded());
1,006
272
1,278
<methods>public void <init>(org.pac4j.saml.config.SAML2Configuration) ,public void generate() ,public boolean shouldGenerate() <variables>protected static final java.lang.String CERTIFICATES_PREFIX,protected final org.slf4j.Logger logger,protected final non-sealed org.pac4j.saml.config.SAML2Configuration saml2Configuration
pac4j_pac4j
pac4j/pac4j-saml/src/main/java/org/pac4j/saml/metadata/keystore/SAML2HttpUrlKeystoreGenerator.java
SAML2HttpUrlKeystoreGenerator
store
class SAML2HttpUrlKeystoreGenerator extends BaseSAML2KeystoreGenerator { /** * <p>Constructor for SAML2HttpUrlKeystoreGenerator.</p> * * @param configuration a {@link SAML2Configuration} object */ public SAML2HttpUrlKeystoreGenerator(final SAML2Configuration configuration) { super(configuration); } /** {@inheritDoc} */ @Override public InputStream retrieve() throws Exception { validate(); val url = saml2Configuration.getKeystoreResource().getURL().toExternalForm(); logger.debug("Loading keystore from {}", url); ClassicHttpRequest httpGet = new HttpGet(url); httpGet.addHeader("Accept", ContentType.TEXT_PLAIN.getMimeType()); httpGet.addHeader("Content-Type", ContentType.TEXT_PLAIN.getMimeType()); return saml2Configuration.getHttpClient().execute(httpGet, response -> { try { if (response != null) { val code = response.getCode(); if (code == HttpStatus.SC_OK) { logger.info("Successfully submitted/created keystore to {}", url); val results = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8); return new ByteArrayInputStream(Base64.getDecoder().decode(results)); } } throw new SAMLException("Unable to retrieve keystore from " + url); } finally { if (response != null && response instanceof CloseableHttpResponse) { response.close(); } } }); } /** {@inheritDoc} */ @Override protected void store(final KeyStore ks, final X509Certificate certificate, final PrivateKey privateKey) throws Exception {<FILL_FUNCTION_BODY>} private void validate() { CommonHelper.assertNotNull("keystoreResource", saml2Configuration.getKeystoreResource()); CommonHelper.assertNotBlank("keystorePassword", saml2Configuration.getPrivateKeyPassword()); CommonHelper.assertNotBlank("privateKeyPassword", saml2Configuration.getPrivateKeyPassword()); } }
validate(); HttpResponse response = null; try (var out = new ByteArrayOutputStream()) { val password = saml2Configuration.getKeystorePassword().toCharArray(); ks.store(out, password); out.flush(); val content = Base64.getEncoder().encodeToString(out.toByteArray()); if (logger.isTraceEnabled()) { logger.trace("Encoded keystore as base-64: {}", content); } val url = saml2Configuration.getKeystoreResource().getURL().toExternalForm(); val httpPost = new HttpPost(url); httpPost.addHeader("Accept", ContentType.TEXT_PLAIN.getMimeType()); httpPost.addHeader("Content-Type", ContentType.TEXT_PLAIN.getMimeType()); httpPost.setEntity(new StringEntity(content, ContentType.TEXT_PLAIN)); logger.debug("Submitting keystore to {}", url); response = saml2Configuration.getHttpClient().execute(httpPost); if (response != null) { val code = response.getCode(); if (code == HttpStatus.SC_NOT_IMPLEMENTED) { logger.info("Storing keystore is not supported/implemented by {}", url); } else if (code == HttpStatus.SC_OK || code == HttpStatus.SC_CREATED) { logger.info("Successfully submitted/created keystore to {}", url); } else if (code == HttpStatus.SC_NOT_MODIFIED) { logger.info("Keystore was not modified/updated: {}", url); } else { logger.error("Unable to store keystore successfully via {}", url); } } } finally { if (response != null && response instanceof CloseableHttpResponse) { ((CloseableHttpResponse) response).close(); } }
568
482
1,050
<methods>public void <init>(org.pac4j.saml.config.SAML2Configuration) ,public void generate() ,public boolean shouldGenerate() <variables>protected static final java.lang.String CERTIFICATES_PREFIX,protected final org.slf4j.Logger logger,protected final non-sealed org.pac4j.saml.config.SAML2Configuration saml2Configuration
pac4j_pac4j
pac4j/pac4j-saml/src/main/java/org/pac4j/saml/metadata/mongo/SAML2MongoMetadataGenerator.java
SAML2MongoMetadataGenerator
storeMetadata
class SAML2MongoMetadataGenerator extends BaseSAML2MetadataGenerator { private final MongoClient mongoClient; private final String entityId; private String metadataDatabase = "saml2"; private String metadataCollection = "metadata"; /** {@inheritDoc} */ @Override public AbstractMetadataResolver createMetadataResolver() throws Exception { var documents = Objects.requireNonNull(getCollection().find(buildMetadataDocumentFilter(this.entityId))); var foundDoc = documents.first(); if (foundDoc != null) { var metadata = foundDoc.getString("metadata"); try (var is = new ByteArrayInputStream(metadata.getBytes(StandardCharsets.UTF_8))) { var document = Configuration.getParserPool().parse(is); var root = document.getDocumentElement(); return new DOMMetadataResolver(root); } } throw new SAMLException("Unable to locate metadata document "); } /** * <p>buildMetadataDocumentFilter.</p> * * @param entityId a {@link String} object * @return a {@link Bson} object */ protected Bson buildMetadataDocumentFilter(final String entityId) { return eq("entityId", entityId); } /** {@inheritDoc} */ @Override public boolean storeMetadata(final String metadata, final boolean force) {<FILL_FUNCTION_BODY>} /** * <p>getCollection.</p> * * @return a {@link MongoCollection} object */ protected MongoCollection<Document> getCollection() { val db = mongoClient.getDatabase(metadataDatabase); return Objects.requireNonNull(db.getCollection(metadataCollection)); } }
if (CommonHelper.isBlank(metadata)) { logger.info("No metadata is provided"); return false; } var metadataToUse = isSignMetadata() ? getMetadataSigner().sign(metadata) : metadata; CommonHelper.assertNotBlank("metadata", metadataToUse); var metadataEntityId = Configuration.deserializeSamlObject(metadataToUse) .map(EntityDescriptor.class::cast) .map(EntityDescriptor::getEntityID) .orElseThrow(); if (!metadataEntityId.equals(this.entityId)) { throw new SAMLException("Entity id from metadata " + metadataEntityId + " does not match supplied entity id " + this.entityId); } var filter = buildMetadataDocumentFilter(metadataEntityId); var foundDoc = getCollection().find(filter).first(); if (foundDoc == null) { val doc = new Document(); doc.put("metadata", metadataToUse); doc.put("entityId", metadataEntityId); return getCollection().insertOne(doc).getInsertedId() != null; } foundDoc.put("metadata", metadataToUse); var updateResult = getCollection().updateOne(filter, new Document("$set", foundDoc)); return updateResult.getMatchedCount() == 1;
443
330
773
<methods>public non-sealed void <init>() ,public org.opensaml.saml.saml2.metadata.EntityDescriptor buildEntityDescriptor() ,public org.opensaml.saml.metadata.resolver.MetadataResolver buildMetadataResolver() throws java.lang.Exception,public List<java.lang.String> getBlackListedSignatureSigningAlgorithms() ,public java.lang.String getMetadata(org.opensaml.saml.saml2.metadata.EntityDescriptor) throws java.lang.Exception,public List<java.lang.String> getSignatureAlgorithms() ,public List<java.lang.String> getSignatureReferenceDigestMethods() <variables>protected java.lang.String assertionConsumerServiceUrl,protected boolean authnRequestSigned,protected List<java.lang.String> blackListedSignatureSigningAlgorithms,protected final org.opensaml.core.xml.XMLObjectBuilderFactory builderFactory,private List<org.pac4j.saml.metadata.SAML2MetadataContactPerson> contactPersons,protected org.pac4j.saml.crypto.CredentialProvider credentialProvider,protected int defaultACSIndex,protected org.opensaml.xmlsec.SignatureSigningConfiguration defaultSignatureSigningConfiguration,protected java.lang.String entityId,protected final org.opensaml.xmlsec.algorithm.AlgorithmRegistry globalAlgorithmRegistry,protected final org.slf4j.Logger logger,protected final org.opensaml.core.xml.io.MarshallerFactory marshallerFactory,private org.pac4j.saml.metadata.SAML2MetadataSigner metadataSigner,private List<org.pac4j.saml.metadata.SAML2MetadataUIInfo> metadataUIInfos,protected java.lang.String nameIdPolicyFormat,protected java.lang.String requestInitiatorLocation,protected List<org.pac4j.saml.metadata.SAML2ServiceProviderRequestedAttribute> requestedAttributes,protected java.lang.String responseBindingType,protected boolean signMetadata,protected List<java.lang.String> signatureAlgorithms,protected List<java.lang.String> signatureReferenceDigestMethods,protected java.lang.String singleLogoutServiceUrl,private List<java.lang.String> supportedProtocols,protected boolean wantAssertionSigned