創建一個新的Spring Security應用程序,并使用JDBC連接數據庫
在這個教程中,我們將學習如何創建一個新的Spring Security應用程序,使用JDBC連接數據庫以獲取用戶信息并進行認證。我們還將學習如何配置Spring Security以從數據庫中獲取用戶和權限信息,并使其與不同的模式和數據源一起工作。
1. 初始化Spring Boot項目
首先,我們需要創建一個新的Spring Boot項目。可以通過訪問 start.spring.io 并設置組名和項目名來完成。選擇以下依賴項:
Spring Web Starter
Spring Security Starter
H2 Database(用于本視頻中的內存數據庫)
JDBC API(用于與數據庫交互)
2. 創建HomeResource類
創建一個HomeResource類,并在其中定義幾個API端點:
/home:公開的端點,任何人都可以訪問
/user:僅用戶或管理員可以訪問
/admin:僅管理員可以訪問
@RestController
public class HomeResource {@GetMapping("/")public String home() {return "Welcome to the home page!";}@GetMapping("/user")public String user() {return "Welcome to the user page!";}@GetMapping("/admin")public String admin() {return "Welcome to the admin page!";}
}
- 配置Spring Security
創建一個SecurityConfiguration類,擴展WebSecurityConfigurerAdapter,以配置認證和授權。
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {@AutowiredDataSource dataSource;@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.jdbcAuthentication().dataSource(dataSource).usersByUsernameQuery("select username, password, enabled from users where username = ?").authoritiesByUsernameQuery("select username, authority from authorities where username = ?");}@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/admin").hasRole("ADMIN").antMatchers("/user").hasAnyRole("USER", "ADMIN").antMatchers("/").permitAll().and().formLogin();}@Beanpublic PasswordEncoder passwordEncoder() {return NoOpPasswordEncoder.getInstance();}
}
- 配置數據庫和數據源
在application.properties中配置H2數據庫和JDBC連接:
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.h2.console.enabled=true
spring.datasource.initialization-mode=always
5. 創建數據庫模式和初始化數據
在src/main/resources目錄下創建schema.sql和data.sql文件,分別定義數據庫模式和初始化數據。
schema.sql:在這里插入代碼片
CREATE TABLE users (username VARCHAR(50) NOT NULL PRIMARY KEY,password VARCHAR(50) NOT NULL,enabled BOOLEAN NOT NULL
);CREATE TABLE authorities (username VARCHAR(50) NOT NULL,authority VARCHAR(50) NOT NULL,FOREIGN KEY (username) REFERENCES users(username)
);CREATE UNIQUE INDEX ix_auth_username ON authorities (username, authority);
data.sql:
INSERT INTO users (username, password, enabled) VALUES ('user', 'pass', true);
INSERT INTO users (username, password, enabled) VALUES ('admin', 'pass', true);INSERT INTO authorities (username, authority) VALUES ('user', 'ROLE_USER');
INSERT INTO authorities (username, authority) VALUES ('admin', 'ROLE_ADMIN');
6. 啟動應用并測試
啟動應用并訪問不同的端點:
訪問/,任何人都可以訪問
訪問/user,需要用戶或管理員角色
訪問/admin,需要管理員角色
輸入相應的用戶名和密碼進行測試,例如user/pass和admin/pass。
結論
通過以上步驟,我們創建了一個使用Spring Security和JDBC進行用戶認證的Spring Boot應用程序。我們還學習了如何配置數據庫和數據源,以及如何初始化數據庫模式和數據。在實際應用中,可以使用類似的方法連接到外部數據庫,并根據需要調整數據庫模式和數據源配置。