org.opensaml.saml.saml2.core.NameID Java Examples

The following examples show how to use org.opensaml.saml.saml2.core.NameID. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AuthnRequestBuilderTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testCreateLogoutRequest() throws Exception {
    Document doc = DOMUtils.createDocument();

    Issuer issuer =
        SamlpRequestComponentBuilder.createIssuer("http://localhost:9001/app");

    NameIDBean nameIdBean = new NameIDBean();
    nameIdBean.setNameValue("uid=joe,ou=people,ou=saml-demo,o=example.com");
    nameIdBean.setNameQualifier("www.example.com");
    NameID nameID = SAML2ComponentBuilder.createNameID(nameIdBean);

    Date notOnOrAfter = new Date();
    notOnOrAfter.setTime(notOnOrAfter.getTime() + 60L * 1000L);
    LogoutRequest logoutRequest =
        SamlpRequestComponentBuilder.createLogoutRequest(SAMLVersion.VERSION_20, issuer, null, null,
                                                         notOnOrAfter, null, nameID);

    Element policyElement = OpenSAMLUtil.toDom(logoutRequest, doc);
    doc.appendChild(policyElement);
    // String outputString = DOM2Writer.nodeToString(policyElement);
    assertNotNull(policyElement);
}
 
Example #2
Source File: MyAuthHandler.java    From armeria with Apache License 2.0 6 votes vote down vote up
/**
 * Invoked when the SAML authentication process is finished and a user is authenticated. You can get
 * information about the authenticated user from the {@link Response}, especially his or her login name.
 * In this example, an email address is used as a login name. The login name is transferred to a web
 * browser via {@code Set-Cookie} header.
 */
@Override
public HttpResponse loginSucceeded(ServiceRequestContext ctx, AggregatedHttpRequest req,
                                   MessageContext<Response> message, @Nullable String sessionIndex,
                                   @Nullable String relayState) {
    final NameID nameId = getNameId(message.getMessage(), SamlNameIdFormat.EMAIL);
    final String username = nameId != null ? nameId.getValue() : null;
    if (username == null) {
        return HttpResponse.of(HttpStatus.UNAUTHORIZED, MediaType.HTML_UTF_8,
                               "<html><body>Username is not found.</body></html>");
    }

    logger.info("{} user '{}' has been logged in.", ctx, username);

    final Cookie cookie = Cookie.builder("username", username)
                                .httpOnly(true)
                                .domain("localhost")
                                .maxAge(60)
                                .path("/")
                                .build();
    return HttpResponse.of(
            ResponseHeaders.of(HttpStatus.OK,
                               HttpHeaderNames.CONTENT_TYPE, MediaType.HTML_UTF_8,
                               HttpHeaderNames.SET_COOKIE, cookie.toSetCookieHeader(false)),
            HttpData.ofUtf8("<html><body onLoad=\"window.location.href='/welcome'\"></body></html>"));
}
 
Example #3
Source File: OnBehalfOfValidator.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
public Credential validate(Credential credential, RequestData data) throws WSSecurityException {
    Credential validatedCredential = super.validate(credential, data);
    SamlAssertionWrapper assertion = validatedCredential.getSamlAssertion();

    Assertion saml2Assertion = assertion.getSaml2();
    if (saml2Assertion == null) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }

    List<AttributeStatement> attributeStatements = saml2Assertion.getAttributeStatements();
    if (attributeStatements == null || attributeStatements.isEmpty()) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }

    Subject subject = saml2Assertion.getSubject();
    NameID nameID = subject.getNameID();
    String subjectName = nameID.getValue();
    if ("alice".equals(subjectName) || "bob".equals(subjectName)) {
        return validatedCredential;
    }

    throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
}
 
Example #4
Source File: SamlServiceProviderTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
private static LogoutRequest getLogoutRequest(String destination, String issuerId) {
    final LogoutRequest logoutRequest = build(LogoutRequest.DEFAULT_ELEMENT_NAME);

    logoutRequest.setID(requestIdManager.newId());
    logoutRequest.setDestination(destination);

    final Issuer issuer = build(Issuer.DEFAULT_ELEMENT_NAME);
    issuer.setValue(issuerId);
    logoutRequest.setIssuer(issuer);
    logoutRequest.setIssueInstant(DateTime.now());

    final NameID nameID = build(NameID.DEFAULT_ELEMENT_NAME);
    nameID.setFormat(SamlNameIdFormat.EMAIL.urn());

    logoutRequest.setNameID(nameID);

    return logoutRequest;
}
 
