请帮我用SpringBoot+Spring Security做一个登录拦截的demo
时间: 2023-07-25 15:21:25 浏览: 59
好的,下面是一个简单的基于 SpringBoot 和 Spring Security 的登录拦截 Demo:
1. 首先,需要添加 SpringBoot 和 Spring Security 的依赖,例如在 Maven 中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
```
2. 在 SpringBoot 主类中,添加 `@EnableWebSecurity` 注解和继承 `WebSecurityConfigurerAdapter` 类,并实现其中的 `configure(HttpSecurity http)` 方法,例如:
```java
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/secure/**").authenticated()
.anyRequest().permitAll()
.and()
.formLogin().loginPage("/login").defaultSuccessURL("/secure/home").permitAll()
.and()
.logout().logoutUrl("/logout").logoutSuccessUrl("/login").permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin").password("{noop}123456").roles("USER");
}
}
```
上面的代码中,`@EnableWebSecurity` 注解开启了 Spring Security 的 Web 安全功能。`configure(HttpSecurity http)` 方法定义了 HTTP 请求的安全配置,`.antMatchers("/secure/**").authenticated()` 定义了需要认证的 URL,`.formLogin().loginPage("/login").defaultSuccessURL("/secure/home").permitAll()` 定义了登录页面的 URL 和登录成功后的默认页面,`.logout().logoutUrl("/logout").logoutSuccessUrl("/login").permitAll()` 定义了退出登录后的跳转页面。`configure(AuthenticationManagerBuilder auth)` 方法定义了用户认证方式,这里使用了内存中的用户信息。
3. 添加登录页面和安全页面:
在 `login.html` 中,添加登录表单:
```html
<form method="post" action="/login">
<input type="text" name="username" placeholder="Username" />
<input type="password" name="password" placeholder="Password" />
<button type="submit">Login</button>
</form>
```
在 `home.html` 中,添加安全页面的内容。
4. 在 application.properties 中添加用户名和密码加密方式:
```properties
spring.security.user.password.encoder=noop
```
这样就完成了一个简单的基于 SpringBoot 和 Spring Security 的登录拦截 Demo。