文章目录
需求
- 实现多用户访问
- 从指定数据源中检索用户数据。
- 使用自定义的登陆页面。
思路
从Spring Security : 用户名密码认证中的时序图可以发现:Spring Security已经实现了完整的用户名密码认证的逻辑。因此只要DaoAuthenticationProvider#retrieveUser()方法返回的UserDetails实例是从指定数据源中检索到的,那么就可以实现“从指定数据源检索用户数据”的需求。当“指定数据源”中的存在多个用户时,同时会实现“多用户访问”。
实现
模型
自定义用户对象 MyUser
org.springframework.security.core.userdetails.User 是Spring Security已实现的UserDetails实现。继承该类。
public class MyUser extends User {
public MyUser(String username, String password, Collection<? extends GrantedAuthority> authorities) {
super(username, password, authorities);
}
public MyUser(String username,
String password,
boolean enabled,
boolean accountNonExpired,
boolean credentialsNonExpired,
boolean accountNonLocked,
Collection<? extends GrantedAuthority> authorities) {
super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
}
}
数据源
模拟数据源 RepositoryUtils
模拟数据源,数据源中保存用户及权限信息
public class RepositoryUtils {
static List<MyUser> users = new ArrayList<>();
static {
//密码加密工具
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(4);
//创建用户并设置用户角色
ArrayList<SimpleGrantedAuthority> userAuth = new ArrayList<>();
userAuth.add(new SimpleGrantedAuthority("MEMBER"));
users.add(new MyUser("user", passwordEncoder.encode("123"), userAuth));
ArrayList<SimpleGrantedAuthority> merchantAuth = new ArrayList<>();
merchantAuth.add(new SimpleGrantedAuthority("MERCHANT"));
users.add(new MyUser("merchant", passwordEncoder.encode("123"), merchantAuth));
ArrayList<SimpleGrantedAuthority> adminAuth = new ArrayList<>();
adminAuth.add(new SimpleGrantedAuthority("ADMIN"));
users.add(new MyUser("admin", passwordEncoder.encode("123"), adminAuth));
}
static MyUser findUserByUsername(String username) {
for (MyUser user : users) {
if(StringUtils.equals(username, user.getUsername()))
return user;
}
throw new UsernameNotFoundException(username);
}
}
数据源访问
从数据源中检索UserDetails。
@Component
public class UserRepository {
public MyUser findUserByUsername(String username) {
return RepositoryUtils.findUserByUsername(username);
}
}
自定义UserDetailsService实现
从指定数据源检索UserDetails。实现UserDetailsService接口。
@Component
public class MyUserDetailsService implements UserDetailsService {
@Autowired
private UserRepository userRepository;
/**
* 根据用户名从数据源中检索用户信息
*
* @param username
*
* @return
*
* @throws UsernameNotFoundException
*/
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
if (StringUtils.isEmpty(username))
throw new IllegalArgumentException("username is empty");
return userRepository.findUserByUsername(username);
}
}
登陆页面
自定义登陆页面
resources目录下新增templates目录,新增文件login.html
<form th:action="@{/login}" method="post">
<div><label> User Name : <input type="text" name="username"/> </label></div>
<div><label> Password: <input type="password" name="password"/> </label></div>
<div><input type="submit" value="Sign In"/></div>
</form>
配置View
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/login").setViewName("login");
}
}
访问资源
模拟用户访问需要认证的资源。
@RestController
public class HelloEndpoint {
@GetMapping("/")
public String hello() {
return "hello, Spring Security";
}
}
配置Spring Security 用户名密码认证
继承WebSecurityConfigurerAdapter。
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private MyUserDetailsService userDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()/*设置认证请求URL*/
.antMatchers(HttpMethod.GET,"/home", "/login", "/login.html").permitAll()/*设置无需认证的URL*/
.anyRequest().authenticated()/*任何URL都需要认证*/
.and()/* 完成上一个配置,进行下一步配置 */
.formLogin()/* 配置表单登录 */
.usernameParameter("username") /* 默认值 username */
.passwordParameter("password") /* 默认值 password */
.loginPage("/login") /* 设置登录页面,默认是HTTP GET /login */
.loginProcessingUrl("/login") /* 设置登录页面,默认是HTTP POST /login */
.and()/* 完成上一个配置,进行下一步配置 */
.logout()/* 配置表单登录 */
.logoutSuccessUrl("/home");/* 设置退出页面 */
}
/**
* spring5.0之后,spring security必须设置加密方法否则会报
* There is no PasswordEncoder mapped for the id "null"
*
* @return 加密
*/
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(4);
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
}
测试
- 启动后的访问地址:http://localhost:8080/