org.springframework.security.core.authority.AuthorityUtils Java Examples
The following examples show how to use
org.springframework.security.core.authority.AuthorityUtils.
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: UserDetailService.java From SpringAll with MIT License | 8 votes |
@Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // 模拟一个用户,替代数据库获取逻辑 MyUser user = new MyUser(); user.setUserName(username); user.setPassword(this.passwordEncoder.encode("123456")); // 输出加密后的密码 System.out.println(user.getPassword()); List<GrantedAuthority> authorities = new ArrayList<>(); if (StringUtils.equalsIgnoreCase("mrbird", username)) { authorities = AuthorityUtils.commaSeparatedStringToAuthorityList("admin"); } else { authorities = AuthorityUtils.commaSeparatedStringToAuthorityList("test"); } return new User(username, user.getPassword(), user.isEnabled(), user.isAccountNonExpired(), user.isCredentialsNonExpired(), user.isAccountNonLocked(), authorities); }
Example #2
Source File: JdbcIndexedSessionRepositoryTests.java From spring-session with Apache License 2.0 | 6 votes |
@Test @SuppressWarnings("unchecked") void findByIndexNameAndIndexValuePrincipalIndexNameFound() { String principal = "username"; Authentication authentication = new UsernamePasswordAuthenticationToken(principal, "notused", AuthorityUtils.createAuthorityList("ROLE_USER")); List<Session> saved = new ArrayList<>(2); Session saved1 = this.repository.createSession(); saved1.setAttribute(SPRING_SECURITY_CONTEXT, authentication); saved.add(saved1); Session saved2 = this.repository.createSession(); saved2.setAttribute(SPRING_SECURITY_CONTEXT, authentication); saved.add(saved2); given(this.jdbcOperations.query(isA(String.class), isA(PreparedStatementSetter.class), isA(ResultSetExtractor.class))).willReturn(saved); Map<String, JdbcSession> sessions = this.repository .findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, principal); assertThat(sessions).hasSize(2); verify(this.jdbcOperations, times(1)).query(isA(String.class), isA(PreparedStatementSetter.class), isA(ResultSetExtractor.class)); }
Example #3
Source File: UserConfig.java From base-admin with MIT License | 6 votes |
@Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { //查询用户 SysUserVo sysUserVo = sysUserService.findByLoginName(username).getData(); //查询权限 List<SysUserAuthorityVo> sysUserAuthorityVoList = sysUserAuthorityService.findByUserId(sysUserVo.getUserId()).getData(); StringBuilder authorityList = new StringBuilder(); for (int i = 0; i < sysUserAuthorityVoList.size(); i++) { SysUserAuthorityVo sysUserAuthorityVo = sysUserAuthorityVoList.get(i); authorityList.append(sysUserAuthorityVo.getSysAuthority().getAuthorityName()); if (i != sysUserAuthorityVoList.size() - 1) { authorityList.append(","); } } //查无此用户 if(StringUtils.isEmpty(sysUserVo.getUserId())){ sysUserVo.setLoginName("查无此用户"); sysUserVo.setPassword("查无此用户"); } // 封装用户信息,并返回。参数分别是:用户名,密码,用户权限 return new User(sysUserVo.getLoginName(), sysUserVo.getPassword(), AuthorityUtils.commaSeparatedStringToAuthorityList(authorityList.toString())); }
Example #4
Source File: JwtService.java From hauth-java with MIT License | 6 votes |
public static Authentication getAuthentication(HttpServletRequest request) { // 从Header中拿到token String token = request.getHeader(HEADER_STRING); if (token == null) { token = getTokenFromCookis(request); } if (token != null && !token.isEmpty()) { // 解析 Token Claims claims = Jwts.parser().setSigningKey(SECRET) .parseClaimsJws(token).getBody(); // 获取用户名 String user = claims.get("UserId").toString(); // 获取权限(角色) List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList((String) claims.get("authorities")); // 返回验证令牌 return user != null ? new UsernamePasswordAuthenticationToken(user, null, authorities) : null; } return null; }
Example #5
Source File: DefaultAccessTokenConverter.java From MaxKey with Apache License 2.0 | 6 votes |
public OAuth2Authentication extractAuthentication(Map<String, ?> map) { Map<String, String> parameters = new HashMap<String, String>(); @SuppressWarnings("unchecked") Set<String> scope = new LinkedHashSet<String>(map.containsKey(SCOPE) ? (Collection<String>) map.get(SCOPE) : Collections.<String>emptySet()); Authentication user = userTokenConverter.extractAuthentication(map); String clientId = (String) map.get(CLIENT_ID); parameters.put(CLIENT_ID, clientId); if (includeGrantType && map.containsKey(GRANT_TYPE)) { parameters.put(GRANT_TYPE, (String) map.get(GRANT_TYPE)); } @SuppressWarnings("unchecked") Set<String> resourceIds = new LinkedHashSet<String>(map.containsKey(AUD) ? (Collection<String>) map.get(AUD) : Collections.<String>emptySet()); Collection<? extends GrantedAuthority> authorities = null; if (user==null && map.containsKey(AUTHORITIES)) { @SuppressWarnings("unchecked") String[] roles = ((Collection<String>)map.get(AUTHORITIES)).toArray(new String[0]); authorities = AuthorityUtils.createAuthorityList(roles); } OAuth2Request request = new OAuth2Request(parameters, clientId, authorities, true, scope, resourceIds, null, null, null); return new OAuth2Authentication(request, user); }
Example #6
Source File: UserConfig.java From springBoot with MIT License | 6 votes |
@Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { //查询用户 SysUserVo sysUserVo = sysUserService.findByLoginName(username).getData(); //查询权限 List<SysUserAuthorityVo> sysUserAuthorityVoList = sysUserAuthorityService.findByUserId(sysUserVo.getUserId()).getData(); StringBuilder authoritys = new StringBuilder(); for (int i = 0; i < sysUserAuthorityVoList.size(); i++) { SysUserAuthorityVo sysUserAuthorityVo = sysUserAuthorityVoList.get(i); authoritys.append(sysUserAuthorityVo.getSysAuthority().getAuthorityName()); if (i != sysUserAuthorityVoList.size() - 1) { authoritys.append(","); } } // 封装用户信息,并返回。参数分别是:用户名,密码,用户权限 return new User(sysUserVo.getLoginName(), sysUserVo.getPassword(), AuthorityUtils.commaSeparatedStringToAuthorityList(authoritys.toString())); }
Example #7
Source File: UserDetailsServiceImpl.java From ExamStack with GNU General Public License v2.0 | 6 votes |
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // TODO Auto-generated method stub User user = null; try { user = userMapper.getUserByName(username); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } if(user == null) throw new UsernameNotFoundException("user not found!"); //roles=角色代码 List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(user.getRoles()); userInfo = new UserInfo(username,user.getPassword(),user.isEnabled(),true,true,true,authorities); userInfo.setUserid(user.getUserId()); userInfo.setRolesName(user.getRoles()); userInfo.setTrueName(user.getTrueName()); userInfo.setEmail(user.getEmail()); userInfo.setPhoneNum(user.getPhoneNum()); userInfo.setNationalId(user.getNationalId()); userInfo.setDepId(user.getDepId()); return userInfo; }
Example #8
Source File: WithOAuth2MockAccessTokenSecurityContextFactory.java From microservices-basics-spring-boot with Apache License 2.0 | 6 votes |
/** * Mock OAuth2Request * * @param withMockOAuth2Token * @return */ private OAuth2Request getOauth2Request(WithMockOAuth2Token withMockOAuth2Token) { String clientId = withMockOAuth2Token.clientId(); Map<String, String> requestParameters = Collections.emptyMap(); boolean approved = true; String redirectUrl = withMockOAuth2Token.redirectUrl(); Set<String> responseTypes = Collections.emptySet(); Set<String> scopes = new HashSet<>(Arrays.asList(withMockOAuth2Token.scopes())); Set<String> resourceIds = Collections.emptySet(); Map<String, Serializable> extensionProperties = Collections.emptyMap(); List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(withMockOAuth2Token.authorities()); OAuth2Request oAuth2Request = new OAuth2Request(requestParameters, clientId, authorities, approved, scopes, resourceIds, redirectUrl, responseTypes, extensionProperties); return oAuth2Request; }
Example #9
Source File: WorkConsumerJobImpl.java From telekom-workflow-engine with MIT License | 6 votes |
@Override public synchronized void start(){ isStopping.set( false ); // number of parallel consumer threads int numberOfConsumerThreads = config.getNumberOfConsumerThreads(); // spring security context for executor threads SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("workflow-engine", "[not-used]", AuthorityUtils.createAuthorityList("ROLE_WORKFLOW_ENGINE"))); // actual executor thread pool ExecutorService delegateExecutorService = Executors.newFixedThreadPool( numberOfConsumerThreads, new NamedPoolThreadFactory( "consumer" ) ); // wrapper executor service that sets the security context for each thread executorService = new DelegatingSecurityContextExecutorService(delegateExecutorService, securityContext); // start the consuming jobs for( int i = 0; i < numberOfConsumerThreads; i++ ){ executorService.execute( new ConsumerRunnable() ); } log.info( "Scheduled {} consumers", numberOfConsumerThreads ); }
Example #10
Source File: UserDetailService.java From SpringAll with MIT License | 6 votes |
@Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // 模拟一个用户,替代数据库获取逻辑 MyUser user = new MyUser(); user.setUserName(username); user.setPassword(this.passwordEncoder.encode("123456")); // 输出加密后的密码 System.out.println(user.getPassword()); List<GrantedAuthority> authorities = new ArrayList<>(); if (StringUtils.equalsIgnoreCase("mrbird", username)) { authorities = AuthorityUtils.commaSeparatedStringToAuthorityList("admin"); } else { authorities = AuthorityUtils.commaSeparatedStringToAuthorityList("test"); } return new User(username, user.getPassword(), user.isEnabled(), user.isAccountNonExpired(), user.isCredentialsNonExpired(), user.isAccountNonLocked(), authorities); }
Example #11
Source File: AuthenticationHandler.java From blackduck-alert with Apache License 2.0 | 6 votes |
private ObjectPostProcessor<AffirmativeBased> createRoleProcessor() { return new ObjectPostProcessor<>() { @Override public AffirmativeBased postProcess(AffirmativeBased affirmativeBased) { WebExpressionVoter webExpressionVoter = new WebExpressionVoter(); DefaultWebSecurityExpressionHandler expressionHandler = new DefaultWebSecurityExpressionHandler(); expressionHandler.setRoleHierarchy(authorities -> { String[] allAlertRoles = retrieveAllowedRoles(); return AuthorityUtils.createAuthorityList(allAlertRoles); }); webExpressionVoter.setExpressionHandler(expressionHandler); affirmativeBased.getDecisionVoters().add(webExpressionVoter); return affirmativeBased; } }; }
Example #12
Source File: SomeExternalServiceAuthenticator.java From spring-boot-security-example with MIT License | 6 votes |
@Override public AuthenticatedExternalWebService authenticate(String username, String password) { ExternalWebServiceStub externalWebService = new ExternalWebServiceStub(); // Do all authentication mechanisms required by external web service protocol and validated response. // Throw descendant of Spring AuthenticationException in case of unsucessful authentication. For example BadCredentialsException // ... // ... // If authentication to external service succeeded then create authenticated wrapper with proper Principal and GrantedAuthorities. // GrantedAuthorities may come from external service authentication or be hardcoded at our layer as they are here with ROLE_DOMAIN_USER AuthenticatedExternalWebService authenticatedExternalWebService = new AuthenticatedExternalWebService(new DomainUser(username), null, AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_DOMAIN_USER")); authenticatedExternalWebService.setExternalWebService(externalWebService); return authenticatedExternalWebService; }
Example #13
Source File: AbstractHazelcastIndexedSessionRepositoryITests.java From spring-session with Apache License 2.0 | 6 votes |
@Test void createSessionWithSecurityContextAndFindByPrincipal() { Assumptions.assumeTrue(this.hazelcastInstance instanceof HazelcastInstanceProxy, "Hazelcast runs in embedded server topology"); HazelcastSession session = this.repository.createSession(); String username = "saves-" + System.currentTimeMillis(); Authentication authentication = new UsernamePasswordAuthenticationToken(username, "password", AuthorityUtils.createAuthorityList("ROLE_USER")); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(authentication); session.setAttribute(SPRING_SECURITY_CONTEXT, securityContext); this.repository.save(session); assertThat(this.repository .findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, username)) .hasSize(1); }
Example #14
Source File: AccountDetailsService.java From WeEvent with Apache License 2.0 | 6 votes |
@Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { log.info("username: {}", username); AccountEntity accountEntity = null; try { accountEntity = accountService.queryByUsername(username); } catch (Exception e) { throw new UsernameNotFoundException("sql execute error!"); } String password = accountEntity.getPassword(); log.info("password: {}", password); User user = new User(username, password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin")); return user; }
Example #15
Source File: SecurityConfiguration.java From syndesis with Apache License 2.0 | 6 votes |
@SuppressWarnings("PMD.SignatureDeclareThrowsException") private RequestHeaderAuthenticationFilter requestHeaderAuthenticationFilter() throws Exception { RequestHeaderAuthenticationFilter f = new RequestHeaderAuthenticationFilter(); f.setPrincipalRequestHeader("X-Forwarded-User"); f.setCredentialsRequestHeader("X-Forwarded-Access-Token"); f.setAuthenticationManager(authenticationManager()); f.setAuthenticationDetailsSource( (AuthenticationDetailsSource<HttpServletRequest, PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails>) (request) ->new PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails( request, AuthorityUtils.createAuthorityList("ROLE_AUTHENTICATED") ) ); f.setAuthenticationFailureHandler(new SimpleUrlAuthenticationFailureHandler()); f.setExceptionIfHeaderMissing(false); return f; }
Example #16
Source File: RoleWiseSuccessHandler.java From zhcet-web with Apache License 2.0 | 6 votes |
public static String determineTargetUrl(Authentication authentication) { Set<String> authorities = AuthorityUtils.authorityListToSet(authentication.getAuthorities()); if (authorities.contains(Role.DEAN_ADMIN.toString())) return "/admin/dean"; else if (authorities.contains(Role.DEVELOPMENT_ADMIN.toString())) return "/actuator/health"; else if (authorities.contains(Role.DEPARTMENT_ADMIN.toString())) return "/admin/department"; else if (authorities.contains(Role.FACULTY.toString())) return "/admin/faculty/courses"; else if (authorities.contains(Role.STUDENT.toString())) return "/dashboard/student/attendance"; else if (authorities.contains(Role.USER.toString())) return "/profile"; else return "/login"; }
Example #17
Source File: UserDetailsServiceImpl.java From ExamStack with GNU General Public License v2.0 | 6 votes |
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // TODO Auto-generated method stub User user = null; try { user = userMapper.getUserByName(username); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } if(user == null) throw new UsernameNotFoundException("user not found!"); //roles=角色代码 List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(user.getRoles()); userInfo = new UserInfo(username,user.getPassword(),user.isEnabled(),true,true,true,authorities); userInfo.setUserid(user.getUserId()); userInfo.setRolesName(user.getRoles()); userInfo.setTrueName(user.getTrueName()); userInfo.setEmail(user.getEmail()); userInfo.setPhoneNum(user.getPhoneNum()); userInfo.setNationalId(user.getNationalId()); userInfo.setDepId(user.getDepId()); return userInfo; }
Example #18
Source File: JwtUserAuthenticationConverter.java From elucidate-server with MIT License | 6 votes |
@Override public Authentication extractAuthentication(Map<String, ?> details) { return uidProperties.stream() .filter(details::containsKey) .map(prop -> (String) details.get(prop)) .findFirst() .map(uid -> { UserSecurityDetails securityDetails = securityDetailsLoader.findOrCreateUserDetails(uid); Collection<String> roles = (Collection<String>) details.get(AUTHORITIES); if (roles == null) { roles = Collections.emptyList(); } List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(roles.toArray(new String[0])); Authentication auth = new UsernamePasswordAuthenticationToken( securityDetails, "N/A", authorities ); return auth; }) .orElse(null); }
Example #19
Source File: CerberusUserFactory.java From Cerberus with MIT License | 6 votes |
public static CerberusUser create(User user) { Collection<? extends GrantedAuthority> authorities; try { authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(user.getAuthorities()); } catch (Exception e) { authorities = null; } return new CerberusUser( user.getId(), user.getUsername(), user.getPassword(), user.getEmail(), user.getLastPasswordReset(), authorities ); }
Example #20
Source File: JwtService.java From batch-scheduler with MIT License | 6 votes |
public static Authentication getAuthentication(HttpServletRequest request) { // 从Header中拿到token String token = request.getHeader(HEADER_STRING); if (token == null) { token = getTokenFromCookis(request); } if (token != null && !token.isEmpty()) { // 解析 Token Claims claims = Jwts.parser().setSigningKey(SECRET) .parseClaimsJws(token).getBody(); // 获取用户名 String user = claims.get("UserId").toString(); // 获取权限(角色) List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList((String) claims.get("authorities")); // 返回验证令牌 return user != null ? new UsernamePasswordAuthenticationToken(user, null, authorities) : null; } return null; }
Example #21
Source File: CustomUserAuthenticationConverter.java From codeway_service with GNU General Public License v3.0 | 6 votes |
/** * 定义access_token内容,JWT谁都可读 * 不应该在载荷里面加入任何敏感的数据 */ @Override public Map<String, ?> convertUserAuthentication(Authentication authentication) { LinkedHashMap<String,Object> response = new LinkedHashMap<>(); String name = authentication.getName(); Object principal = authentication.getPrincipal(); UserJwt userJwt = null; if(principal instanceof UserJwt){ userJwt = (UserJwt) principal; }else{ //refresh_token默认不去调用userdetailService获取用户信息,手动去调用,得到 UserJwt UserDetails userDetails = userDetailsService.loadUserByUsername(name); userJwt = (UserJwt) userDetails; } if (authentication.getAuthorities() != null && !authentication.getAuthorities().isEmpty()) { response.put("authorities", AuthorityUtils.authorityListToSet(authentication.getAuthorities())); } response.put("id", userJwt.getId()); return response; }
Example #22
Source File: WebSecurityAuthenticationConfigurer.java From chvote-protocol-poc with GNU Affero General Public License v3.0 | 6 votes |
@Bean UserDetailsService userDetailsService() { return username -> { LOGGER.debug(String.format("Looking for user [%s]", username)); Account account = accountRepository.findByUsername(username); if (account != null) { LOGGER.info(String.format("Found user [%s]", username)); return new User(account.getUsername(), account.getPassword(), true, true, true, true, AuthorityUtils.createAuthorityList("USER")); } else { LOGGER.info(String.format("Couldn't find user [%s]", username)); throw new UsernameNotFoundException(String.format("couldn't find the user '%s'", username)); } }; }
Example #23
Source File: AuthenticationProviderApplication.java From Spring with Apache License 2.0 | 5 votes |
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String username = authentication.getName(); String password = authentication.getCredentials().toString(); if (isValid(username, password)) { return new UsernamePasswordAuthenticationToken(username, password, AuthorityUtils.createAuthorityList("USER")); } throw new BadCredentialsException( "couldn't authenticate (" + authentication + ")"); }
Example #24
Source File: ActivitiAuthenticationProvider.java From maven-framework-project with MIT License | 5 votes |
@Override @Transactional(readOnly = true) protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { log.trace("retrieveUser()"); log.debug("retrieving user: " + username); User user; try { user = this.read(username); if (user == null) { throw new Exception(); } } catch (Exception e) { throw new UsernameNotFoundException("User " + username + " cannot be found"); } String userName = user.getId(); String pw = user.getPassword(); List<Group> groups = this.identityService.createGroupQuery().groupMember(userName).groupType("security-role").list(); List<String> groupStr = Lists.newArrayList(); for (Group g : groups) { groupStr.add(g.getId()); } Collection<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList(Joiner.on(",").skipNulls().join(groupStr)); boolean enabled = groupStr.contains("user"); UserDetails userDetails = new org.springframework.security.core.userdetails.User(userName, pw, enabled, true, true, true, auths); log.debug("returning new userDetails: " + userDetails); return userDetails; }
Example #25
Source File: SessionEventHazelcastIndexedSessionRepositoryTests.java From spring-session with Apache License 2.0 | 5 votes |
@Test void saveSessionTest() throws InterruptedException { String username = "saves-" + System.currentTimeMillis(); S sessionToSave = this.repository.createSession(); String expectedAttributeName = "a"; String expectedAttributeValue = "b"; sessionToSave.setAttribute(expectedAttributeName, expectedAttributeValue); Authentication toSaveToken = new UsernamePasswordAuthenticationToken(username, "password", AuthorityUtils.createAuthorityList("ROLE_USER")); SecurityContext toSaveContext = SecurityContextHolder.createEmptyContext(); toSaveContext.setAuthentication(toSaveToken); sessionToSave.setAttribute("SPRING_SECURITY_CONTEXT", toSaveContext); sessionToSave.setAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, username); this.repository.save(sessionToSave); assertThat(this.registry.receivedEvent(sessionToSave.getId())).isTrue(); assertThat(this.registry.<SessionCreatedEvent>getEvent(sessionToSave.getId())) .isInstanceOf(SessionCreatedEvent.class); Session session = this.repository.findById(sessionToSave.getId()); assertThat(session.getId()).isEqualTo(sessionToSave.getId()); assertThat(session.getAttributeNames()).isEqualTo(sessionToSave.getAttributeNames()); assertThat(session.<String>getAttribute(expectedAttributeName)) .isEqualTo(sessionToSave.getAttribute(expectedAttributeName)); }
Example #26
Source File: JdbcSecurityConfiguration.java From pro-spring-boot with Apache License 2.0 | 5 votes |
@Bean public UserDetailsService userDetailsService(JdbcTemplate jdbcTemplate) { RowMapper<User> userRowMapper = (ResultSet rs, int i) -> new User( rs.getString("ACCOUNT_NAME"), rs.getString("PASSWORD"), rs.getBoolean("ENABLED"), rs.getBoolean("ENABLED"), rs.getBoolean("ENABLED"), rs.getBoolean("ENABLED"), AuthorityUtils.createAuthorityList("ROLE_USER", "ROLE_ADMIN")); return username -> jdbcTemplate.queryForObject("SELECT * from ACCOUNT where ACCOUNT_NAME = ?", userRowMapper, username); }
Example #27
Source File: SimpleUserDetailsServiceTest.java From Spring with Apache License 2.0 | 5 votes |
private Collection<UserDetails> contributeUsers() { return IntStream.range(0, 5) .mapToObj(i -> new User("user" + i, this.passwordEncoder.encode("password" + i), true, true, true, true, AuthorityUtils.createAuthorityList("USER"))) .collect(Collectors.toList()); }
Example #28
Source File: ManualMockMvcTests.java From Spring with Apache License 2.0 | 5 votes |
@Test public void contextFails() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .addFilters(this.springSecurityFilterChain).build(); UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken( "user", "password", AuthorityUtils.createAuthorityList("ROLE_USER")); SecurityContextHolder.getContext().setAuthentication(authentication); mockMvc.perform(get("/")).andExpect(status().isUnauthorized()); }
Example #29
Source File: AuthorizationServerConfiguration.java From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License | 5 votes |
@Override public Map<String, ?> convertUserAuthentication(Authentication authentication) { Map<String, Object> response = new LinkedHashMap<String, Object>(); response.put("sub", authentication.getName()); if (authentication.getAuthorities() != null && !authentication.getAuthorities().isEmpty()) { response.put(AUTHORITIES, AuthorityUtils.authorityListToSet(authentication.getAuthorities())); } return response; }
Example #30
Source File: InMemoryAuthentificationProvider.java From gravitee-management-rest-api with Apache License 2.0 | 5 votes |
@Override public org.springframework.security.authentication.AuthenticationProvider configure() throws Exception { boolean found = true; int userIdx = 0; while (found) { String user = environment.getProperty("users[" + userIdx + "].user"); found = (user != null && user.isEmpty()); if (found) { String username = environment.getProperty("users[" + userIdx + "].username"); String firstname = environment.getProperty("users[" + userIdx + "].firstname"); String lastname = environment.getProperty("users[" + userIdx + "].lastname"); String password = environment.getProperty("users[" + userIdx + "].password"); String email = environment.getProperty("users[" + userIdx + "].email"); String roles = environment.getProperty("users[" + userIdx + "].roles"); List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(roles); userIdx++; io.gravitee.rest.api.idp.api.authentication.UserDetails newUser = new io.gravitee.rest.api.idp.api.authentication.UserDetails(username, password, email, authorities); newUser.setSource(InMemoryIdentityProvider.PROVIDER_TYPE); newUser.setSourceId(username); newUser.setFirstname(firstname); newUser.setLastname(lastname); LOGGER.debug("Add an in-memory user: {}", newUser); userDetailsService.createUser(newUser); } } return this; }