Spring-Security 使用 spring-boot 和 JDBC 身份驗證
假設你想要阻止未經授權的使用者訪問該頁面,那麼你必須通過授權訪問來阻止他們。我們可以通過使用 spring-security 來實現這一點,spring-security 通過保護所有 HTTP 端點來提供基本身份驗證。為此,你需要為專案新增 spring-security 依賴項,在 maven 中我們可以將依賴項新增為:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
這是一個安全配置,可確保只有經過身份驗證的使用者才能訪問。
@Configuration
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
DataSource datasource;
@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
            .anyRequest()
            .fullyAuthenticated()
            .and()
        .formLogin()
            .loginPage("/login")
            .failureUrl("/login?error")
            .permitAll()
            .and()
        .logout()
            .logoutUrl("/logout")
            .logoutSuccessUrl("/login?logout")
            .permitAll()
            .and()
        .csrf();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.jdbcAuthentication().dataSource(datasource).passwordEncoder(passwordEncoder());
}
@Bean
public PasswordEncoder passwordEncoder() {
    PasswordEncoder encoder = new BCryptPasswordEncoder();
    return encoder;
}
}
| 組態 | 描述 | 
|---|---|
@Configuration | 
表示 Spring IoC 容器可以將該類用作 bean 定義的源。 | 
@Order (SecurityProperties.ACCESS_OVERRIDE_ORDER) | 
覆蓋訪問規則而不更改任何其他自動配置的功能。較低的值具有較高的優先順序 | 
WebSecurityConfigurerAdapter | 
SecurityConfig 類擴充套件並覆蓋其幾個方法來設定安全配置的一些細節。 | 
@Autowired of DataSource | 
提供工廠以連線到物理資料來源。 | 
configure(HttpSecurity) | 
重寫方法定義應該保護哪些 URL 路徑,哪些不應該保護。 | 
.authorizeRequests().anyRequest() .fullyAuthenticated() | 
表示要對我們的應用程式的所有請求進行身份驗證。 | 
.formLogin() | 
配置基於表單的登入 | 
.loginPage("/login").failureUrl("/login?error").permitAll() | 
指定登入頁面的位置,並允許所有使用者訪問該頁面。 | 
.logout().logoutUrl("/logout") .logoutSuccessUrl("/login?logout").permitAll() | 
登出後重定向到的 URL。預設為/ login?logout。 | 
.csrf() | 
用於防止跨站點請求偽造,啟用 CSRF 保護(預設)。 | 
configure(AuthenticationManagerBuilder){} | 
重寫方法,用於定義使用者的身份驗證方式。 | 
.jdbcAuthentication().dataSource(datasource) | 
表示我們正在使用 JDBC 身份驗證 | 
.passwordEncoder(passwordEncoder()) | 
表示我們正在使用密碼編碼器來編碼我們的密碼。 (建立一個 bean 來返回密碼 Encoder 的選擇,我們在這種情況下使用 BCrypt) | 
請注意,我們尚未配置任何要使用的表名或任何查詢,這是因為預設情況下 spring security 會查詢下表:
create table users (   
  username varchar(50) not null primary key,
  password varchar(255) 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),
  unique index authorities_idx_1 (username, authority));
將以下行插入上表:
INSERT INTO authorities(username,authority) 
VALUES ('user', 'ROLE_ADMIN');
INSERT INTO users(username,password,enabled)
VALUES('user', '$2a$10$JvqOtJaDys0yoXPX9w47YOqu9wZr/PkN1dJqjG9HHAzMyu9EV1R4m', '1');
在我們的例子中,使用者名稱是 user,密碼也是用 BCrypt 演算法加密的 user
最後,在 application.properties 中配置資料來源以使用 spring boot:
spring.datasource.url = jdbc:mysql://localhost:3306/spring
spring.datasource.username = root
spring.datasource.password = Welcome123
注意: 建立並配置登入控制器並將其對映到路徑/login,並將登入頁面指向此控制器