/** * Created by macro on 2019/9/30. */ @Service public class UserService implements UserDetailsService { private List userList;@Autowiredprivate PasswordEncoder passwordEncoder;@PostConstructpublic void initData() { String password = passwordEncoder.encode("123456"); userList = new ArrayList<>(); userList.add(new User("macro", password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin"))); userList.add(new User("andy", password, AuthorityUtils.commaSeparatedStringToAuthorityList("client"))); userList.add(new User("mark", password, AuthorityUtils.commaSeparatedStringToAuthorityList("client"))); }@Overridepublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { List findUserList = userList.stream().filter(user -> user.getUsername().equals(username)).collect(Collectors.toList());if (!CollectionUtils.isEmpty(findUserList)) {return findUserList.get(0); } else {throw new UsernameNotFoundException("用户名或密码错误"); } } }
添加认证服务器配置,使用@EnableAuthorizationServer注解开启:
/** * 认证服务器配置 * Created by macro on 2019/9/30. */ @Configuration @EnableAuthorizationServer public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
/** * 资源服务器配置 * Created by macro on 2019/9/30. */ @Configuration @EnableResourceServer public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
/** * SpringSecurity配置 * Created by macro on 2019/10/8. */ @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); }
/** * Created by macro on 2019/9/30. */ @RestController @RequestMapping("/user") public class UserController { @GetMapping("/getCurrentUser") public Object getCurrentUser(Authentication authentication) { return authentication.getPrincipal(); } }