org.opensaml.saml2.core.NameID Java Examples

The following examples show how to use org.opensaml.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: OAuth2SAMLUtil.java    From jam-collaboration-sample with Apache License 2.0 6 votes vote down vote up
public static NameID makeEmailFormatName(final String subjectNameId, final String subjectNameIdFormat, final String subjectNameIdQualifier) {
    NameID nameID = (new NameIDBuilder().buildObject());

    if (subjectNameIdFormat.equals("email")) {
        nameID.setFormat(NameIDType.EMAIL);
    } else if (subjectNameIdFormat.equals("unspecified")) {
        nameID.setFormat(NameIDType.UNSPECIFIED);
    } else {
        throw new IllegalArgumentException("subjectNameIdFormat must be 'email' or 'unspecified'.");
    }
    
    if (subjectNameIdQualifier != null) {
        nameID.setNameQualifier(subjectNameIdQualifier);
    }
    
    nameID.setValue(subjectNameId);
    
    return nameID;
}
 
Example #2
Source File: LogoutRequestUnmarshaller.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject)
        throws UnmarshallingException {
    LogoutRequest req = (LogoutRequest) parentSAMLObject;

    if (childSAMLObject instanceof BaseID) {
        req.setBaseID((BaseID) childSAMLObject);
    } else if (childSAMLObject instanceof NameID) {
        req.setNameID((NameID) childSAMLObject);
    } else if (childSAMLObject instanceof EncryptedID) {
        req.setEncryptedID((EncryptedID) childSAMLObject);
    } else if (childSAMLObject instanceof SessionIndex) {
        req.getSessionIndexes().add((SessionIndex) childSAMLObject);
    } else {
        super.processChildElement(parentSAMLObject, childSAMLObject);
    }
}
 
Example #3
Source File: SubjectConfirmationUnmarshaller.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
protected void processChildElement(XMLObject parentObject, XMLObject childObject) throws UnmarshallingException {
    SubjectConfirmation subjectConfirmation = (SubjectConfirmation) parentObject;

    if (childObject instanceof BaseID) {
        subjectConfirmation.setBaseID((BaseID) childObject);
    } else if (childObject instanceof NameID) {
        subjectConfirmation.setNameID((NameID) childObject);
    } else if (childObject instanceof EncryptedID) {
        subjectConfirmation.setEncryptedID((EncryptedID) childObject);
    } else if (childObject instanceof SubjectConfirmationData) {
        subjectConfirmation.setSubjectConfirmationData((SubjectConfirmationData) childObject);
    } else {
        super.processChildElement(parentObject, childObject);
    }
}
 
Example #4
Source File: AbstractNameIDTypeMarshaller.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
protected void marshallAttributes(XMLObject samlObject, Element domElement) throws MarshallingException {
    NameIDType nameID = (NameIDType) samlObject;

    if (nameID.getNameQualifier() != null) {
        domElement.setAttributeNS(null, NameID.NAME_QUALIFIER_ATTRIB_NAME, nameID.getNameQualifier());
    }

    if (nameID.getSPNameQualifier() != null) {
        domElement.setAttributeNS(null, NameID.SP_NAME_QUALIFIER_ATTRIB_NAME, nameID.getSPNameQualifier());
    }

    if (nameID.getFormat() != null) {
        domElement.setAttributeNS(null, NameID.FORMAT_ATTRIB_NAME, nameID.getFormat());
    }

    if (nameID.getSPProvidedID() != null) {
        domElement.setAttributeNS(null, NameID.SPPROVIDED_ID_ATTRIB_NAME, nameID.getSPProvidedID());
    }
}
 
Example #5
Source File: SubjectUnmarshaller.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
protected void processChildElement(XMLObject parentObject, XMLObject childObject) throws UnmarshallingException {
    Subject subject = (Subject) parentObject;

    if (childObject instanceof BaseID) {
        subject.setBaseID((BaseID) childObject);
    } else if (childObject instanceof NameID) {
        subject.setNameID((NameID) childObject);
    } else if (childObject instanceof EncryptedID) {
        subject.setEncryptedID((EncryptedID) childObject);
    } else if (childObject instanceof SubjectConfirmation) {
        subject.getSubjectConfirmations().add((SubjectConfirmation) childObject);
    } else {
        super.processChildElement(parentObject, childObject);
    }
}
 
