Springboot 登陆功能
时间: 2024-01-13 13:46:51 浏览: 26
Spring Boot 登录功能可以使用 Spring Security 来实现。Spring Security 是一个基于 Spring 的安全框架,提供了身份认证和授权的支持。
以下是实现 Spring Boot 登录的步骤:
1. 添加 Spring Security 依赖
在 pom.xml 文件中添加如下依赖:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
```
2. 配置 Spring Security
在 Spring Boot 应用程序的配置类中添加 @EnableWebSecurity 注解,同时继承 WebSecurityConfigurerAdapter 类,并覆盖 configure() 方法。在 configure() 方法中配置 Spring Security 的行为。
例如:
```
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/", "/home").permitAll() // 不需要身份认证的页面
.anyRequest().authenticated() // 其他页面需要身份认证
.and()
.formLogin().loginPage("/login").permitAll() // 登录页面
.and()
.logout().permitAll(); // 登出页面
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password("{noop}password").roles("USER"); // 添加一个用户
}
}
```
在上面的例子中,我们配置了:
- 不需要身份认证的页面是 / 和 /home
- 其他页面需要身份认证
- 登录页面是 /login
- 登出页面是默认的 /logout
- 添加了一个用户名为 user,密码为 password 的用户,并赋予 USER 角色
3. 添加登录页面
在 resources/templates 目录下添加 login.html 文件,该文件包含登录表单。
例如:
```
<!DOCTYPE html>
<html>
<head>
<title>登录</title>
</head>
<body>
<h2>登录</h2>
<form action="/login" method="POST">
<div>
<label for="username">用户名:</label>
<input type="text" id="username" name="username">
</div>
<div>
<label for="password">密码:</label>
<input type="password" id="password" name="password">
</div>
<button type="submit">登录</button>
</form>
</body>
</html>
```
4. 启动应用程序
在浏览器中访问应用程序的登录页面(例如 http://localhost:8080/login),输入用户名和密码进行登录。
以上就是使用 Spring Security 实现 Spring Boot 登录的过程。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)