Java tutorial
/** * Copyright 2014 Paul Illingworth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.threeonefour.ifictionary.web.security.service; import java.util.ArrayList; import java.util.Collection; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import uk.co.threeonefour.ifictionary.web.user.dao.UserDao; import uk.co.threeonefour.ifictionary.web.user.model.Role; public class UserDetailsServiceImpl implements UserDetailsService { private final UserDao userDao; public UserDetailsServiceImpl(UserDao userDao) { this.userDao = userDao; } @Override public UserDetails loadUserByUsername(String userId) throws UsernameNotFoundException { uk.co.threeonefour.ifictionary.web.user.model.User userEntity; userEntity = userDao.findUser(userId); if (userEntity == null) { throw new UsernameNotFoundException("user name not found"); } return buildUserFromUserEntity(userEntity); } private User buildUserFromUserEntity(uk.co.threeonefour.ifictionary.web.user.model.User userEntity) { // convert model user to spring security user String username = userEntity.getUserId(); String password = userEntity.getPassword(); boolean enabled = true; boolean accountNonExpired = true; boolean credentialsNonExpired = true; boolean accountNonLocked = true; Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); Collection<Role> roles = userEntity.getRoles(); for (Role role : roles) { authorities.add(new SimpleGrantedAuthority(role.name())); } User springUser = new User(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities); return springUser; } }