Example #6
Source File: SimpleSAMLUserDetailsServiceTest.java    From spring-boot-security-saml with MIT License 6 votes vote down vote up
@Test
public void testAttributes() {
    SAMLCredential samlCredential = mock(SAMLCredential.class);
    NameID nameId = mock(NameID.class);
    when(samlCredential.getNameID()).thenReturn(nameId);
    Attribute attribute = mock(Attribute.class);
    when(attribute.getName()).thenReturn("attr");
    when(samlCredential.getAttributes()).thenReturn(Collections.singletonList(attribute));
    when(samlCredential.getAttribute("attr")).thenReturn(attribute);
    when(samlCredential.getAttributeAsString("attr")).thenReturn("value");
    when(samlCredential.getAttributeAsStringArray("attr")).thenReturn(new String[]{"value"});
    when(nameId.toString()).thenReturn(NameID.UNSPECIFIED);
    SAMLUserDetails details = (SAMLUserDetails) new SimpleSAMLUserDetailsService().loadUserBySAML(samlCredential);
    assertThat(details.getPassword()).isEmpty();
    assertThat(details.isAccountNonExpired()).isTrue();
    assertThat(details.isAccountNonLocked()).isTrue();
    assertThat(details.isCredentialsNonExpired()).isTrue();
    assertThat(details.isEnabled()).isTrue();
    assertThat(details.getAuthorities()).extracting(GrantedAuthority::getAuthority).containsExactly("ROLE_USER");
    assertThat(details.getAttribute("attr")).isEqualTo("value");
    assertThat(details.getAttributeArray("attr")).containsExactly("value");
    assertThat(details.getAttributes()).containsOnlyKeys("attr").containsValue("value");
    assertThat(details.getAttributesArrays()).containsOnlyKeys("attr");
    assertThat(details.getAttributesArrays().get("attr")).containsExactly("value");
}
 
Example #7
Source File: SAMLUserDetailsTest.java    From spring-boot-security-saml with MIT License 6 votes vote down vote up
@Test
public void testAttributes() {
    SAMLCredential samlCredential = mock(SAMLCredential.class);
    NameID nameId = mock(NameID.class);
    when(samlCredential.getNameID()).thenReturn(nameId);
    Attribute attribute = mock(Attribute.class);
    when(attribute.getName()).thenReturn("attr");
    when(samlCredential.getAttributes()).thenReturn(Collections.singletonList(attribute));
    when(samlCredential.getAttribute("attr")).thenReturn(attribute);
    when(samlCredential.getAttributeAsString("attr")).thenReturn("value");
    when(samlCredential.getAttributeAsStringArray("attr")).thenReturn(new String[]{"value"});
    when(nameId.toString()).thenReturn(NameID.UNSPECIFIED);
    SAMLUserDetails details = new SAMLUserDetails(samlCredential);
    assertThat(details.getPassword()).isEmpty();
    assertThat(details.isAccountNonExpired()).isTrue();
    assertThat(details.isAccountNonLocked()).isTrue();
    assertThat(details.isCredentialsNonExpired()).isTrue();
    assertThat(details.isEnabled()).isTrue();
    assertThat(details.getAuthorities()).extracting(GrantedAuthority::getAuthority).containsExactly("ROLE_USER");
    assertThat(details.getAttribute("attr")).isEqualTo("value");
    assertThat(details.getAttributeArray("attr")).containsExactly("value");
    assertThat(details.getAttributes()).containsOnlyKeys("attr").containsValue("value");
    assertThat(details.getAttributesArrays()).containsOnlyKeys("attr");
    assertThat(details.getAttributesArrays().get("attr")).containsExactly("value");
}
 
