1 SecurityConfig配置类
package com.mangoubiubiu.security.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
/**
* SecurityConfig 配置类
*/
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
//表单登录
http.formLogin()
.loginProcessingUrl("/login")
.loginPage("/login.html")
.successForwardUrl("/main")
.failureForwardUrl("/toError")
//自定义登录用户名参数
.usernameParameter("user")
.passwordParameter("pwd");
//所有请求都必须被认证(登录)
http.authorizeRequests()
//放行登录页面
.antMatchers("/login.html","/error.html").permitAll()
//所有请求都必须被认证(登录)
.anyRequest().authenticated();
//关闭 csrf 跨站请求伪造
http.csrf().disable();
}
@Bean
public PasswordEncoder pw(){
return new BCryptPasswordEncoder();
}
}
2 error.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录失败</title>
</head>
<body>
<h1 style="color: red">登录失败</h1>
</body>
</html>
3 LoginController
package com.mangoubiubiu.security.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class LoginController {
@RequestMapping("/main")
public String tomain(){
return "redirect:main.html";
}
@RequestMapping("/toError")
public String error(){
return "redirect:error.html";
}
}