Example #5
Source File: GoogleAccountsService.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
/**
 * Construct SAML response.
 * <a href="http://bit.ly/1uI8Ggu">See this reference for more info.</a>
 * @return the SAML response
 */
private String constructSamlResponse() {
    final DateTime currentDateTime = DateTime.parse(new ISOStandardDateFormat().getCurrentDateAndTime());
    final DateTime notBeforeIssueInstant = DateTime.parse("2003-04-17T00:46:02Z");

    final RegisteredService svc = this.servicesManager.findServiceBy(this);
    final String userId = svc.getUsernameAttributeProvider().resolveUsername(getPrincipal(), this);

    final org.opensaml.saml.saml2.core.Response response = BUILDER.newResponse(
            BUILDER.generateSecureRandomId(),
            currentDateTime,
            getId(), this);
    response.setStatus(BUILDER.newStatus(StatusCode.SUCCESS, null));

    final AuthnStatement authnStatement = BUILDER.newAuthnStatement(
            AuthnContext.PASSWORD_AUTHN_CTX, currentDateTime);
    final Assertion assertion = BUILDER.newAssertion(authnStatement,
            "https://www.opensaml.org/IDP",
            notBeforeIssueInstant, BUILDER.generateSecureRandomId());

    final Conditions conditions = BUILDER.newConditions(notBeforeIssueInstant,
            currentDateTime, getId());
    assertion.setConditions(conditions);

    final Subject subject = BUILDER.newSubject(NameID.EMAIL, userId,
            getId(), currentDateTime, this.requestId);
    assertion.setSubject(subject);

    response.getAssertions().add(assertion);

    final StringWriter writer = new StringWriter();
    BUILDER.marshalSamlXmlObject(response, writer);

    final String result = writer.toString();
    logger.debug("Generated Google SAML response: {}", result);
    return result;
}
 
Example #6
Source File: SamlpRequestComponentBuilder.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static LogoutRequest createLogoutRequest(
    Issuer issuer,
    String reason,
    NameID nameId,
    List<String> sessionIndices
) {
    if (logoutRequestBuilder == null) {
        logoutRequestBuilder = (SAMLObjectBuilder<LogoutRequest>)
            builderFactory.getBuilder(LogoutRequest.DEFAULT_ELEMENT_NAME);
    }
    if (sessionIndexBuilder == null) {
        sessionIndexBuilder = (SAMLObjectBuilder<SessionIndex>)
            builderFactory.getBuilder(SessionIndex.DEFAULT_ELEMENT_NAME);
    }

    LogoutRequest logoutRequest = logoutRequestBuilder.buildObject();

    logoutRequest.setID("_" + UUID.randomUUID().toString());
    logoutRequest.setIssueInstant(new DateTime());

    if (reason != null) {
        logoutRequest.setReason(reason);
    }
    if (nameId != null) {
        logoutRequest.setNameID(nameId);
    }

    if (sessionIndices != null && !sessionIndices.isEmpty()) {
        for (String sessionIndex : sessionIndices) {
            SessionIndex sessionIndexObj = sessionIndexBuilder.buildObject();
            sessionIndexObj.setSessionIndex(sessionIndex);
            logoutRequest.getSessionIndexes().add(sessionIndexObj);
        }
    }

    logoutRequest.setIssuer(issuer);

    return logoutRequest;
}
 
Example #7
Source File: SamlpRequestComponentBuilder.java    From cxf with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static LogoutRequest createLogoutRequest(
    SAMLVersion version,
    Issuer issuer,
    String destination,
    String consent,
    Date notOnOrAfter,
    String reason,
    NameID nameID
) {
    if (logoutRequestBuilder == null) {
        logoutRequestBuilder = (SAMLObjectBuilder<LogoutRequest>)
            builderFactory.getBuilder(LogoutRequest.DEFAULT_ELEMENT_NAME);
    }
    LogoutRequest logoutRequest = logoutRequestBuilder.buildObject();
    logoutRequest.setID("_" + UUID.randomUUID());
    logoutRequest.setVersion(version);
    logoutRequest.setIssueInstant(new DateTime());
    logoutRequest.setDestination(destination);
    logoutRequest.setConsent(consent);
    logoutRequest.setIssuer(issuer);
    if (notOnOrAfter != null) {
        logoutRequest.setNotOnOrAfter(new DateTime(notOnOrAfter.getTime()));
    }
    logoutRequest.setReason(reason);
    logoutRequest.setNameID(nameID);

    return logoutRequest;
}
 