Example #8
Source File: NameIDMappingRequestUnmarshaller.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject)
        throws UnmarshallingException {
    NameIDMappingRequest req = (NameIDMappingRequest) parentSAMLObject;

    if (childSAMLObject instanceof BaseID) {
        req.setBaseID((BaseID) childSAMLObject);
    } else if (childSAMLObject instanceof NameID) {
        req.setNameID((NameID) childSAMLObject);
    } else if (childSAMLObject instanceof EncryptedID) {
        req.setEncryptedID((EncryptedID) childSAMLObject);
    } else if (childSAMLObject instanceof NameIDPolicy) {
        req.setNameIDPolicy((NameIDPolicy) childSAMLObject);
    } else {
        super.processChildElement(parentSAMLObject, childSAMLObject);
    }
}
 
Example #9
Source File: ManageNameIDRequestUnmarshaller.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject)
        throws UnmarshallingException {
    ManageNameIDRequest req = (ManageNameIDRequest) parentSAMLObject;

    if (childSAMLObject instanceof NameID) {
        req.setNameID((NameID) childSAMLObject);
    } else if (childSAMLObject instanceof EncryptedID) {
        req.setEncryptedID((EncryptedID) childSAMLObject);
    } else if (childSAMLObject instanceof NewID) {
        req.setNewID((NewID) childSAMLObject);
    } else if (childSAMLObject instanceof NewEncryptedID) {
        req.setNewEncryptedID((NewEncryptedID) childSAMLObject);
    } else if (childSAMLObject instanceof Terminate) {
        req.setTerminate((Terminate) childSAMLObject);
    } else {
        super.processChildElement(parentSAMLObject, childSAMLObject);
    }
}
 
Example #10
Source File: SubjectGenerator.java    From MaxKey with Apache License 2.0 6 votes vote down vote up
public Subject generateSubject( 
						String assertionConsumerURL, 
						String inResponseTo, 
						int validInSeconds) {
	
	String nameIdValue =WebContext.getUserInfo().getUsername();
	NameID nameID =builderNameID(nameIdValue,assertionConsumerURL);
	Subject subject =builderSubject(nameID);
	
	String clientAddress=WebContext.getRequestIpAddress(WebContext.getRequest());
	SubjectConfirmation subjectConfirmation =builderSubjectConfirmation(
							assertionConsumerURL,
							inResponseTo,
							validInSeconds,
							clientAddress);

	subject.getSubjectConfirmations().add(subjectConfirmation);
	
	return subject;
}
 
Example #11
Source File: SAML2ArtifactType0004Builder.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Gets the source location used to for the artifacts created by this encoder.
 * 
 * @param requestContext current request context
 * 
 * @return source location used to for the artifacts created by this encoder
 */
protected Endpoint getAcsEndpoint(SAMLMessageContext<SAMLObject, SAMLObject, NameID> requestContext) {
    BasicEndpointSelector selector = new BasicEndpointSelector();
    selector.setEndpointType(ArtifactResolutionService.DEFAULT_ELEMENT_NAME);
    selector.getSupportedIssuerBindings().add(SAMLConstants.SAML2_SOAP11_BINDING_URI);
    selector.setMetadataProvider(requestContext.getMetadataProvider());
    selector.setEntityMetadata(requestContext.getLocalEntityMetadata());
    selector.setEntityRoleMetadata(requestContext.getLocalEntityRoleMetadata());

    Endpoint acsEndpoint = selector.selectEndpoint();

    if (acsEndpoint == null) {
        log.error("No artifact resolution service endpoint defined for the entity "
                + requestContext.getOutboundMessageIssuer());
        return null;
    }

    return acsEndpoint;
}
 
