前提
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
依赖
<!--spring security-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
层级结构
直接复制代码
SecurityConfig
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
//表单提交
http.formLogin()
.usernameParameter("username123")
.passwordParameter("password123")
//当发现login是认为是登录, 必须和表单提交的地址一样 去执行UserDetailsServiceImpl
.loginProcessingUrl("/login")
//自定义登录页
.loginPage("/login.html")
//登录成功后跳转页面,post请求
// .successForwardUrl("/toMain")
//登录成功后的处理器 不能与successForwardUrl共存
.successHandler(new MyAuthenticationSuccessHandler("http://www.baidu.com"))
//登录失败后跳转页面,
// .failureForwardUrl("/toError")
//登录失败后的处理器 不能与failureForwardUrl共存
.failureHandler(new MyAuthenticationFailureHandler("/error.html")) ;
//授权认证
http.authorizeRequests()
//login.html不需要被认证
.antMatchers("/login.html","/error.html", "/js/**").permitAll()
//所有请求必须被认证,必须登录后访问
.anyRequest().authenticated();
//关闭csrf防护
http.csrf().disable();
}
@Bean
public PasswordEncoder getPasswordEncoder() {
return new BCryptPasswordEncoder();
}
}
UserDetailsServiceImpl
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private PasswordEncoder passwordEncoder;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
log.warn("进来loadUserByUsername方法!!");
//1,查询数据库判断用户名是否存在,如果不存在就会抛出异常
if (!StringUtils.equals("admin",username)){
throw new UsernameNotFoundException("用户名不存在!");
}
//2,把查询出来的密码(注册时已经加密过) 进行解析, 或者把密码放到构造方法
String password = passwordEncoder.encode("123");
return new User(username,password,
AuthorityUtils.commaSeparatedStringToAuthorityList("admin,normal"));
}
}
LoginController
@Controller
public class LoginController {
@RequestMapping(value = "toMain",method = RequestMethod.POST)
// @RequestMapping("toMain")
public String toMain(){
return "redirect:main.html";
// return "main";
}
@RequestMapping("toError")
public String toError(){
return "redirect:error.html";
}
}
页面
登录页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录页</title>
</head>
<body>
<form action="/login" method="post">
用户名 : <input type="text" name="username123"></br>
密码 : <input type="password" name="password123"></br>
<input type="submit" value="登录">
</form>
</body>
</html>
主页
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>主页</title>
</head>
<body>
登录成功!
</body>
</html>
错误页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>主页</title>
</head>
<body>
操作失败,请重新登陆 <a href="/login.html">跳转</a>
</body>
</html>
本文暂时没有评论,来添加一个吧(●'◡'●)