Spring Boot提供了Spring Security來實現安全認證和授權功能。下面是一個簡單的示例來演示如何在Spring Boot中實現基本的安全認證和授權:
pom.xml
文件中添加Spring Security的依賴:<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
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();
}
}
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");
}
}
}
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類來定義更復雜的安全規則和用戶信息獲取方式。