Refactor MyUserDetailsService

This commit is contained in:
Grzegorz Piwowarek 2016-10-01 09:58:51 +02:00
parent c8ff59ffe2
commit 62fb8b257b
1 changed files with 9 additions and 31 deletions

View File

@ -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<String, User> availableUsers = new HashMap<String, User>();
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<SecurityRole> roles) {
logger.info("Create user " + username);
final List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
for (final SecurityRole role : roles) {
authorities.add(new SimpleGrantedAuthority(role.toString()));
}
final List<GrantedAuthority> authorities = roles.stream()
.map(role -> new SimpleGrantedAuthority(role.toString()))
.collect(Collectors.toList());
return new User(username, password, true, true, true, true, authorities);
}
}