四、实验(训)方法与步骤 1.配置 Spring Security。 2.创建用户认证服务。 3.定义访问控制拦截器。 4.测试登录流程。代码
时间: 2025-01-06 10:50:08 浏览: 2
好的,下面是一个详细的步骤指南,用于配置Spring Security、创建用户认证服务、定义访问控制拦截器以及测试登录流程。
### 1. 配置 Spring Security
首先,在你的Spring Boot项目中引入Spring Security的依赖。在`pom.xml`文件中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
```
### 2. 创建用户认证服务
创建一个类来实现`UserDetailsService`接口,用于加载用户特定的数据。
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
@Service
public class MyUserDetailsService implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
com.example.demo.model.User user = userRepository.findByUsername(username);
if (user == null) {
throw new UsernameNotFoundException("User not found");
}
return User.withUsername(user.getUsername())
.password(user.getPassword())
.roles(user.getRoles().toArray(new String[0]))
.build();
}
}
```
### 3. 定义访问控制拦截器
创建一个配置类来定义访问控制规则。
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private MyUserDetailsService userDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/user/**").hasAnyRole("USER", "ADMIN")
.anyRequest().authenticated()
.and()
.formLogin()
.permitAll()
.and()
.logout()
.permitAll();
}
}
```
### 4. 测试登录流程
启动你的Spring Boot应用,并访问一个受保护的资源。你将被重定向到登录页面。输入有效的用户名和密码后,你应该能够成功登录并访问资源。
#### 示例代码
```java
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class LoginTest {
@Test
public void testLogin() {
// 这里可以使用Selenium或RestAssured进行登录测试
// 示例使用RestAssured
given()
.auth().form("username", "password")
.when()
.get("/admin/dashboard")
.then()
.statusCode(200);
}
}
```
阅读全文