Example #8
Source File: Util.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Build NameID object given name ID format
 *
 * @param nameIdFormat Name ID format
 * @param subject      Subject
 * @return SAML NameID object
 */
public static NameID buildNameID(String nameIdFormat, String subject) {
    NameID nameIdObj = new NameIDBuilder().buildObject();
    if (!StringUtils.isEmpty(nameIdFormat)) {
        nameIdObj.setFormat(nameIdFormat);
    } else {
        nameIdObj.setFormat(SSOConstants.NAME_ID_POLICY_DEFAULT);
    }
    nameIdObj.setValue(subject);
    return nameIdObj;
}
 
Example #9
Source File: SamlUtil.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a {@link NameID} which is matched to the specified {@code filter} from the {@link Response}.
 */
@Nullable
public static NameID getNameId(Response response, Predicate<NameID> filter) {
    return response.getAssertions().stream()
                   .map(s -> s.getSubject().getNameID())
                   .filter(filter)
                   .findFirst().orElse(null);
}
 
Example #10
Source File: SamlClient.java    From saml-client with MIT License 5 votes vote down vote up
/**
 * Gets the encoded logout request.
 *
 * @param nameId the name id
 * @return the logout request
 * @throws SamlException the saml exception
 */
public String getLogoutRequest(String nameId) throws SamlException {
  LogoutRequest request = (LogoutRequest) getBasicSamlRequest(LogoutRequest.DEFAULT_ELEMENT_NAME);

  NameID nid = (NameID) buildSamlObject(NameID.DEFAULT_ELEMENT_NAME);
  nid.setValue(nameId);
  request.setNameID(nid);

  signSAMLObject(request);

  return marshallAndEncodeSamlObject(request);
}
 
Example #11
Source File: SAML2SPLogic.java    From syncope with Apache License 2.0 4 votes vote down vote up
@PreAuthorize("isAuthenticated() and not(hasRole('" + IdRepoEntitlement.ANONYMOUS + "'))")
public SAML2RequestTO createLogoutRequest(final String accessToken, final String spEntityID) {
    check();

    // 1. fetch the current JWT used for Syncope authentication
    JwsJwtCompactConsumer consumer = new JwsJwtCompactConsumer(accessToken);
    if (!consumer.verifySignatureWith(jwsSignatureVerifier)) {
        throw new IllegalArgumentException("Invalid signature found in Access Token");
    }

    // 2. look for IdP
    String idpEntityID = (String) consumer.getJwtClaims().getClaim(JWT_CLAIM_IDP_ENTITYID);
    if (idpEntityID == null) {
        throw new NotFoundException("No SAML 2.0 IdP information found in the access token");
    }
    SAML2IdPEntity idp = cache.get(idpEntityID);
    if (idp == null) {
        throw new NotFoundException("SAML 2.0 IdP '" + idpEntityID + '\'');
    }
    if (idp.getSLOLocation(idp.getBindingType()) == null) {
        throw new IllegalArgumentException("No SingleLogoutService available for " + idp.getId());
    }

    // 3. create LogoutRequest
    LogoutRequest logoutRequest = new LogoutRequestBuilder().buildObject();
    logoutRequest.setID('_' + SecureRandomUtils.generateRandomUUID().toString());
    logoutRequest.setDestination(idp.getSLOLocation(idp.getBindingType()).getLocation());

    DateTime now = new DateTime();
    logoutRequest.setIssueInstant(now);
    logoutRequest.setNotOnOrAfter(now.plusMinutes(5));

    Issuer issuer = new IssuerBuilder().buildObject();
    issuer.setValue(spEntityID);
    logoutRequest.setIssuer(issuer);

    NameID nameID = new NameIDBuilder().buildObject();
    nameID.setFormat((String) consumer.getJwtClaims().getClaim(JWT_CLAIM_NAMEID_FORMAT));
    nameID.setValue((String) consumer.getJwtClaims().getClaim(JWT_CLAIM_NAMEID_VALUE));
    logoutRequest.setNameID(nameID);

    SessionIndex sessionIndex = new SessionIndexBuilder().buildObject();
    sessionIndex.setSessionIndex((String) consumer.getJwtClaims().getClaim(JWT_CLAIM_SESSIONINDEX));
    logoutRequest.getSessionIndexes().add(sessionIndex);

    SAML2RequestTO requestTO = new SAML2RequestTO();
    requestTO.setIdpServiceAddress(logoutRequest.getDestination());
    requestTO.setBindingType(idp.getBindingType());
    try {
        // 3. generate relay state as JWT
        Map<String, Object> claims = new HashMap<>();
        claims.put(JWT_CLAIM_IDP_DEFLATE,
                idp.getBindingType() == SAML2BindingType.REDIRECT ? true : idp.isUseDeflateEncoding());
        Pair<String, Date> relayState = accessTokenDataBinder.generateJWT(
                SecureRandomUtils.generateRandomUUID().toString(),
                logoutRequest.getID(), JWT_RELAY_STATE_DURATION, claims);
        requestTO.setRelayState(relayState.getLeft());

        // 4. sign and encode AuthnRequest
        switch (idp.getBindingType()) {
            case REDIRECT:
                requestTO.setContent(SAML2ReaderWriter.encode(logoutRequest, true));
                requestTO.setSignAlg(saml2rw.getSigAlgo());
                requestTO.setSignature(saml2rw.sign(requestTO.getContent(), requestTO.getRelayState()));
                break;

            case POST:
            default:
                saml2rw.sign(logoutRequest);
                requestTO.setContent(SAML2ReaderWriter.encode(logoutRequest, idp.isUseDeflateEncoding()));
        }
    } catch (Exception e) {
        LOG.error("While generating LogoutRequest", e);
        SyncopeClientException sce = SyncopeClientException.build(ClientExceptionType.Unknown);
        sce.getElements().add(e.getMessage());
        throw sce;
    }

    return requestTO;
}
 
