Spring Boot提供了Spring Security来实现安全认证和授权功能。下面是一个简单的示例来演示如何在Spring Boot中实现基本的安全认证和授权:
- 添加依赖:在
pom.xml
文件中添加Spring Security的依赖:
org.springframework.boot spring-boot-starter-security
- 创建一个WebSecurityConfig类来配置安全规则:
import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/admin/**").hasRole("ADMIN") .antMatchers("/user/**").hasRole("USER") .anyRequest().authenticated() .and() .formLogin() .and() .httpBasic(); } }
- 创建一个UserDetailsService实现类来获取用户信息:
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 CustomUserDetailsService implements UserDetailsService { @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { if ("admin".equals(username)) { return User.withDefaultPasswordEncoder().username("admin").password("admin").roles("ADMIN").build(); } else if ("user".equals(username)) { return User.withDefaultPasswordEncoder().username("user").password("user").roles("USER").build(); } else { throw new UsernameNotFoundException("User not found"); } } }
- 创建一个Controller来测试安全认证和授权:
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class TestController { @GetMapping("/admin/test") public String adminTest() { return "Admin test"; } @GetMapping("/user/test") public String userTest() { return "User test"; } }
这样就可以在Spring Boot中实现基本的安全认证和授权功能了。当访问/admin/test
时需要ADMIN角色才能访问,访问/user/test
时需要USER角色才能访问。可以通过配置WebSecurityConfig类来定义更复杂的安全规则和用户信息获取方式。