沈斌
2017-11-05 b59ca89001a572f450a84926bb603acc9aee996b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package com.moral.service.impl;
 
import com.moral.entity.auth.AuthRole;
import com.moral.entity.auth.AuthUser;
import com.moral.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
 
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
 
@Service
public class AuthUserServiceImpl implements UserDetailsService {
 
    @Autowired
    private UserService userService;
 
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        AuthUser user = userService.findByUsername(username);
 
        if(user == null){
            throw new UsernameNotFoundException("用户名:"+ username + "不存在!");
        }
        Collection<SimpleGrantedAuthority> collection = new HashSet<SimpleGrantedAuthority>();
        Iterator<AuthRole> iterator =  user.getList().iterator();
        while (iterator.hasNext()){
            collection.add(new SimpleGrantedAuthority(iterator.next().getRole_name()));
        }
 
        return new org.springframework.security.core.userdetails.User(username, user.getPassword(), collection);
    }
}