Example #12
Source File: UserDetailsServiceTest.java    From blackduck-alert with Apache License 2.0 6 votes vote down vote up
@Test
public void testValidCredential() {
    SAMLCredential credential = Mockito.mock(SAMLCredential.class);

    NameID nameId = Mockito.mock(NameID.class);
    Mockito.when(nameId.getValue()).thenReturn(USER_NAME);
    Mockito.when(credential.getNameID()).thenReturn(nameId);
    Mockito.when(credential.getAttributeAsString("Name")).thenReturn(USER_NAME);
    Mockito.when(credential.getAttributeAsString("Email")).thenReturn(EMAIL);
    Mockito.when(credential.getAttributeAsStringArray("AlertRoles")).thenReturn(VALID_ROLES);
    UserDetailsService userDetailsService = new UserDetailsService(authoritiesPopulator);
    Object result = userDetailsService.loadUserBySAML(credential);

    assertNotNull(result);
    assertTrue(UserPrincipal.class.isInstance(result));
    UserPrincipal principal = (UserPrincipal) result;
    assertEquals(USER_NAME, principal.getUsername());
    assertTrue(StringUtils.isBlank(principal.getPassword()));
    assertEquals(VALID_ROLES.length, principal.getAuthorities().size());
    List<String> expectedRoles = List.of(VALID_ROLES);
    List<String> actualRoles = principal.getAuthorities().stream().map(GrantedAuthority::getAuthority).map(authority -> StringUtils.remove(authority, UserModel.ROLE_PREFIX)).collect(Collectors.toList());
    assertTrue(expectedRoles.containsAll(actualRoles));
}
 
Example #13
Source File: UserDetailsServiceTest.java    From blackduck-alert with Apache License 2.0 6 votes vote down vote up
@Test
public void testEmptyRoleArray() {
    SAMLCredential credential = Mockito.mock(SAMLCredential.class);
    String[] roles = new String[0];
    NameID nameId = Mockito.mock(NameID.class);
    Mockito.when(nameId.getValue()).thenReturn(USER_NAME);
    Mockito.when(credential.getNameID()).thenReturn(nameId);
    Mockito.when(credential.getAttributeAsString("Name")).thenReturn(USER_NAME);
    Mockito.when(credential.getAttributeAsString("Email")).thenReturn(EMAIL);
    Mockito.when(credential.getAttributeAsStringArray("AlertRoles")).thenReturn(roles);

    UserDetailsService userDetailsService = new UserDetailsService(authoritiesPopulator);
    Object result = userDetailsService.loadUserBySAML(credential);

    assertNotNull(result);
    assertTrue(UserPrincipal.class.isInstance(result));
    UserPrincipal principal = (UserPrincipal) result;
    assertEquals(USER_NAME, principal.getUsername());
    assertTrue(StringUtils.isBlank(principal.getPassword()));
    assertTrue(principal.getAuthorities().isEmpty());
}
 
Example #14
Source File: UserDetailsServiceTest.java    From blackduck-alert with Apache License 2.0 6 votes vote down vote up
@Test
public void testNullRoleArray() {
    SAMLCredential credential = Mockito.mock(SAMLCredential.class);

    NameID nameId = Mockito.mock(NameID.class);
    Mockito.when(nameId.getValue()).thenReturn(USER_NAME);
    Mockito.when(credential.getNameID()).thenReturn(nameId);
    Mockito.when(credential.getAttributeAsString("Name")).thenReturn(USER_NAME);
    Mockito.when(credential.getAttributeAsString("Email")).thenReturn(EMAIL);
    Mockito.when(credential.getAttributeAsStringArray("AlertRoles")).thenReturn(null);

    UserDetailsService userDetailsService = new UserDetailsService(authoritiesPopulator);
    Object result = userDetailsService.loadUserBySAML(credential);

    assertNotNull(result);
    assertTrue(UserPrincipal.class.isInstance(result));
    UserPrincipal principal = (UserPrincipal) result;
    assertEquals(USER_NAME, principal.getUsername());
    assertTrue(StringUtils.isBlank(principal.getPassword()));
    assertTrue(principal.getAuthorities().isEmpty());
}
 
Example #15
Source File: AuthenticationRequestBuilder.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Generate an authentication request with passive support.
 *
 * @return AuthnRequest Object
 * @throws Exception
 */
