参考资料https://docs.spring.io/spring-security/site/docs/5.4.7/reference/html5/
本文采用Spring Security,实现用户名+密码 验证登陆
1、pom.xml中添加jar
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2、使用注解@Configuration@EnableWebSecurity,自定义配置WebSecurityConfig,继承WebSecurityConfigurerAdapter
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/static/**", "/login/**").permitAll() // 不拦截的请求
.anyRequest().authenticated() // 拦截所有请求
.and()
.formLogin((formLogin) -> formLogin
.loginPage("/login") // 跳转登陆
.failureUrl("/login-error")
);
}
@Bean
public UserDetailsService userDetailsService() {
// 查询所有注册用户名、密码
List<MyUser> myUsers = myUserDao.getAllUserList();
List<UserDetails> userDetails = new ArrayList<UserDetails>();
if (myUsers != null) {
for (MyUser obj : myUsers) {
UserDetails userDetail = User.withDefaultPasswordEncoder()
.username(obj.getAccount())
.password(obj.getPassword())
.roles("USER") // 必须项目
.build();
userDetails.add(userDetail);
}
}
return new InMemoryUserDetailsManager(userDetails);
}
3、Spring Security 集成了Servlet,在login请求中,使用HttpServletRequest.login()实现登陆验证。代码中,需要捕获ServletException
try {
request.login(username, password);
} catch (ServletException e) {
e.printStackTrace();
}
4、获取当前登陆用户信息
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();