From 62fb8b257b2ab67a1b6c4ecd5807ec6da496a0e0 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sat, 1 Oct 2016 09:58:51 +0200 Subject: [PATCH] Refactor MyUserDetailsService --- .../service/MyUserDetailsService.java | 40 +++++-------------- 1 file changed, 9 insertions(+), 31 deletions(-) diff --git a/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/service/MyUserDetailsService.java b/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/service/MyUserDetailsService.java index 2baf88a62d..c662c32738 100644 --- a/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/service/MyUserDetailsService.java +++ b/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/service/MyUserDetailsService.java @@ -1,11 +1,5 @@ package org.baeldung.service; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.baeldung.security.SecurityRole; @@ -17,9 +11,9 @@ import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; -/** - * User Details Service - hard coded to two users for the example. - */ +import java.util.*; +import java.util.stream.Collectors; + @Service public class MyUserDetailsService implements UserDetailsService { @@ -28,24 +22,19 @@ public class MyUserDetailsService implements UserDetailsService { private final Map availableUsers = new HashMap(); public MyUserDetailsService() { - populateDemoUsers(); - } - // - @Override public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException { logger.info("Load user by username " + username); final UserDetails user = availableUsers.get(username); if (user == null) { - throw new UsernameNotFoundException("Username not found"); - } else { - return availableUsers.get(username); + throw new UsernameNotFoundException(username); } + return user; } /** @@ -59,24 +48,13 @@ public class MyUserDetailsService implements UserDetailsService { availableUsers.put("admin", createUser("admin", "password", Arrays.asList(SecurityRole.ROLE_ADMIN))); } - /** - * Create a demo User. - * - * @param username - * Username - * @param password - * Password - * @param roles - * Role names user is assigned to - * @return User - */ private User createUser(final String username, final String password, final List roles) { logger.info("Create user " + username); - final List authorities = new ArrayList(); - for (final SecurityRole role : roles) { - authorities.add(new SimpleGrantedAuthority(role.toString())); - } + final List authorities = roles.stream() + .map(role -> new SimpleGrantedAuthority(role.toString())) + .collect(Collectors.toList()); + return new User(username, password, true, true, true, true, authorities); } }