public AuthnRequest buildAuthenticationRequest(String subjectName, String nameIdPolicyFormat, boolean isPassive)
        throws Exception {

    if (log.isDebugEnabled()) {
        log.debug("Building Authentication Request");
    }
    Util.doBootstrap();
    AuthnRequest authnRequest = (AuthnRequest) Util
            .buildXMLObject(AuthnRequest.DEFAULT_ELEMENT_NAME);
    authnRequest.setID(Util.createID());
    authnRequest.setVersion(SAMLVersion.VERSION_20);
    authnRequest.setIssueInstant(new DateTime());
    authnRequest.setIssuer(buildIssuer());
    authnRequest.setNameIDPolicy(buildNameIDPolicy(nameIdPolicyFormat));
    authnRequest.setIsPassive(isPassive);
    authnRequest.setDestination(Util.getIdentityProviderSSOServiceURL());
    String acs = Util.getAssertionConsumerServiceURL();
    if (acs != null && acs.trim().length() > 0) {
        authnRequest.setAssertionConsumerServiceURL(acs);
    } else {
        authnRequest.setAssertionConsumerServiceURL(CarbonUIUtil.getAdminConsoleURL("").replace("carbon/", "acs"));
    }

    if (subjectName != null) {
        Subject subject = new SubjectBuilder().buildObject();
        NameID nameId = new NameIDBuilder().buildObject();
        nameId.setValue(subjectName);
        nameId.setFormat(NameIdentifier.EMAIL);
        subject.setNameID(nameId);
        authnRequest.setSubject(subject);

    }

    Util.setSignature(authnRequest, XMLSignature.ALGO_ID_SIGNATURE_RSA, new SignKeyDataHolder());

    return authnRequest;
}
 
Example #16
Source File: LogoutRequestBuilder.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Build the logout request
 *
 * @param subject name of the user
 * @param reason  reason for generating logout request.
 * @return LogoutRequest object
 * @throws Exception
 */
public LogoutRequest buildLogoutRequest(String subject, String reason, String sessionIndexStr) throws Exception {
    log.info("Building logout request");
    Util.doBootstrap();
    LogoutRequest logoutReq = new org.opensaml.saml2.core.impl.LogoutRequestBuilder().buildObject();
    logoutReq.setID(Util.createID());
    logoutReq.setDestination(Util.getIdentityProviderSSOServiceURL());

    DateTime issueInstant = new DateTime();
    logoutReq.setIssueInstant(issueInstant);
    logoutReq.setNotOnOrAfter(new DateTime(issueInstant.getMillis() + 5 * 60 * 1000));

    IssuerBuilder issuerBuilder = new IssuerBuilder();
    Issuer issuer = issuerBuilder.buildObject();
    issuer.setValue(Util.getServiceProviderId());
    logoutReq.setIssuer(issuer);

    NameID nameId = new NameIDBuilder().buildObject();
    nameId.setFormat(SAML2SSOAuthenticatorConstants.SAML2_NAME_ID_POLICY_TRANSIENT);
    nameId.setValue(subject);
    logoutReq.setNameID(nameId);

    SessionIndex sessionIndex = new SessionIndexBuilder().buildObject();
    sessionIndex.setSessionIndex(sessionIndexStr);
    logoutReq.getSessionIndexes().add(sessionIndex);

    logoutReq.setReason(reason);

    Util.setSignature(logoutReq, XMLSignature.ALGO_ID_SIGNATURE_RSA, new SignKeyDataHolder());

    return logoutReq;
}
 
