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

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

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

Spring Boot 项目创建

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

  1. $ 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

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

  1. <?xml version="1.0" encoding="UTF-8"?><project>
  2. <dependencies>
  3. <dependency>
  4. <groupId>org.springframework.boot</groupId>
  5. <artifactId>spring-boot-starter-data-rest</artifactId>
  6. </dependency>
  7. <dependency>
  8. <groupId>org.springframework.boot</groupId>
  9. <artifactId>spring-boot-starter-security</artifactId>
  10. </dependency>
  11. <dependency>
  12. <groupId>org.springframework.boot</groupId>
  13. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  14. </dependency>
  15. <dependency>
  16. <groupId>org.springframework.boot</groupId>
  17. <artifactId>spring-boot-starter-web</artifactId>
  18. </dependency>
  19. <dependency>
  20. <groupId>org.springframework.boot</groupId>
  21. <artifactId>spring-boot-starter-test</artifactId>
  22. <scope>test</scope>
  23. </dependency>
  24. </dependencies>
  25. </project>

将创建以下项目树:

  1. 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 控制器来测试它:

  1. package com.example;
  2. import org.springframework.web.bind.annotation.RequestMapping;
  3. import org.springframework.web.bind.annotation.RestController;
  4. @RestController
  5. public class SampleController {
  6. @RequestMapping("/greeting")
  7. public String greeting() {
  8. return "Hello world!";
  9. }
  10. }

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

  1. $ ./mvnw spring-boot:run

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

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

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

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

在 application.properties 中配置安全性

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

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

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

内存安全

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

  1. import org.springframework.beans.factory.annotation.Autowired;
  2. import org.springframework.context.annotation.Configuration;
  3. import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
  4. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  5. import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
  6. @Configuration
  7. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  8. @Override
  9. protected void configure(HttpSecurity http) throws Exception {
  10. http.authorizeRequests().anyRequest().authenticated().and().httpBasic();
  11. }
  12. @Autowired
  13. public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
  14. auth.inMemoryAuthentication().withUser("user").password("password").roles("USER");
  15. }
  16. }

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

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

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

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

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

  1. $ ./mvnw spring-boot:run

数据库安全

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

  1. $ 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 映像:

  1. 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 中包含用于对数据库进行身份验证的数据源设置:

  1. 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

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

  1. 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”,我们使用以下方法加密:

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

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

  1. package com.example;
  2. import javax.sql.DataSource;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
  5. import org.springframework.context.annotation.Configuration;
  6. import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
  7. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  8. import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
  9. import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  10. @Configuration
  11. @EnableAutoConfiguration
  12. public class DatabaseSecurityConfiguration extends WebSecurityConfigurerAdapter {
  13. @Autowired DataSource dataSource;
  14. @Override
  15. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  16. auth.jdbcAuthentication()
  17. .dataSource(dataSource)
  18. .usersByUsernameQuery("select username, password, enabled" + " from users where username=?")
  19. .authoritiesByUsernameQuery(
  20. "select username, authority " + "from authorities where username=?")
  21. .passwordEncoder(new BCryptPasswordEncoder());
  22. }
  23. @Override
  24. protected void configure(HttpSecurity http) throws Exception {
  25. http.authorizeRequests().anyRequest().hasAnyRole("ADMIN", "USER").and().httpBasic();
  26. }
  27. }

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

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

相关文章