Example #12
Source File: SAML2IdPLogic.java    From syncope with Apache License 2.0 4 votes vote down vote up
private List<SAML2IdPTO> importIdPs(final InputStream input) throws Exception {
    List<EntityDescriptor> idpEntityDescriptors = new ArrayList<>();

    Element root = OpenSAMLUtil.getParserPool().parse(new InputStreamReader(input)).getDocumentElement();
    if (SAMLConstants.SAML20MD_NS.equals(root.getNamespaceURI())
            && EntityDescriptor.DEFAULT_ELEMENT_LOCAL_NAME.equals(root.getLocalName())) {

        idpEntityDescriptors.add((EntityDescriptor) OpenSAMLUtil.fromDom(root));
    } else if (SAMLConstants.SAML20MD_NS.equals(root.getNamespaceURI())
            && EntitiesDescriptor.DEFAULT_ELEMENT_LOCAL_NAME.equals(root.getLocalName())) {

        NodeList children = root.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            Node child = children.item(i);
            if (SAMLConstants.SAML20MD_NS.equals(child.getNamespaceURI())
                    && EntityDescriptor.DEFAULT_ELEMENT_LOCAL_NAME.equals(child.getLocalName())) {

                NodeList descendants = child.getChildNodes();
                for (int j = 0; j < descendants.getLength(); j++) {
                    Node descendant = descendants.item(j);
                    if (SAMLConstants.SAML20MD_NS.equals(descendant.getNamespaceURI())
                            && IDPSSODescriptor.DEFAULT_ELEMENT_LOCAL_NAME.equals(descendant.getLocalName())) {

                        idpEntityDescriptors.add((EntityDescriptor) OpenSAMLUtil.fromDom((Element) child));
                    }
                }
            }
        }
    }

    List<SAML2IdPTO> result = new ArrayList<>(idpEntityDescriptors.size());
    for (EntityDescriptor idpEntityDescriptor : idpEntityDescriptors) {
        SAML2IdPTO idpTO = new SAML2IdPTO();
        idpTO.setEntityID(idpEntityDescriptor.getEntityID());
        idpTO.setName(idpEntityDescriptor.getEntityID());
        idpTO.setUseDeflateEncoding(false);

        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            SAML2ReaderWriter.write(new OutputStreamWriter(baos), idpEntityDescriptor, false);
            idpTO.setMetadata(Base64.getEncoder().encodeToString(baos.toByteArray()));
        }

        ItemTO connObjectKeyItem = new ItemTO();
        connObjectKeyItem.setIntAttrName("username");
        connObjectKeyItem.setExtAttrName(NameID.DEFAULT_ELEMENT_LOCAL_NAME);
        idpTO.setConnObjectKeyItem(connObjectKeyItem);

        SAML2IdPEntity idp = cache.put(idpEntityDescriptor, idpTO);
        if (idp.getSSOLocation(SAML2BindingType.POST) != null) {
            idpTO.setBindingType(SAML2BindingType.POST);
        } else if (idp.getSSOLocation(SAML2BindingType.REDIRECT) != null) {
            idpTO.setBindingType(SAML2BindingType.REDIRECT);
        } else {
            throw new IllegalArgumentException("Neither POST nor REDIRECT artifacts supported by " + idp.getId());
        }

        result.add(idpTO);
    }

    return result;
}
 