Example #17
Source File: SAML2LoginAPIAuthenticatorCmdTest.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
private Response buildMockResponse() throws Exception {
    Response samlMessage = new ResponseBuilder().buildObject();
    samlMessage.setID("foo");
    samlMessage.setVersion(SAMLVersion.VERSION_20);
    samlMessage.setIssueInstant(new DateTime(0));
    Issuer issuer = new IssuerBuilder().buildObject();
    issuer.setValue("MockedIssuer");
    samlMessage.setIssuer(issuer);
    Status status = new StatusBuilder().buildObject();
    StatusCode statusCode = new StatusCodeBuilder().buildObject();
    statusCode.setValue(StatusCode.SUCCESS_URI);
    status.setStatusCode(statusCode);
    samlMessage.setStatus(status);
    Assertion assertion = new AssertionBuilder().buildObject();
    Subject subject = new SubjectBuilder().buildObject();
    NameID nameID = new NameIDBuilder().buildObject();
    nameID.setValue("SOME-UNIQUE-ID");
    nameID.setFormat(NameIDType.PERSISTENT);
    subject.setNameID(nameID);
    assertion.setSubject(subject);
    AuthnStatement authnStatement = new AuthnStatementBuilder().buildObject();
    authnStatement.setSessionIndex("Some Session String");
    assertion.getAuthnStatements().add(authnStatement);
    AttributeStatement attributeStatement = new AttributeStatementBuilder().buildObject();
    assertion.getAttributeStatements().add(attributeStatement);
    samlMessage.getAssertions().add(assertion);
    return samlMessage;
}
 
Example #18
Source File: SAMLConfigurerProfileConsumerTests.java    From spring-security-saml-dsl with MIT License 5 votes vote down vote up
private SAMLCredential stubSAMLCredential() {
	return new SAMLCredential(
			mock(NameID.class),
			mock(Assertion.class),
			"entity",
			"local");
}
 
Example #19
Source File: SubjectGenerator.java    From MaxKey with Apache License 2.0 5 votes vote down vote up
public NameID builderNameID(String value,String strSPNameQualifier){
	//Response/Assertion/Subject/NameID	
	NameID nameID = new NameIDBuilder().buildObject();
	nameID.setValue(value);
	//nameID.setFormat(NameIDType.PERSISTENT);
	nameID.setFormat(NameIDType.UNSPECIFIED);
	//nameID.setSPNameQualifier(strSPNameQualifier);
	
	return nameID;
}
 
Example #20
Source File: SAML2SSOManager.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
protected LogoutRequest buildLogoutRequest(String user, String sessionIdx) throws SSOAgentException {

        LogoutRequest logoutReq = new LogoutRequestBuilder().buildObject();

        logoutReq.setID(SSOAgentUtils.createID());
        logoutReq.setDestination(ssoAgentConfig.getSAML2().getIdPURL());

        DateTime issueInstant = new DateTime();
        logoutReq.setIssueInstant(issueInstant);
        logoutReq.setNotOnOrAfter(new DateTime(issueInstant.getMillis() + 5 * 60 * 1000));

        IssuerBuilder issuerBuilder = new IssuerBuilder();
        Issuer issuer = issuerBuilder.buildObject();
        issuer.setValue(ssoAgentConfig.getSAML2().getSPEntityId());
        logoutReq.setIssuer(issuer);

        NameID nameId = new NameIDBuilder().buildObject();
        nameId.setFormat("urn:oasis:names:tc:SAML:2.0:nameid-format:entity");
        nameId.setValue(user);
        logoutReq.setNameID(nameId);

        SessionIndex sessionIndex = new SessionIndexBuilder().buildObject();
        sessionIndex.setSessionIndex(sessionIdx);
        logoutReq.getSessionIndexes().add(sessionIndex);

        logoutReq.setReason("Single Logout");

        return logoutReq;
    }
 
Example #21
Source File: SAMLUserDetailsServiceImplTest.java    From spring-boot-security-saml-sample with Apache License 2.0 5 votes vote down vote up
@Test
public void testLoadUserBySAML() {
    // given
    NameID mockNameID = mock(NameID.class);
    when(mockNameID.getValue()).thenReturn(USER_NAME);

    SAMLCredential credentialsMock = mock(SAMLCredential.class);
    when(credentialsMock.getNameID()).thenReturn(mockNameID);

    // when
    Object actual = userDetailsService.loadUserBySAML(credentialsMock);

    // / then
    assertNotNull(actual);
    assertTrue(actual instanceof User);

    User user = (User)actual;
    assertEquals(USER_NAME, user.getUsername());
    assertEquals(USER_PASSWORD, user.getPassword());
    assertTrue(user.isEnabled());
    assertTrue(user.isAccountNonExpired());
    assertTrue(user.isCredentialsNonExpired());
    assertTrue(user.isAccountNonLocked());
    assertEquals(1, user.getAuthorities().size());

    List<GrantedAuthority> authorities = new ArrayList<>(user.getAuthorities());
    Object authority = authorities.get(0);

    assertTrue(authority instanceof SimpleGrantedAuthority);
    assertEquals(USER_ROLE, ((SimpleGrantedAuthority)authority).getAuthority());
}
 
