public String convert(final Object attribute) { if (attribute != null && attribute instanceof String) { final String s = (String) attribute; if (CommonHelper.isNotBlank(s) && CommonHelper.isNotBlank(this.regex) && CommonHelper.isNotBlank(this.replacement)) { return s.replaceAll(this.regex, this.replacement); } } return null; }
@Override protected void verifyProfile(CommonProfile userProfile) { final PayPalProfile profile = (PayPalProfile) userProfile; assertEquals("YAxf5WKSFn4BG_l3wqcBJUSObQTG1Aww5FY0EDf_ccw", profile.getId()); assertEquals( PayPalProfile.class.getName() + CommonProfile.SEPARATOR + "YAxf5WKSFn4BG_l3wqcBJUSObQTG1Aww5FY0EDf_ccw", profile.getTypedId()); assertTrue(ProfileHelper.isTypedIdOf(profile.getTypedId(), PayPalProfile.class)); assertTrue(CommonHelper.isNotBlank(profile.getAccessToken())); assertCommonProfile( userProfile, "*****@*****.**", "Test", "ScribeUP", "Test ScribeUP", null, Gender.UNSPECIFIED, Locale.FRANCE, null, null, "Europe/Berlin"); final PayPalAddress address = profile.getAddress(); assertEquals("FR", address.getCountry()); assertEquals("Paris", address.getLocality()); assertEquals("75001", address.getPostalCode()); assertEquals("Adr1", address.getStreetAddress()); final Locale language = profile.getLanguage(); assertEquals(Locale.FRANCE, language); assertEquals(9, profile.getAttributes().size()); }
@Override protected void verifyProfile(UserProfile userProfile) { final Google2Profile profile = (Google2Profile) userProfile; assertEquals("113675986756217860428", profile.getId()); assertEquals( Google2Profile.class.getName() + UserProfile.SEPARATOR + "113675986756217860428", profile.getTypedId()); assertTrue(ProfileHelper.isTypedIdOf(profile.getTypedId(), Google2Profile.class)); assertTrue(CommonHelper.isNotBlank(profile.getAccessToken())); assertCommonProfile( userProfile, "*****@*****.**", "Jérôme", "ScribeUP", "Jérôme ScribeUP", null, Gender.MALE, Locale.ENGLISH, "https://lh4.googleusercontent.com/-fFUNeYqT6bk/AAAAAAAAAAI/AAAAAAAAAAA/5gBL6csVWio/photo.jpg", "https://plus.google.com/113675986756217860428", null); assertNull(profile.getBirthday()); assertTrue(profile.getEmails() != null && profile.getEmails().size() == 1); assertEquals(9, profile.getAttributes().size()); }
@Override protected void verifyProfile(UserProfile userProfile) { final WordPressProfile profile = (WordPressProfile) userProfile; logger.debug("userProfile : {}", profile); assertEquals("35944437", profile.getId()); assertEquals( WordPressProfile.class.getName() + UserProfile.SEPARATOR + "35944437", profile.getTypedId()); assertTrue(ProfileHelper.isTypedIdOf(profile.getTypedId(), WordPressProfile.class)); assertTrue(CommonHelper.isNotBlank(profile.getAccessToken())); assertCommonProfile( userProfile, "*****@*****.**", null, null, "testscribeup", "testscribeup", Gender.UNSPECIFIED, null, "https://0.gravatar.com/avatar/67c3844a672979889c1e3abbd8c4eb22?s=96&d=identicon&r=G", "http://en.gravatar.com/testscribeup", null); assertEquals(36224958, profile.getPrimaryBlog().intValue()); final WordPressLinks links = profile.getLinks(); assertEquals("https://public-api.wordpress.com/rest/v1/me", links.getSelf()); assertEquals("https://public-api.wordpress.com/rest/v1/me/help", links.getHelp()); assertEquals("https://public-api.wordpress.com/rest/v1/sites/36224958", links.getSite()); assertEquals(8, profile.getAttributes().size()); }
@Override protected void verifyProfile(UserProfile userProfile) { final TwitterProfile profile = (TwitterProfile) userProfile; assertEquals("488358057", profile.getId()); assertEquals( TwitterProfile.class.getName() + UserProfile.SEPARATOR + "488358057", profile.getTypedId()); assertTrue(ProfileHelper.isTypedIdOf(profile.getTypedId(), TwitterProfile.class)); assertTrue(CommonHelper.isNotBlank(profile.getAccessToken())); assertCommonProfile( userProfile, null, null, null, "test scribeUP", "testscribeUP", Gender.UNSPECIFIED, Locale.UK, ".twimg.com/sticky/default_profile_images/default_profile_5_normal.png", "http://t.co/fNjYqp7wZ8", "New York"); assertFalse(profile.getContributorsEnabled()); assertEquals( TestsHelper.getFormattedDate(1328872224000L, "EEE MMM dd HH:mm:ss Z yyyy", Locale.US), profile.getCreatedAt().toString()); assertTrue(profile.getDefaultProfile()); assertTrue(profile.getDefaultProfileImage()); assertEquals("biographie", profile.getDescription()); assertEquals(0, profile.getFavouritesCount().intValue()); assertFalse(profile.getFollowRequestSent()); assertEquals(0, profile.getFollowersCount().intValue()); assertFalse(profile.getFollowing()); assertEquals(0, profile.getFriendsCount().intValue()); assertFalse(profile.getGeoEnabled()); assertFalse(profile.getIsTranslator()); assertEquals(0, profile.getListedCount().intValue()); assertFalse(profile.getNotifications()); assertTrue(profile.getProfileBackgroundColor() instanceof Color); assertTrue( profile.getProfileBackgroundImageUrl().contains(".twimg.com/images/themes/theme1/bg.png")); assertTrue( profile.getProfileBackgroundImageUrlHttps().endsWith("/images/themes/theme1/bg.png")); assertFalse(profile.getProfileBackgroundTile()); assertTrue( profile .getProfileImageUrlHttps() .endsWith("/sticky/default_profile_images/default_profile_5_normal.png")); assertTrue(profile.getProfileLinkColor() instanceof Color); assertTrue(profile.getProfileSidebarBorderColor() instanceof Color); assertTrue(profile.getProfileSidebarFillColor() instanceof Color); assertTrue(profile.getProfileTextColor() instanceof Color); assertTrue(profile.getProfileUseBackgroundImage()); assertTrue(profile.getProtected()); assertNull(profile.getShowAllInlineMedia()); assertEquals(0, profile.getStatusesCount().intValue()); assertEquals("Amsterdam", profile.getTimeZone()); assertEquals(3600, profile.getUtcOffset().intValue()); assertFalse(profile.getVerified()); assertNotNull(profile.getAccessSecret()); assertEquals(37, profile.getAttributes().size()); }
@Override protected boolean hasBeenCancelled(final WebContext context) { final String denied = context.getRequestParameter("denied"); if (CommonHelper.isNotBlank(denied)) { return true; } else { return false; } }
protected Result redirectToOriginallyRequestedUrl(final WebContext context) { final String requestedUrl = (String) context.getSessionAttribute(Pac4jConstants.REQUESTED_URL); logger.debug("requestedUrl: {}", requestedUrl); if (CommonHelper.isNotBlank(requestedUrl)) { context.setSessionAttribute(Pac4jConstants.REQUESTED_URL, null); return redirect(requestedUrl); } else { return redirect(this.defaultUrl); } }
@Override public boolean isAuthorized( final WebContext context, final UserProfile profile, final String authorizerName, final Map<String, Authorizer> authorizersMap) { final List<Authorizer> authorizers = new ArrayList<>(); // if we have an authorizer name (which may be a list of authorizer names) if (CommonHelper.isNotBlank(authorizerName)) { final String[] names = authorizerName.split(Pac4jConstants.ELEMENT_SEPRATOR); final int nb = names.length; for (int i = 0; i < nb; i++) { final String name = names[i]; if ("hsts".equalsIgnoreCase(name)) { authorizers.add(STRICT_TRANSPORT_SECURITY_HEADER); } else if ("nosniff".equalsIgnoreCase(name)) { authorizers.add(X_CONTENT_TYPE_OPTIONS_HEADER); } else if ("noframe".equalsIgnoreCase(name)) { authorizers.add(X_FRAME_OPTIONS_HEADER); } else if ("xssprotection".equalsIgnoreCase(name)) { authorizers.add(XSS_PROTECTION_HEADER); } else if ("nocache".equalsIgnoreCase(name)) { authorizers.add(CACHE_CONTROL_HEADER); } else if ("securityheaders".equalsIgnoreCase(name)) { authorizers.add(CACHE_CONTROL_HEADER); authorizers.add(X_CONTENT_TYPE_OPTIONS_HEADER); authorizers.add(STRICT_TRANSPORT_SECURITY_HEADER); authorizers.add(X_FRAME_OPTIONS_HEADER); authorizers.add(XSS_PROTECTION_HEADER); } else if ("csrfToken".equalsIgnoreCase(name)) { authorizers.add(CSRF_TOKEN_GENERATOR_AUTHORIZER); } else if ("csrfCheck".equalsIgnoreCase(name)) { authorizers.add(CSRF_AUTHORIZER); } else if ("csrf".equalsIgnoreCase(name)) { authorizers.add(CSRF_TOKEN_GENERATOR_AUTHORIZER); authorizers.add(CSRF_AUTHORIZER); } else { // we must have authorizers CommonHelper.assertNotNull("authorizersMap", authorizersMap); final Authorizer result = authorizersMap.get(name); // we must have an authorizer defined for this name CommonHelper.assertNotNull("authorizersMap['" + name + "']", result); authorizers.add(result); } } } return isAuthorized(context, profile, authorizers); }
@Override protected void internalInit() { CommonHelper.assertTrue( CommonHelper.isNotBlank(this.idpMetadata) || CommonHelper.isNotBlank(this.idpMetadataPath), "Either idpMetadata or idpMetadataPath must be provided"); CommonHelper.assertNotBlank("callbackUrl", this.callbackUrl); if (!this.callbackUrl.startsWith("http")) { throw new TechnicalException("SAML callbackUrl must be absolute"); } if (CommonHelper.isNotBlank(this.keystorePath) || CommonHelper.isNotBlank(this.keystorePassword) || CommonHelper.isNotBlank(this.privateKeyPassword)) { CommonHelper.assertNotBlank("keystorePath", this.keystorePath); CommonHelper.assertNotBlank("keystorePassword", this.keystorePassword); CommonHelper.assertNotBlank("privateKeyPassword", this.privateKeyPassword); // load private key from the keystore and provide it as OpenSAML credentials this.credentialProvider = new CredentialProvider(this.keystorePath, this.keystorePassword, this.privateKeyPassword); this.decrypter = new EncryptionProvider(this.credentialProvider).buildDecrypter(); } // Bootsrap OpenSAML try { DefaultBootstrap.bootstrap(); NamedKeyInfoGeneratorManager manager = Configuration.getGlobalSecurityConfiguration().getKeyInfoGeneratorManager(); X509KeyInfoGeneratorFactory generator = new X509KeyInfoGeneratorFactory(); generator.setEmitEntityCertificate(true); generator.setEmitEntityCertificateChain(true); manager.registerFactory(Saml2Client.SAML_METADATA_KEY_INFO_GENERATOR, generator); } catch (ConfigurationException e) { throw new SamlException("Error bootstrapping OpenSAML", e); } // required parserPool for XML processing final StaticBasicParserPool parserPool = newStaticBasicParserPool(); final AbstractMetadataProvider idpMetadataProvider = idpMetadataProvider(parserPool); final XMLObject md; try { md = idpMetadataProvider.getMetadata(); } catch (MetadataProviderException e) { throw new SamlException("Error initializing idpMetadataProvider", e); } // If no idpEntityId declared, select first EntityDescriptor entityId as our IDP entityId if (this.idpEntityId == null) { this.idpEntityId = getIdpEntityId(md); } // Generate our Service Provider metadata Saml2MetadataGenerator metadataGenerator = new Saml2MetadataGenerator(); if (this.credentialProvider != null) { metadataGenerator.setCredentialProvider(this.credentialProvider); metadataGenerator.setAuthnRequestSigned(true); } // If the spEntityId is blank, use the callback url if (CommonHelper.isBlank(this.spEntityId)) { this.spEntityId = getCallbackUrl(); } metadataGenerator.setEntityId(this.spEntityId); // Assertion consumer service url is the callback url metadataGenerator.setAssertionConsumerServiceUrl(getCallbackUrl()); // for now same for logout url metadataGenerator.setSingleLogoutServiceUrl(getCallbackUrl()); AbstractMetadataProvider spMetadataProvider = metadataGenerator.buildMetadataProvider(); // Initialize metadata provider for our SP and get the XML as a String try { spMetadataProvider.initialize(); this.spMetadata = metadataGenerator.printMetadata(); } catch (MetadataProviderException e) { throw new TechnicalException("Error initializing spMetadataProvider", e); } catch (MarshallingException e) { logger.warn("Unable to print SP metadata", e); } // Put IDP and SP metadata together ChainingMetadataProvider metadataManager = new ChainingMetadataProvider(); try { metadataManager.addMetadataProvider(idpMetadataProvider); metadataManager.addMetadataProvider(spMetadataProvider); } catch (MetadataProviderException e) { throw new TechnicalException("Error adding idp or sp metadatas to manager", e); } // Build the contextProvider this.contextProvider = new Saml2ContextProvider(metadataManager, this.idpEntityId, this.spEntityId); // Get an AuthnRequest builder this.authnRequestBuilder = new Saml2AuthnRequestBuilder(forceAuth, comparisonType, destinationBindingType); // Build the WebSSO handler for sending and receiving SAML2 messages MessageEncoder encoder = null; if (SAMLConstants.SAML2_POST_BINDING_URI.equals(destinationBindingType)) { // Get a velocity engine for the HTTP-POST binding (building of an HTML document) VelocityEngine velocityEngine = VelocityEngineFactory.getEngine(); encoder = new HTTPPostEncoder(velocityEngine, "/templates/saml2-post-binding.vm"); } else if (SAMLConstants.SAML2_REDIRECT_BINDING_URI.equals(destinationBindingType)) { encoder = new HTTPRedirectDeflateEncoder(); } else { throw new UnsupportedOperationException( "Binding type - " + destinationBindingType + " is not supported"); } // Do we need binding specific decoder? MessageDecoder decoder = new Pac4jHTTPPostDecoder(parserPool); this.handler = new Saml2WebSSOProfileHandler( this.credentialProvider, encoder, decoder, parserPool, destinationBindingType); // Build provider for digital signature validation and encryption this.signatureTrustEngineProvider = new SignatureTrustEngineProvider(metadataManager); // Build the SAML response validator this.responseValidator = new Saml2ResponseValidator(); if (this.maximumAuthenticationLifetime != null) { this.responseValidator.setMaximumAuthenticationLifetime(this.maximumAuthenticationLifetime); } }