Example #13
Source File: SAMLGroupIDExtractorImplTest.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
@Test
public void getGroupingIdentifiersTestCase() throws ParserConfigurationException, IOException, SAXException,
        UnmarshallingException, UserStoreException {

    SAMLGroupIDExtractorImpl samlGroupIDExtractor = new SAMLGroupIDExtractorImplWrapper();

    Mockito.when(DocumentBuilderFactory.newInstance()).thenReturn(documentBuilderFactory);
    Mockito.when(documentBuilderFactory.newDocumentBuilder()).thenReturn(documentBuilder);
    Mockito.when(documentBuilder.parse(samlGroupIDExtractor.getByteArrayInputStream("test"))).
            thenReturn(document);
    Mockito.when(document.getDocumentElement()).thenReturn(element);

    PowerMockito.mockStatic(XMLObjectProviderRegistrySupport.class);
    Response response = Mockito.mock(Response.class);
    List<Assertion> assertion = new ArrayList();
    Subject subject = Mockito.mock(Subject.class);
    NameID nameID = Mockito.mock(NameID.class);
    Assertion assertion1 = Mockito.mock(Assertion.class);
    assertion.add(assertion1);
    Mockito.when(XMLObjectProviderRegistrySupport.getUnmarshallerFactory()).thenReturn(unmarshallerFactory);
    Mockito.when(unmarshallerFactory.getUnmarshaller(element)).thenReturn(unmarshaller);
    Mockito.when(unmarshaller.unmarshall(element)).thenReturn(response);
    Mockito.when(response.getAssertions()).thenReturn(assertion);
    Mockito.when(assertion.get(0).getSubject()).thenReturn(subject);
    Mockito.when(subject.getNameID()).thenReturn(nameID);
    Mockito.when(nameID.getValue()).thenReturn("user");

    ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    RealmService realmService = Mockito.mock(RealmService.class);
    UserRealm userRealm = Mockito.mock(UserRealm.class);
    TenantManager tenantManager = Mockito.mock(TenantManager.class);
    UserStoreManager userStoreManager = Mockito.mock(UserStoreManager.class);
    APIManagerConfigurationService apiManagerConfigService = Mockito.mock(APIManagerConfigurationService.class);
    APIManagerConfiguration apiManagerConfig = Mockito.mock(APIManagerConfiguration.class);
    Mockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
    Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
    Mockito.when(serviceReferenceHolder.getAPIManagerConfigurationService()).thenReturn(apiManagerConfigService);
    Mockito.when(apiManagerConfigService.getAPIManagerConfiguration()).thenReturn(apiManagerConfig);
    Mockito.when(apiManagerConfig.getFirstProperty(APIConstants.API_STORE_GROUP_EXTRACTOR_CLAIM_URI)).
            thenReturn("http://wso2.org/claims/organization");

    Mockito.when(tenantManager.getTenantId("carbon.super")).thenReturn(1234);
    Mockito.when(realmService.getTenantUserRealm(1234)).thenReturn(userRealm);
    Mockito.when(userRealm.getUserStoreManager()).thenReturn(userStoreManager);
    Mockito.when(userStoreManager.getUserClaimValue(MultitenantUtils.
            getTenantAwareUsername("user"), "http://wso2.org/claims/organization", null)).
            thenReturn("organization");

    Assert.assertEquals("carbon.super/organization",samlGroupIDExtractor.
            getGroupingIdentifiers("test"));
}
 
