前面一章讲了security登陆的基本原理,这节讲讲如何不用basic登陆,采用表单登陆以及登陆过程中添加验证码
1.login.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>标准登录页面</h2>
<h3>表单登录</h3>
<form action="/login/form" method="post">
<table>
<tr>
<td>用户名:</td>
<td><input type="text" name="username" value="mj"></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td colspan="2"><button type="submit">登录</button></td>
</tr>
</table>
</form>
</body>
</html>
/**
* security配置
* @author majie
*
*/
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter{
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.formLogin() //表单登陆
.loginPage("/login/authentication") //指定需要登录时发送用户的URL,根据需要重定向请求,需要自己写对应的请求路径
.loginProcessingUrl("/login/form") //指定验证凭据的URL,和表单路径一样
.and()
.authorizeRequests()
.antMatchers("/login.html","/login/authentication")
.permitAll() //上面匹配的请求允许访问
.anyRequest()
.authenticated() //其他请求需要认证才能访问
.and()
.csrf().disable();
}
}
关于loginPage的请求路径,所有不允许直接访问的请求进来,都会去访问该路径,我们在这个请求里需要做的就是判断是否路径经过授权过,没有就让它跳到对应的登陆页面或者提示权限不足。
所以对应的controller
/**
* 登陆controller
* @author majie
*
*/
@RestController
public class LoginController {
// 重定向策略
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
// 请求缓存(跳转过来之前会先把请求保存到session里面,所以下面请求可以直接从缓存中获取请求)
private RequestCache requestCache = new HttpSessionRequestCache();
/**
* 下面的参数都应该进行封装
*/
@GetMapping("/login/authentication")
public Object loginAuthentication(HttpServletRequest request,HttpServletResponse response) throws IOException {
//获取缓存的请求
SavedRequest savedRequest = requestCache.getRequest(request, response);
/**
* 以html结尾的请求都跳转至登陆页面
* 通过ajax发送的请求给出相应的提示,前端在根据提示做对应处理
*/
if (savedRequest != null) {
String redirectUrl = savedRequest.getRedirectUrl();
if (StringUtils.endsWithIgnoreCase(redirectUrl, ".html")) {
redirectStrategy.sendRedirect(request, response, "/login.html");
}
}
return "需要进行身份验证"; // 这里应该封装
}
}
获取当前登录的用户信息
/**
* UserController
* @author majie
*
*/
@RestController
public class UserController {
/**
* 获取当前登录用户信息的三种方法
* spring会自动注入
* @param userDetails
* @return
*/
@GetMapping("/user1")
public Object getUserInfo(@AuthenticationPrincipal UserDetails userDetails) {
return userDetails;
}
@GetMapping("/user2")
public Object getUserInfo() {
return SecurityContextHolder.getContext().getAuthentication();
}
@GetMapping("/user3")
public Object getUserInfo(Authentication authentication) {
return authentication;
}
}
最后的项目结构:
接下来启动项目做测试:
我们访问localhost:8080/xxx.html的时候会自动跳转到localhost:8080/login.html
访问任意localhost:8080/xxx的时候会跳转到localhost:8080/login/authentication
通过表单登陆以后访问http://localhost:8080/user1,http://localhost:8080/user2,http://localhost:8080/user3都可以拿到对应的用户信息
项目源码地址:
https://gitee.com/mengcan/SpringSecurity.git