授权服务器(Authorization Server)
UserDetailsServiceImpl:
package com.authorization.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
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 org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
/**
* @description:
* @Author C_Y_J
* @create 2022/1/7 14:02
**/
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private PasswordEncoder passwordEncoder;
/**
* @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String)
*/
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
return buildUser(username);
}
private UserDetails buildUser(String username) {
// 根据用户名查找用户信息
// 根据查找到的用户信息判断用户是否被冻结
String password = passwordEncoder.encode("123456");
return new User(username, password,
true, true, true, true,
AuthorityUtils.commaSeparatedStringToAuthorityList("admin,ROLE_USER"));
}
}
WebSecurityConfiguration:
/**
* TokenStore 令牌存储服务(令牌存储在哪个地方)
*
* @return
*/
@Bean
public TokenStore inMemoryTokenStore() {
return new InMemoryTokenStore();
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
// @Override
// protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// // 添加一个用户、保存在内存中
// auth.inMemoryAuthentication()
// .withUser("user")
// .password(passwordEncoder().encode("123456"))
// .authorities(Collections.emptyList());
//
// }
AuthorizationServerConfiguration:
private final AuthenticationManager authenticationManager;
private final TokenStore tokenStore;
private final UserDetailsService userDetailsService;
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
// 配置端点
endpoints.tokenStore(tokenStore)
.authenticationManager(authenticationManager)
.userDetailsService(userDetailsService);
}
后记
在这里加上了UserDetailsService 、TokenStore。UserDetailsService:查询数据库中用户信息,TokenStore:token令牌存储服务(令牌存储在哪个地方)