Example #14
Source File: SAMLGroupIDExtractorImplTest.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
@Test
public void getGroupingIdentifierListTestCase() throws ParserConfigurationException, IOException, SAXException,
        UnmarshallingException, UserStoreException {

    String claim = "http://wso2.org/claims/organization";
    String organizationValue = "organization";
    SAMLGroupIDExtractorImpl samlGroupIDExtractor = new SAMLGroupIDExtractorImplWrapper();
    Mockito.when(DocumentBuilderFactory.newInstance()).thenReturn(documentBuilderFactory);
    Mockito.when(documentBuilderFactory.newDocumentBuilder()).
            thenReturn(documentBuilder);
    Mockito.when(documentBuilder.parse(samlGroupIDExtractor.getByteArrayInputStream("test"))).
            thenReturn(document);
    Mockito.when(document.getDocumentElement()).thenReturn(element);
    ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    PowerMockito.mockStatic(XMLObjectProviderRegistrySupport.class);
    Response response = Mockito.mock(Response.class);
    List<Assertion> assertion = new ArrayList();
    Subject subject = Mockito.mock(Subject.class);
    NameID nameID = Mockito.mock(NameID.class);
    Assertion assertion1 = Mockito.mock(Assertion.class);
    assertion.add(assertion1);
    Mockito.when(XMLObjectProviderRegistrySupport.getUnmarshallerFactory()).thenReturn(unmarshallerFactory);
    Mockito.when(unmarshallerFactory.getUnmarshaller(element)).thenReturn(unmarshaller);
    Mockito.when(unmarshaller.unmarshall(element)).thenReturn(response);
    Mockito.when(response.getAssertions()).thenReturn(assertion);
    Mockito.when(assertion.get(0).getSubject()).thenReturn(subject);
    Mockito.when(subject.getNameID()).thenReturn(nameID);
    Mockito.when(nameID.getValue()).thenReturn("user");
    System.setProperty(APIConstants.READ_ORGANIZATION_FROM_SAML_ASSERTION, "true");
    APIManagerConfigurationService apiManagerConfigService = Mockito.mock(APIManagerConfigurationService.class);
    Mockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    Mockito.when(serviceReferenceHolder.getAPIManagerConfigurationService()).thenReturn(apiManagerConfigService);
    APIManagerConfiguration apiManagerConfig = Mockito.mock(APIManagerConfiguration.class);
    Mockito.when(apiManagerConfigService.getAPIManagerConfiguration()).thenReturn(apiManagerConfig);
    Mockito.when(apiManagerConfig.getFirstProperty(APIConstants.API_STORE_GROUP_EXTRACTOR_CLAIM_URI)).
            thenReturn("http://wso2.org/claims/organization");

    System.setProperty("carbon.home", "");
    PrivilegedCarbonContext carbonContext;
    carbonContext = Mockito.mock(PrivilegedCarbonContext.class);
    PowerMockito.mockStatic(PrivilegedCarbonContext.class);

    PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(carbonContext);
    PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()).thenReturn(-1234);
    PowerMockito.doNothing().when(carbonContext).setTenantDomain("carbon.super", true);

    AttributeStatement mockAttributeStatement = PowerMockito.mock(AttributeStatement.class);
    List<AttributeStatement> attributeStatementList = Collections.singletonList(mockAttributeStatement);
    PowerMockito.when(assertion1.getAttributeStatements()).thenReturn(attributeStatementList);

    Attribute mockAttribute = PowerMockito.mock(Attribute.class);
    List<Attribute> attributesList = Collections.singletonList(mockAttribute);
    PowerMockito.when(mockAttributeStatement.getAttributes()).thenReturn(attributesList);

    XMLObject rawAttribute = PowerMockito.mock(XMLObject.class);
    PowerMockito.when(rawAttribute.toString()).thenReturn(organizationValue);
    List<XMLObject> mockedAttributeValues = Collections.singletonList(rawAttribute);
    AttributedStringImpl mockedAttributedStringImpl = new AttributedStringImpl("nameSpaceURI", "elementLocalName",
            "namespacePrefix");
    String sampleAttrValue = "MockedAuthParamSampleAttribute";
    mockedAttributedStringImpl.setValue(sampleAttrValue);
    List<XMLObject> mockedXSSAttributeValues = Collections.singletonList((XMLObject) mockedAttributedStringImpl);
    XSAnyImpl mockedXSAnyImpl = Mockito.mock(XSAnyImpl.class);
    PowerMockito.when(mockedXSAnyImpl.getTextContent()).thenReturn(sampleAttrValue);
    List<XMLObject> mockedXSAnyImplAttributeValues = Collections.singletonList((XMLObject) mockedXSAnyImpl);
    List<XMLObject> multiMockedAttributeValues = Arrays.asList(rawAttribute, PowerMockito.mock(XMLObject.class));
    AuthenticatorsConfiguration.AuthenticatorConfig mockedAuthenticatorConfig = Mockito
            .mock(AuthenticatorsConfiguration.AuthenticatorConfig.class);
    PowerMockito.when(mockAttribute.getAttributeValues())
            .thenReturn(mockedAttributeValues, multiMockedAttributeValues, mockedXSSAttributeValues,
                    mockedXSAnyImplAttributeValues);

    PowerMockito.mockStatic(AuthenticatorsConfiguration.class);
    AuthenticatorsConfiguration mockedAuthenticatorsConfiguration = PowerMockito
            .mock(AuthenticatorsConfiguration.class);
    PowerMockito.when(AuthenticatorsConfiguration.getInstance()).thenReturn(mockedAuthenticatorsConfiguration);
    Map<String, String> mockedConfigParameters = new HashMap<String, String>();
    mockedConfigParameters.put(APIConstants.ORGANIZATION_CLAIM_ATTRIBUTE, claim);
    PowerMockito.when(mockedAuthenticatorConfig.getParameters()).thenReturn(mockedConfigParameters);
    PowerMockito.when(mockedAuthenticatorsConfiguration
            .getAuthenticatorConfig(APIConstants.SAML2_SSO_AUTHENTICATOR_NAME))
            .thenReturn(mockedAuthenticatorConfig);
    PowerMockito.when(mockAttribute.getName()).thenReturn(claim);

    String[] organizations = samlGroupIDExtractor.
            getGroupingIdentifierList("test");
    Assert.assertEquals(organizationValue, organizations[0]);
}
 
