使用内存和数据库配置 Spring Boot 身份验证

x33g5p2x  于2022-10-05 转载在 Spring  
字(6.8k)|赞(0)|评价(0)|浏览(371)

在本教程中,我们将学习如何使用从默认安全用户/密码到内存安全的不同安全提供程序来保护 Spring Boot Web 应用程序。最后,我们将切换到使用 mysql 作为数据库的数据库身份验证。

Spring Boot 项目创建

起点是在您的 Spring initializr 中包含 spring-boot-starter-security。首先创建您的项目,如下所示:

$ mkdir spring-boot-secure $ cd spring-boot-secure $ spring init -d=web,thymeleaf,data-rest,security -g=com.example -a=spring-boot-secure --package-name=com.example -name=spring-boot-secure -x

以下依赖项列表将添加到您的项目中:

<?xml version="1.0" encoding="UTF-8"?><project>
   <dependencies>
            
      <dependency>
                
         <groupId>org.springframework.boot</groupId>
                
         <artifactId>spring-boot-starter-data-rest</artifactId>
             
      </dependency>
          
      <dependency>
                
         <groupId>org.springframework.boot</groupId>
                
         <artifactId>spring-boot-starter-security</artifactId>
             
      </dependency>
          
      <dependency>
                
         <groupId>org.springframework.boot</groupId>
                
         <artifactId>spring-boot-starter-thymeleaf</artifactId>
             
      </dependency>
          
      <dependency>
                
         <groupId>org.springframework.boot</groupId>
                
         <artifactId>spring-boot-starter-web</artifactId>
             
      </dependency>
          
      <dependency>
                
         <groupId>org.springframework.boot</groupId>
                
         <artifactId>spring-boot-starter-test</artifactId>
                
         <scope>test</scope>
             
      </dependency>
       
   </dependencies>
    
</project>

将创建以下项目树:

spring-boot-secure/ ├── mvnw ├── mvnw.cmd ├── pom.xml └── src     ├── main     │   ├── java     │   │   └── com     │   │       └── example     │   │           └── SpringBootSecureApplication.java     │   └── resources     │       ├── application.properties     │       ├── static     │       └── templates     └── test         └── java             └── com                 └── example                     └── SpringBootSecureApplicationTests.java

接下来,让我们在我们的应用程序中添加一个最小的 REST 控制器来测试它:

package com.example;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SampleController {
  @RequestMapping("/greeting")
  public String greeting() {
    return "Hello world!";
  }
}

现在启动我们的应用程序:

$ ./mvnw spring-boot:run

从日志中可以看出,已为默认用户“user”自动生成了一个安全密码:

Using generated security password: 96172694-a2ef-4fa6-8797-ef5dea54fef5

现在,如果您尝试访问 /greeting REST 服务,将显示一个基本身份验证窗口:

如果您输入用户名“user”和控制台上打印的密码,您将能够访问您的 REST 服务。

在 application.properties 中配置安全性

下一步,将在 application.properties 文件中添加用户名和密码。这将替换默认用户和密码:

# Security spring.security.user.password=mypassword spring.security.user.name=myuser

重新启动您的应用程序并验证您是否能够使用“myuser”和“mypassword”登录。

内存安全

使用 application.properties 文件并不是真正的解决方案。下一步,让我们看看如何使用内存中安全性。要在 Spring Boot 中启用 HTTP 安全性,我们需要扩展 WebSecurityConfigurerAdapter 并在 configure(HttpSecurity http) 方法中提供默认配置:

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.WebSecurityConfigurerAdapter;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().anyRequest().authenticated().and().httpBasic();
  }

  @Autowired
  public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication().withUser("user").password("password").roles("USER");
  }
}

我们在 configureGlobal 方法中为用户提供了一个角色。调用此方法来自动连接 AuthenticationManagerBuilder。

AuthenticationManagerBuilder 允许您通过添加 UserDetailsS​​ervice 和身份验证提供程序轻松构建身份验证。在这种情况下,它将使用内存,因为它正在调用 inMemoryAuthentication 方法并使用他们的密码和角色设置两个用户。

在运行应用程序之前,让我们在 application.properties 中注释用户:

# Security  #spring.security.user.password=mypassword #spring.security.user.name=myuser

现在启动我们的应用程序并尝试使用“用户”和“密码”凭据请求我们的 REST 资源:

$ ./mvnw spring-boot:run

数据库安全

最后一步是将提供者更改为数据库。为了做到这一点,我们的示例应用程序将需要一些额外的依赖项,假设 MySQL 将用作数据库:

$ spring init -d=web,thymeleaf,data-jpa,data-rest,mysql,security -g=com.example -a=spring-boot-secure --package-name=com.example -name=spring-boot-secure -x

我们将使用 MySQL 启动它的 Docker 映像:

docker run -d  -p 3306:3306 -e MYSQL_USER=spring -e MYSQL_PASSWORD=spring -e MYSQL_DATABASE=mysqlschema -e MYSQL_ROOT_PASSWORD=secret mysql

然后,我们将在 application.properties 中包含用于对数据库进行身份验证的数据源设置:

spring.datasource.url = jdbc:mysql://172.17.0.2:3306/mysqlschema spring.datasource.username = spring spring.datasource.password = spring spring.datasource.testWhileIdle = true spring.datasource.validationQuery = SELECT 1 spring.jpa.show-sql = true spring.jpa.hibernate.ddl-auto = create-drop spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect spring.data.rest.basePath

现在让我们连接到我们的数据库并定义表和一些用户:

create table users(     -> username varchar(50) not null primary key,     -> password varchar(100) not null,     -> enabled boolean not null     -> );  mysql> create table authorities (     -> username varchar(50) not null,     -> authority varchar(50) not null,     -> constraint fk_authorities_users foreign key(username) references users(username)     -> );  mysql> create unique index ix_auth_username on authorities (username,authority);  mysql> insert into users(username,password,enabled)     -> values('admin','$2a$10$.phOScfrUCA7zY5n9CK7cOKNft4HMfwqkVZYUAE1azFeXpK0WcnSa',true);  mysql> insert into authorities(username,authority)      -> values('admin','ROLE_ADMIN');

如您所见,我们为用户 admin 包含了一个加密密码。密码是“admin”,我们使用以下方法加密:

String encoded = new BCryptPasswordEncoder().encode("admin");
System.out.println(encoded);

现在只需更改用于身份验证的 Provider 即可。在这种情况下,我们将使用 jdbcAuthentication 提供查询来检索用户名和角色:

package com.example;

import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
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.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
@EnableAutoConfiguration
public class DatabaseSecurityConfiguration extends WebSecurityConfigurerAdapter {
  @Autowired DataSource dataSource;

  @Override
  protected 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=?")
        .passwordEncoder(new BCryptPasswordEncoder());
  }

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().anyRequest().hasAnyRole("ADMIN", "USER").and().httpBasic();
  }
}

就这样!验证身份验证是否适用于我们插入的用户(管理员/管理员)。

恭喜,您刚刚使用从默认安全用户/密码到内存安全的不同安全组合完成了 Spring Boot 身份验证。最后,我们将切换到使用 mysql 作为数据库的数据库身份验证。

相关文章

微信公众号

最新文章

更多