springboot整合security代码登录验证拦截器
时间: 2023-09-17 12:09:16 浏览: 50
Spring Boot整合Security实现登录验证拦截器,可以通过以下步骤完成:
1.添加Security依赖
在pom.xml文件中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
```
2.配置Security
在配置类中添加@EnableWebSecurity注解,并继承WebSecurityConfigurerAdapter类,实现configure()方法,配置Security相关信息,如登录页面、成功页面、失败页面等:
```java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/login").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/success")
.failureUrl("/error")
.permitAll()
.and()
.logout()
.logoutSuccessUrl("/login")
.permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
}
```
3.添加登录页面
在templates目录下添加login.html页面,实现用户登录表单,如下所示:
```html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Login Page</title>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<body>
<h1>Login Page</h1>
<div th:if="${param.error}">
Invalid username and password.
</div>
<div th:if="${param.logout}">
You have been logged out.
</div>
<form th:action="@{/login}" method="post">
<div>
<label for="username">Username:</label>
<input type="text" id="username" name="username" />
</div>
<div>
<label for="password">Password:</label>
<input type="password" id="password" name="password" />
</div>
<div>
<input type="submit" value="Login" />
</div>
</form>
</body>
</html>
```
4.添加成功页面和失败页面
在templates目录下添加success.html和error.html页面,用于显示用户登录成功和失败的信息。
5.添加拦截器
在Controller中添加拦截器,实现对指定的URL进行拦截,如下所示:
```java
@Controller
public class HomeController {
@GetMapping("/")
public String home() {
return "home";
}
@GetMapping("/login")
public String login() {
return "login";
}
@GetMapping("/success")
public String success() {
return "success";
}
@GetMapping("/error")
public String error() {
return "error";
}
@GetMapping("/admin")
public String admin() {
return "admin";
}
}
```
6.测试登录验证拦截器
启动应用,通过浏览器访问http://localhost:8080/admin,应该会自动跳转到登录页面,输入用户名和密码,登录成功后会跳转到成功页面,否则会跳转到失败页面。