Example #22
Source File: LogoutRequestBuilder.java    From carbon-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Build the logout request
 * @param subject name of the user
 * @param reason reason for generating logout request.
 * @return LogoutRequest object
 */
public LogoutRequest buildLogoutRequest(String subject,String sessionIndexId, String reason,
                                        String issuerId) {
    Util.doBootstrap();
    LogoutRequest logoutReq = new org.opensaml.saml2.core.impl.LogoutRequestBuilder().buildObject();
    logoutReq.setID(Util.createID());

    DateTime issueInstant = new DateTime();
    logoutReq.setIssueInstant(issueInstant);
    logoutReq.setNotOnOrAfter(new DateTime(issueInstant.getMillis() + 5 * 60 * 1000));

    IssuerBuilder issuerBuilder = new IssuerBuilder();
    Issuer issuer = issuerBuilder.buildObject();
    issuer.setValue(issuerId);
    logoutReq.setIssuer(issuer);

    NameID nameId = new NameIDBuilder().buildObject();
    nameId.setFormat(SSOConstants.SAML2_NAME_ID_POLICY);
    nameId.setValue(subject);
    logoutReq.setNameID(nameId);

    SessionIndex sessionIndex = new SessionIndexBuilder().buildObject();
    sessionIndex.setSessionIndex(sessionIndexId);
    logoutReq.getSessionIndexes().add(sessionIndex);

    logoutReq.setReason(reason);

    return logoutReq;
}
 
Example #23
Source File: SamlAssertionProducer.java    From saml-generator with Apache License 2.0 5 votes vote down vote up
private Subject createSubject(final String subjectId, final Integer samlAssertionDays) {
	DateTime currentDate = new DateTime();
	if (samlAssertionDays != null)
		currentDate = currentDate.plusDays(samlAssertionDays);
	
	// create name element
	NameIDBuilder nameIdBuilder = new NameIDBuilder(); 
	NameID nameId = nameIdBuilder.buildObject();
	nameId.setValue(subjectId);
	nameId.setFormat("urn:oasis:names:tc:SAML:2.0:nameid-format:persistent");

	SubjectConfirmationDataBuilder dataBuilder = new SubjectConfirmationDataBuilder();
	SubjectConfirmationData subjectConfirmationData = dataBuilder.buildObject();
	subjectConfirmationData.setNotOnOrAfter(currentDate);
	
	SubjectConfirmationBuilder subjectConfirmationBuilder = new SubjectConfirmationBuilder();
	SubjectConfirmation subjectConfirmation = subjectConfirmationBuilder.buildObject();
	subjectConfirmation.setMethod("urn:oasis:names:tc:SAML:2.0:cm:bearer");
	subjectConfirmation.setSubjectConfirmationData(subjectConfirmationData);
	
	// create subject element
	SubjectBuilder subjectBuilder = new SubjectBuilder();
	Subject subject = subjectBuilder.buildObject();
	subject.setNameID(nameId);
	subject.getSubjectConfirmations().add(subjectConfirmation);
	
	return subject;
}
 
Example #24
Source File: SAMLUtils.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public static LogoutRequest buildLogoutRequest(String logoutUrl, String spId, String nameIdString) {
    Issuer issuer = new IssuerBuilder().buildObject();
    issuer.setValue(spId);
    NameID nameID = new NameIDBuilder().buildObject();
    nameID.setValue(nameIdString);
    LogoutRequest logoutRequest = new LogoutRequestBuilder().buildObject();
    logoutRequest.setID(generateSecureRandomId());
    logoutRequest.setDestination(logoutUrl);
    logoutRequest.setVersion(SAMLVersion.VERSION_20);
    logoutRequest.setIssueInstant(new DateTime());
    logoutRequest.setIssuer(issuer);
    logoutRequest.setNameID(nameID);
    return logoutRequest;
}
 