Example #15
Source File: SamlUtil.java    From armeria with Apache License 2.0 4 votes vote down vote up
/**
 * Returns a {@link NameID} that its name format equals to the specified {@code expectedFormat},
 * from the {@link Response}.
 */
@Nullable
public static NameID getNameId(Response response, SamlNameIdFormat expectedFormat) {
    return getNameId(response, nameId -> nameId.getFormat().equals(expectedFormat.urn()));
}
 
Example #16
Source File: SamlResponseCreator.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
private Assertion createSAML2Assertion(RequestContext context, Idp idp, SamlAssertionWrapper receivedToken,
                                       String requestID, String requestIssuer,
                                       String remoteAddr, String racs) throws Exception {
    // Create an AuthenticationAssertion
    SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
    String issuer = isUseRealmForIssuer() ? idp.getRealm() : idp.getIdpUrl().toString();
    callbackHandler.setIssuer(issuer);
    callbackHandler.setSubject(receivedToken.getSaml2().getSubject());

    // Test Subject against received Subject (if applicable)
    SAMLAuthnRequest authnRequest =
        (SAMLAuthnRequest)WebUtils.getAttributeFromFlowScope(context, IdpConstants.SAML_AUTHN_REQUEST);
    if (authnRequest.getSubjectNameId() != null && receivedToken.getSaml2().getSubject().getNameID() != null) {
        NameID issuedNameId = receivedToken.getSaml2().getSubject().getNameID();
        if (!authnRequest.getSubjectNameId().equals(issuedNameId.getValue())) {
            LOG.debug("Received NameID value of {} does not match issued value {}",
                      authnRequest.getSubjectNameId(), issuedNameId.getValue());
            throw new ProcessingException(ProcessingException.TYPE.INVALID_REQUEST);
        }
    }

    // Subject Confirmation Data
    SubjectConfirmationDataBean subjectConfirmationData = new SubjectConfirmationDataBean();
    subjectConfirmationData.setAddress(remoteAddr);
    subjectConfirmationData.setInResponseTo(requestID);
    subjectConfirmationData.setNotAfter(new DateTime().plusMinutes(5));
    subjectConfirmationData.setRecipient(racs);
    callbackHandler.setSubjectConfirmationData(subjectConfirmationData);

    // Audience Restriction
    ConditionsBean conditions = new ConditionsBean();
    conditions.setTokenPeriodMinutes(5);

    AudienceRestrictionBean audienceRestriction = new AudienceRestrictionBean();
    audienceRestriction.setAudienceURIs(Collections.singletonList(requestIssuer));
    conditions.setAudienceRestrictions(Collections.singletonList(audienceRestriction));
    callbackHandler.setConditions(conditions);

    // Attributes
    callbackHandler.setAttributeStatements(receivedToken.getSaml2().getAttributeStatements());

    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(callbackHandler, samlCallback);
    SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);

    Crypto issuerCrypto = CertsUtils.getCryptoFromCertificate(idp.getCertificate());
    assertion.signAssertion(issuerCrypto.getDefaultX509Identifier(), idp.getCertificatePassword(),
                            issuerCrypto, false);

    return assertion.getSaml2();
}
 
