spring 中的认证
时间: 2024-03-20 22:45:28 浏览: 6
Spring框架提供了多种认证机制,其中最常见的是基于用户名和密码的表单认证,下面是一个简单的Spring Security的认证示例:
1. 添加Spring Security依赖:在pom.xml中添加以下依赖:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
```
2. 配置Spring Security:在Spring Boot的配置类中添加以下配置:
```
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password("{noop}password").roles("USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.httpBasic();
}
}
```
这里使用了内存身份验证机制,用户名是"user",密码是"password",角色是"USER"。配置中还指定了任何请求都需要身份验证、使用表单登录和HTTP Basic身份验证。
3. 添加登录表单:在Spring Boot的模板文件中添加登录表单:
```
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<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>
<button type="submit">Login</button>
</form>
</body>
</html>
```
4. 测试认证:启动应用程序并访问http://localhost:8080/login,输入用户名和密码进行登录,验证身份认证是否成功。
除了基于表单的认证,Spring Security还支持其他多种认证方式,如基于LDAP、OAuth等,可以根据具体需求进行选择和配置。