Example #25
Source File: AbstractNameIDTypeUnmarshaller.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException {
    NameIDType nameID = (NameIDType) samlObject;
    if (attribute.getLocalName().equals(NameID.NAME_QUALIFIER_ATTRIB_NAME)) {
        nameID.setNameQualifier(attribute.getValue());
    } else if (attribute.getLocalName().equals(NameID.SP_NAME_QUALIFIER_ATTRIB_NAME)) {
        nameID.setSPNameQualifier(attribute.getValue());
    } else if (attribute.getLocalName().equals(NameID.FORMAT_ATTRIB_NAME)) {
        nameID.setFormat(attribute.getValue());
    } else if (attribute.getLocalName().equals(NameID.SPPROVIDED_ID_ATTRIB_NAME)) {
        nameID.setSPProvidedID(attribute.getValue());
    } else {
        super.processAttribute(samlObject, attribute);
    }
}
 
Example #26
Source File: NameIDMappingResponseUnmarshaller.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject)
        throws UnmarshallingException {
    NameIDMappingResponse resp = (NameIDMappingResponse) parentSAMLObject;

    if (childSAMLObject instanceof NameID) {
        resp.setNameID((NameID) childSAMLObject);
    } else if (childSAMLObject instanceof EncryptedID) {
        resp.setEncryptedID((EncryptedID) childSAMLObject);
    } else {
        super.processChildElement(parentSAMLObject, childSAMLObject);
    }
}
 
Example #27
Source File: DelegateUnmarshaller.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject)
        throws UnmarshallingException {
    Delegate delegate = (Delegate) parentSAMLObject;
    
    if (childSAMLObject instanceof BaseID) {
        delegate.setBaseID((BaseID) childSAMLObject);
    } else if (childSAMLObject instanceof NameID) {
        delegate.setNameID((NameID) childSAMLObject);
    } else if (childSAMLObject instanceof EncryptedID) {
        delegate.setEncryptedID((EncryptedID) childSAMLObject);
    } else {
        super.processChildElement(parentSAMLObject, childSAMLObject);
    }
}
 
Example #28
Source File: SAML2ArtifactType0004Builder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
public SAML2ArtifactType0004 buildArtifact(SAMLMessageContext<SAMLObject, SAMLObject, NameID> requestContext) {
    try {
        IndexedEndpoint acsEndpoint = (IndexedEndpoint) getAcsEndpoint(requestContext);
        if (acsEndpoint == null) {
            return null;
        }

        byte[] endpointIndex = DatatypeHelper.intToByteArray(acsEndpoint.getIndex());
        byte[] trimmedIndex = new byte[2];
        trimmedIndex[0] = endpointIndex[2];
        trimmedIndex[1] = endpointIndex[3];

        MessageDigest sha1Digester = MessageDigest.getInstance("SHA-1");
        byte[] source = sha1Digester.digest(requestContext.getLocalEntityId().getBytes());

        SecureRandom handleGenerator = SecureRandom.getInstance("SHA1PRNG");
        byte[] assertionHandle;
        assertionHandle = new byte[20];
        handleGenerator.nextBytes(assertionHandle);

        return new SAML2ArtifactType0004(trimmedIndex, source, assertionHandle);
    } catch (NoSuchAlgorithmException e) {
        log.error("JVM does not support required cryptography algorithms: SHA-1/SHA1PRNG.", e);
        throw new InternalError("JVM does not support required cryptography algorithms: SHA-1/SHA1PRNG.");
    }
}
 
Example #29
Source File: LogoutRequestImpl.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/** {@inheritDoc} */
public void setNameID(NameID newNameID) {
    nameID = prepareForAssignment(nameID, newNameID);
}
 
Example #30
Source File: DelegateImpl.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/** {@inheritDoc} */
public NameID getNameID() {
    return nameID;
}