Example #17
Source File: MockSamlIdpServer.java    From deprecated-security-advanced-modules with Apache License 2.0 4 votes vote down vote up
private NameID createNameID(String format, String value) {
    NameID nameID = createSamlElement(NameID.class);
    nameID.setFormat(format);
    nameID.setValue(value);
    return nameID;
}
 
Example #18
Source File: DefaultSAMLPRequestBuilder.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
@Override
public LogoutRequest createLogoutRequest(
    String issuerId,
    String reason,
    SamlAssertionWrapper authenticatedAssertion
) throws Exception {
    Issuer issuer =
        SamlpRequestComponentBuilder.createIssuer(issuerId);

    NameID nameID = null;
    List<String> sessionIndices = new ArrayList<>();

    if (authenticatedAssertion != null) {
        if (authenticatedAssertion.getSaml2() != null) {
            org.opensaml.saml.saml2.core.Subject subject =
                authenticatedAssertion.getSaml2().getSubject();
            if (subject != null && subject.getNameID() != null) {
                nameID = subject.getNameID();
            }
        }

        if (nameID != null) {
            nameID.detach();
        }

        List<AuthnStatement> authnStatements =
            authenticatedAssertion.getSaml2().getAuthnStatements();
        if (authnStatements != null && !authnStatements.isEmpty()) {
            for (AuthnStatement authnStatement : authnStatements) {
                if (authnStatement.getSessionIndex() != null) {
                    sessionIndices.add(authnStatement.getSessionIndex());
                }
            }
        }
    }

    //CHECKSTYLE:OFF
    return SamlpRequestComponentBuilder.createLogoutRequest(
        issuer,
        reason,
        nameID,
        sessionIndices
    );
}
 
Example #19
Source File: CustomSAMLPRequestBuilder.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
@Override
public LogoutRequest createLogoutRequest(
    String issuerId,
    String reason,
    SamlAssertionWrapper authenticatedAssertion
) throws Exception {
    Issuer issuer =
        SamlpRequestComponentBuilder.createIssuer(issuerId);

    NameID nameID = null;
    List<String> sessionIndices = new ArrayList<>();

    if (authenticatedAssertion != null) {
        if (authenticatedAssertion.getSaml2() != null) {
            org.opensaml.saml.saml2.core.Subject subject =
                authenticatedAssertion.getSaml2().getSubject();
            if (subject != null && subject.getNameID() != null) {
                nameID = subject.getNameID();
            }
        }

        if (nameID != null) {
            nameID.detach();
        }

        List<AuthnStatement> authnStatements =
            authenticatedAssertion.getSaml2().getAuthnStatements();
        if (authnStatements != null && !authnStatements.isEmpty()) {
            for (AuthnStatement authnStatement : authnStatements) {
                if (authnStatement.getSessionIndex() != null) {
                    sessionIndices.add(authnStatement.getSessionIndex());
                }
            }
        }
    }

    //CHECKSTYLE:OFF
    return SamlpRequestComponentBuilder.createLogoutRequest(
        issuer,
        reason,
        nameID,
        sessionIndices
    );
}
 
Example #20
Source File: AbstractSaml20ObjectBuilder.java    From springboot-shiro-cas-mybatis with MIT License 3 votes vote down vote up
/**
 * Gets name id.
 *
 * @param nameIdFormat the name id format
 * @param nameIdValue the name id value
 * @return the name iD
 */
protected NameID getNameID(final String nameIdFormat, final String nameIdValue) {
    final NameID nameId = newSamlObject(NameID.class);
    nameId.setFormat(nameIdFormat);
    nameId.setValue(nameIdValue);
    return nameId;
}