org.springframework.security.saml.SAMLCredential Java Examples
The following examples show how to use
org.springframework.security.saml.SAMLCredential.
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: UserDetailsService.java From blackduck-alert with Apache License 2.0 | 6 votes |
@Override public Object loadUserBySAML(SAMLCredential credential) throws UsernameNotFoundException { String userName = credential.getNameID().getValue(); String emailAddress = StringUtils.contains(userName, "@") ? userName : null; String[] alertRoles = credential.getAttributeAsStringArray(authoritiesPopulator.getSAMLRoleAttributeName("AlertRoles")); Set<UserRoleModel> roles = Set.of(); if (alertRoles != null) { Set<String> roleNames = authoritiesPopulator.addAdditionalRoleNames(userName, Arrays.stream(alertRoles).collect(Collectors.toSet()), false); roles = roleNames.stream() .map(UserRoleModel::of) .collect(Collectors.toSet()); } UserModel userModel = UserModel.newUser(userName, "", emailAddress, AuthenticationType.SAML, roles, true); return new UserPrincipal(userModel); }
Example #2
Source File: UserDetailsServiceTest.java From blackduck-alert with Apache License 2.0 | 6 votes |
@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 #3
Source File: UserDetailsServiceTest.java From blackduck-alert with Apache License 2.0 | 6 votes |
@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 #4
Source File: UserDetailsServiceTest.java From blackduck-alert with Apache License 2.0 | 6 votes |
@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 #5
Source File: InsightsAuthenticationTokenUtils.java From Insights with Apache License 2.0 | 6 votes |
/** * used to create AbstractAuthenticationToken for SAML data * * @param request * @param response * @return */ public Authentication authenticationSAMLData(HttpServletRequest request, HttpServletResponse response) { Log.debug(" Inside authenticationSAMLData , url ==== {} ", request.getRequestURI()); String auth_token = extractAndValidateAuthToken(request, response); SecurityContext context = SecurityContextHolder.getContext(); Authentication auth = context.getAuthentication(); if (auth != null) { SAMLCredential credentials = (SAMLCredential) auth.getCredentials(); InsightsAuthenticationToken jwtAuthenticationToken = new InsightsAuthenticationToken(auth_token, auth.getDetails(), credentials, auth.getAuthorities()); return jwtAuthenticationToken; } else { AuthenticationUtils.setResponseMessage(response, AuthenticationUtils.SECURITY_CONTEXT_CODE, "Authentication not successful ,Please relogin "); return null; } }
Example #6
Source File: SAMLUserDetailsServiceImpl.java From spring-boot-security-saml-sample with Apache License 2.0 | 6 votes |
public Object loadUserBySAML(SAMLCredential credential) throws UsernameNotFoundException { // The method is supposed to identify local account of user referenced by // data in the SAML assertion and return UserDetails object describing the user. String userID = credential.getNameID().getValue(); LOG.info(userID + " is logged in"); List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); GrantedAuthority authority = new SimpleGrantedAuthority("ROLE_USER"); authorities.add(authority); // In a real scenario, this implementation has to locate user in a arbitrary // dataStore based on information present in the SAMLCredential and // returns such a date in a form of application specific UserDetails object. return new User(userID, "<abc123>", true, true, true, true, authorities); }
Example #7
Source File: SAMLUserDetailsService.java From kylin with Apache License 2.0 | 6 votes |
@Override public Object loadUserBySAML(SAMLCredential samlCredential) throws UsernameNotFoundException { final String userEmail = samlCredential.getAttributeAsString("email"); logger.debug("samlCredential.email:" + userEmail); final String userName = userEmail.substring(0, userEmail.indexOf("@")); UserDetails userDetails = null; try { userDetails = ldapUserDetailsService.loadUserByUsername(userName); if (userDetails instanceof LdapUserDetailsImpl) { LdapUserDetailsImpl.Essence essence = new LdapUserDetailsImpl.Essence(); essence.setDn(((LdapUserDetailsImpl) userDetails).getDn()); essence.setUsername(userEmail); essence.setPassword(userDetails.getPassword()); essence.setAuthorities(userDetails.getAuthorities()); essence.setTimeBeforeExpiration(((LdapUserDetailsImpl) userDetails).getTimeBeforeExpiration()); essence.setGraceLoginsRemaining(((LdapUserDetailsImpl) userDetails).getGraceLoginsRemaining()); userDetails = essence.createUserDetails(); } } catch (org.springframework.security.core.userdetails.UsernameNotFoundException e) { logger.error("User not found in LDAP, check whether he/she has been added to the groups.", e); } logger.debug("userDeail by search ldap with '" + userName + "' is: " + userDetails); return userDetails; }
Example #8
Source File: Auth0SSODemoApplication.java From spring-boot-security-saml-samples with MIT License | 6 votes |
@Bean public SAMLUserDetailsService userDetailsService() { return new SAMLUserDetailsService() { @Override public Object loadUserBySAML(SAMLCredential samlCredential) throws UsernameNotFoundException { return new SAMLUserDetails(samlCredential) { @Override public Map<String, String> getAttributes() { return samlCredential.getAttributes().stream() .collect(Collectors.toMap(Attribute::getName, this::getValue)); } private String getValue(Attribute attribute) { return Optional.ofNullable(getAttribute(attribute.getName())).orElse(""); } }; } }; }
Example #9
Source File: SimpleSAMLUserDetailsServiceTest.java From spring-boot-security-saml with MIT License | 6 votes |
@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 #10
Source File: SAMLUserDetailsTest.java From spring-boot-security-saml with MIT License | 6 votes |
@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 #11
Source File: SAMLSimpleUserDetailsService.java From kylin-on-parquet-v2 with Apache License 2.0 | 5 votes |
@Override public Object loadUserBySAML(SAMLCredential samlCredential) throws UsernameNotFoundException { final String userEmail = samlCredential.getAttributeAsString("email"); logger.debug("samlCredential.email:" + userEmail); final String userName = userEmail.substring(0, userEmail.indexOf("@")); KylinUserManager userManager = KylinUserManager.getInstance(KylinConfig.getInstanceFromEnv()); ManagedUser existUser = userManager.get(userName); // create if not exists if (existUser == null) { ManagedUser user = new ManagedUser(userName, NO_EXISTENCE_PASSWORD, true, defaultAuthorities); userManager.update(user); } return userManager.get(userName); }
Example #12
Source File: SAMLUserDetailsServiceImplTest.java From spring-boot-security-saml-sample with Apache License 2.0 | 5 votes |
@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 #13
Source File: SAMLSimpleUserDetailsService.java From kylin with Apache License 2.0 | 5 votes |
@Override public Object loadUserBySAML(SAMLCredential samlCredential) throws UsernameNotFoundException { final String userEmail = samlCredential.getAttributeAsString("email"); logger.debug("samlCredential.email:" + userEmail); KylinUserManager userManager = KylinUserManager.getInstance(KylinConfig.getInstanceFromEnv()); ManagedUser existUser = userManager.get(userEmail); // create if not exists if (existUser == null) { ManagedUser user = new ManagedUser(userEmail, NO_EXISTENCE_PASSWORD, true, defaultAuthorities); userManager.update(user); } return userManager.get(userEmail); }
Example #14
Source File: SAMLConfigurerProfileConsumerTests.java From spring-security-saml-dsl with MIT License | 5 votes |
private SAMLCredential stubSAMLCredential() { return new SAMLCredential( mock(NameID.class), mock(Assertion.class), "entity", "local"); }
Example #15
Source File: SAMLUserDetailsServiceImpl.java From spring-tsers-auth with Apache License 2.0 | 5 votes |
public Object loadUserBySAML(SAMLCredential credential) throws UsernameNotFoundException { XSAnyImpl uid = (XSAnyImpl) credential.getAttributes().stream() .filter(a -> a.getFriendlyName().equals("uid")) .findFirst(). orElseThrow(() -> new UsernameNotFoundException("uid not found from assertion")) .getAttributeValues().get(0); List<GrantedAuthority> authorities = new ArrayList<>(); return new User(uid.getTextContent(), "", true, true, true, true, authorities); }
Example #16
Source File: SAMLUserDetailsService.java From kylin-on-parquet-v2 with Apache License 2.0 | 5 votes |
@Override public Object loadUserBySAML(SAMLCredential samlCredential) throws UsernameNotFoundException { final String userEmail = samlCredential.getAttributeAsString("email"); logger.debug("samlCredential.email:" + userEmail); final String userName = userEmail.substring(0, userEmail.indexOf("@")); UserDetails userDetails = null; try { userDetails = ldapUserDetailsService.loadUserByUsername(userName); } catch (org.springframework.security.core.userdetails.UsernameNotFoundException e) { logger.error("User not found in LDAP, check whether he/she has been added to the groups.", e); } logger.debug("userDeail by search ldap with '" + userName + "' is: " + userDetails); return userDetails; }
Example #17
Source File: SimpleSAMLUserDetailsService.java From spring-boot-security-saml with MIT License | 4 votes |
@Override public Object loadUserBySAML(SAMLCredential credential) throws UsernameNotFoundException { return new SAMLUserDetails(credential); }
Example #18
Source File: SAMLUserDetails.java From spring-boot-security-saml-samples with MIT License | 4 votes |
public SAMLUserDetails(SAMLCredential samlCredential) { this.samlCredential = samlCredential; }
Example #19
Source File: SAMLUserDetailsServiceImpl.java From spring-boot-security-saml-samples with MIT License | 4 votes |
public Object loadUserBySAML(SAMLCredential credential) throws UsernameNotFoundException { log.info("Login received for user {}", credential.getNameID().getValue()); return new SAMLUserDetails(credential); }
Example #20
Source File: EppnSamlFilter.java From sakai with Educational Community License v2.0 | 4 votes |
@Override public Object loadUserBySAML(SAMLCredential cred) throws UsernameNotFoundException { // https://www.incommon.org/federation/attributesummary.html return cred.getAttributeAsString("urn:oid:1.3.6.1.4.1.5923.1.1.1.6"); }
Example #21
Source File: UpnSamlFilter.java From sakai with Educational Community License v2.0 | 4 votes |
@Override public Object loadUserBySAML(SAMLCredential cred) throws UsernameNotFoundException { // https://www.incommon.org/federation/attributesummary.html return cred.getAttributeAsString("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn"); }
Example #22
Source File: SAMLUserDetails.java From spring-boot-security-saml with MIT License | 4 votes |
public SAMLUserDetails(SAMLCredential samlCredential) { this.samlCredential = samlCredential; }
Example #23
Source File: UserDetailsService.java From Insights with Apache License 2.0 | 4 votes |
@RequestMapping(value = "/insightsso/getUserDetail", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public @ResponseBody JsonObject getUserDetail() { log.debug("Inside getUserDetail"); Map<String, String> headersGrafana = new HashMap<String, String>(); JsonObject jsonResponse = new JsonObject(); try { SecurityContext context = SecurityContextHolder.getContext(); Authentication auth = context.getAuthentication(); SAMLCredential credentials = (SAMLCredential) auth.getCredentials(); Object principal = auth.getPrincipal(); String userid = credentials.getNameID().getValue(); String givenname = credentials .getAttributeAsString("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname"); headersGrafana.put(AuthenticationUtils.GRAFANA_WEBAUTH_USERKEY, userid); headersGrafana.put(AuthenticationUtils.GRAFANA_WEBAUTH_USERKEY_NAME, userid); headersGrafana.put(AuthenticationUtils.HEADER_COOKIES_KEY, "username=" + userid); String grafanaCurrentOrg = getGrafanaCurrentOrg(headersGrafana); jsonResponse.addProperty("grafanaOrg", grafanaCurrentOrg); String grafanaCurrentOrgRole = getCurrentOrgRole(headersGrafana, grafanaCurrentOrg); jsonResponse.addProperty("grafanaRole", grafanaCurrentOrgRole); jsonResponse.addProperty("insights-sso-token", userid); jsonResponse.addProperty("insights-sso-givenname", givenname); jsonResponse.addProperty("postLogoutURL", ApplicationConfigProvider.getInstance().getSingleSignOnConfig().getPostLogoutURL()); String jToken = tokenProviderUtility.createToken(userid); jsonResponse.addProperty("jtoken", jToken); // set Authority to spring context List<GrantedAuthority> updatedAuthorities = new ArrayList<GrantedAuthority>(); updatedAuthorities.add(AuthenticationUtils.getSpringAuthorityRole(grafanaCurrentOrgRole)); Date expDate = new Date(System.currentTimeMillis() + 60 * 60 * 1000); ExpiringUsernameAuthenticationToken autharization = new ExpiringUsernameAuthenticationToken(expDate, principal, auth.getCredentials(), updatedAuthorities); SecurityContextHolder.getContext().setAuthentication(autharization); Authentication auth2 = SecurityContextHolder.getContext().getAuthentication(); auth2.getAuthorities().forEach(a -> log.debug("GrantedAuthority " + a.getAuthority().toString())); httpRequest.setAttribute("responseHeaders", jsonResponse); } catch (Exception e) { log.error("Error in SSO Cookie {} ", e); return PlatformServiceUtil.buildFailureResponse("Error in SSO Cookie " + e); } return PlatformServiceUtil.buildSuccessResponseWithData(jsonResponse); }
Example #24
Source File: SamlUserDetailsServiceImpl.java From Insights with Apache License 2.0 | 4 votes |
@Override public Object loadUserBySAML(SAMLCredential credential) throws UsernameNotFoundException { return new SamlUserDetails(); }
Example #25
Source File: EppnSamlFilter.java From sakai with Educational Community License v2.0 | 4 votes |
@Override public Object loadUserBySAML(SAMLCredential cred) throws UsernameNotFoundException { // https://www.incommon.org/federation/attributesummary.html return cred.getAttributeAsString("urn:oid:1.3.6.1.4.1.5923.1.1.1.6"); }
Example #26
Source File: UpnSamlFilter.java From sakai with Educational Community License v2.0 | 4 votes |
@Override public Object loadUserBySAML(SAMLCredential cred) throws UsernameNotFoundException { // https://www.incommon.org/federation/attributesummary.html return cred.getAttributeAsString("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn"); }