SpringSecurity如何实现自定义登录页面呢?
下文笔者讲述SpringSecurity实现自定义登录页面的方法分享,如下所示
一、定义一个登录页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录页面设计</title>
</head>
<body>
<form action="/user/login" method="post">
用户名:<input type="text" name="username"/><br>
密码:<input type="password" name="password"/><br>
<input type="submit" value="登录"/>
</form>
</body>
</html>
二、配置类
注意事项: 1.先关闭csrf保护,否则无法进行认证 2.设置点击登录后访问的路径
配置类的定义
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin() //自定义登录页面
.loginPage("/login.html") //登录页面设置
.loginProcessingUrl("/user/login") //点击登录后访问的路径
.defaultSuccessUrl("/index").permitAll() //登录成功后跳转路径,permitAll表示无条件进行访问
.and().authorizeRequests()
.mvcMatchers("/","/hello","/user/login").permitAll() //设置不需要认证可以直接访问的路径
.anyRequest().authenticated()
.and().csrf().disable(); //关闭csrf保护
}
}
三、控制层
@RestController
public class loginController {
@GetMapping("/hello")
public String hello(){
return "hello SpringSecurity";
}
//登录成功后的返回地址
@GetMapping("/index")
public String index(){
return "登录成功";
}
}
四、测试
访问hello url
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


