上一篇博客集成?Spring Security,使用其默认生效的?HTTP?基本认证保护?URL?资源,下面使用表单认证来保护?URL?资源。
一、默认表单认证:
代码改动:自定义WebSecurityConfig配置类
package com.security.demo.config;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
}
因为WebSecurityConfigurerAdapter的configure(HttpSecurity http)方法自带默认的表单身份认证,这里继承后不做方法修改,启动项目,这时访问localhost:8089/securityDemo/user/test仍然会跳转到默认的登陆页
二、自定义表单登陆:
1、自定义表单登陆页:
? 代码改动:
(1)覆盖configure(HttpSecurity http)方法
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{
protected void configure(HttpSecurity http) throws Exception{
http.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin().
loginPage("/myLogin.html")
// 使登录页不设限访问
.permitAll()
.and().
csrf().disable();
}
}
(2)编写自定义的登陆页myLogin.html,放在resources/static/?下
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登录</title>
</head>
<body>
<div class = "login" style="width:300px;height:300px">
<h2>Acced Form</h2>
<div class ="login-top"></div>
<h1>LOGIN FORM</h1>
<form action="myLogin.html" method="post">
<input type="text" name="username" placeholder="username"/>
<input type="password" name="password" placeholder="password"/>
<div class="forgot" style="margin-top:20px;">
<a href="#">forgot Password</a>
<input type="submit" value="login">
</div>
</form>
<div class="login-bottom">
<h3>New User <a href ="">Register</a> </h3>
</div>
</div>
</body>
</html>
访问localhost:8089/securityDemo/user/test会自动跳转到localhost:8089/securityDemo/static/myLogin.html
2、自定义登陆接口地址:?如自定义登陆接口为/login,代码改动:
(1)覆盖方法:
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{
protected void configure(HttpSecurity http) throws Exception{
http.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
// .loginPage("/myLogin.html")
.loginProcessingUrl("/login")
.permitAll()
.and()
.csrf().disable();
}
}
(2)新增/login接口
package com.security.demo.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class Login {
@RequestMapping("/login")
public String login(String username,String password){
System.out.println("用户名:"+username+",密码:"+password);
return "登陆成功";
}
}
重启后访问localhost:8089/securityDemo/user/test,自动跳转到spring默认的登陆页
输入user、控制台打印的密码,点击登陆按钮,可以看到调用了/login接口
调用成功后自动跳转到目标接口
注意:测试发现这个/login接口去掉也可以。