SpringBoot+SpringSecurity
整合了SpringSecurity权限框架
@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailServiceImpl userDetailService;
//授权
@Override
protected void configure(HttpSecurity http) throws Exception {
//登录页放开校验
http.authorizeRequests()
.antMatchers("/login.html", "/login").permitAll()
.anyRequest().authenticated();
//自动跳转登录页
//定义了一个login请求用于跳转登陆页面
http.formLogin().loginPage("/login").loginProcessingUrl("/login").defaultSuccessUrl("/success");
//关闭csrf校验
http.csrf().disable();
}
//认证
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//认证方法
auth.userDetailsService(userDetailService).passwordEncoder(passwordEncoder());
}
//自定义加密方式
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
// auth.userDetailsService()
// 这个方法需要一个UserDetailsService接口的实现类,我们需要创建一个类来实现这个接口,
//并且重写loadUserByUsername方法,写入我们自己想要实现的逻辑,然后将该实现类放入ioc,在这个auth.userDetailsService()地方传入该实现类的实例对象
//使用注解将该对象放入容器中
@Component
public class UserDetailServiceImpl implements UserDetailsService {
@Autowired
private PasswordEncoder encoder;
@Autowired
private SystemService systemService;
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
User currUser = systemService.getUserInfo(s);
if (currUser == null){
throw new UsernameNotFoundException("用户不存在");
}
//加密过程在此处体现
return new org.springframework.security.core.userdetails.User(currUser.getUserName(), encoder.encode(currUser.getPassword()),new ArrayList<>());
}
}
用于跳转自定义登录页的请求
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(
) {
try {
return "login";
} catch (Exception e) {
e.printStackTrace();
return e.getMessage();
}
}
前台页面流转暂时使用的是thymeleaf,仅用于测试SpringSecurity有效性,之后会改成Vue前后台分离项目
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org/" lang="en">
<head>
<meta charset="UTF-8">
<title>用户登录</title>
</head>
<body>
<h1>用户登录</h1>
<form th:action="@{/login}" method="post">
用户名:<input type="text" name="username"> <br>
密码:<input type="text" name="password"><br>
<input type="submit" value="登录">
</form>
</body>
</html>
现在访问未放开的接口,security都会自动跳转到我们自定义的登陆页面
登陆成功后,才可访问其他页面和请求
返回json
跳转页面