java - Spring Boot启动器安全性未进行身份验证

标签 java spring spring-boot spring-mvc spring-security

我是 Spring Boot 安全新手,正在学习本教程:

https://www.baeldung.com/spring-security-jdbc-authentication

我正在使用 POSTMAN 进行测试。

我在授权 -> 类型中使用了 Type = Basic Auth

用户名/密码=admin/12345

我尝试了一切,但总是得到以下响应:

{
    "timestamp": "2019-10-11T16:03:23.463+0000",
    "status": 401,
    "error": "Unauthorized",
    "message": "Unauthorized",
    "path": "/api/user"
}    

其中一个网址:

http://localhost:8080/api/user

这是我的安全配置:

package com.spr.security;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
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.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import com.spr.util.Constants;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter 
{
    @Autowired
    private DataSource dataSource;

    @Autowired
    private PasswordEncoder passwordEncoder;

    protected void configure(HttpSecurity http) throws Exception 
    {
        http.httpBasic()
            .and()
            .authorizeRequests()
            .antMatchers("/api/**").hasRole("USER")
            .antMatchers("/admin/**").hasRole("ADMIN")
            .and()
            .csrf().disable()
            .headers().frameOptions().disable();
    }

    @Autowired
    protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception 
    {
            auth.jdbcAuthentication().dataSource(dataSource).passwordEncoder(passwordEncoder);  

        /*
         * By default spring security assumes `users` table for storing users 
         * and `authorities` table for storing roles
         */
    }

    @Bean
    public PasswordEncoder passwordEncoder() 
    {
        return new BCryptPasswordEncoder();
    }
}

还尝试过:

auth.jdbcAuthentication().dataSource(dataSource).passwordEncoder(new BCryptPasswordEncoder());  

我使用实体创建了下表。

users
    id int AUTO_INCREMENT (PK)
    username UNIQUE varchar(256)
    email varchar(256)

authorities
    username varchar(256)
    authority varchar(256)

每个表只有一条记录

在用户中:

username = admin
password = $2y$10$llcw8Cbuww90KW1dYB6Rn.98iM0JyTiC1VBT1WveVKz99VqbhFLpG
email = abc@test.com

密码在 bcrypt-generator.com 上经过 12345 哈希处理,强度为 10

当局:

username = admin
authority = ROLE_USER

我也尝试过权限= USER

我的 pom.xml 中有以下依赖项

<!-- Spring data JPA -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<!-- spring security -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

        <!-- for jdbc authentication -->
        <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

我的application.properties文件

## Spring DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.url=jdbc:mysql://localhost:3306/sprboot?useSSL=false&serverTimezone=UTC
spring.datasource.username=spr
spring.datasource.password=boot


## Hibernate Properties
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect

# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto=validate

spring.jackson.serialization.fail-on-empty-beans=false

spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration
logging.level.org.springframework.security=DEBUG

没有 Spring Security,我的所有路径、 Controller 、jpa 等都可以正常工作。

我在这里做错了什么?

还需要更多信息吗?

编辑

有没有办法在日志窗口(控制台)中查看Spring Security身份验证sql 我在 application.properties 中添加了以下内容,但没有显示生成的 sql

spring.jpa.show-sql=true
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type=TRACE
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
logging.level.org.springframework.security=DEBUG

我使用的是mysql数据库

最佳答案

有两个问题,我是这样解决的:

hasRole()更改为hasAuthority()

protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.httpBasic()
            .and()
            .authorizeRequests()
            .antMatchers("/api/**").hasAuthority("USER")
            .antMatchers("/admin/**").hasAuthority("ADMIN")
            .and()
            .csrf().disable()
            .headers().frameOptions().disable();
    }

我在堆栈溢出的另一个链接中发现 Spring Security 中存在一个错误,bcrypted 密码应以 $2a... 开头,而不是 $2b...$2y...

关于java - Spring Boot启动器安全性未进行身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58345156/

相关文章:

java - Spring基于范围的默认配置文件选择

java - 使用 Java JJWT 签名生成在 jwt.io 调试器中失败

Spring-boot LDAP 自定义 UserDetails

java - 如何将字符串返回为json格式

spring - 如何覆盖Spring Cloud Ribbon中的ribbon.serverListRefreshInterval默认值?

spring - 创建自定义AuthenticationSuccessHandler并在完成后调用默认的AuthenticationSuccessHandler

java - 应用程序无法启动

java - TestNG - 如何通过 testng.xml 设置运行 @Test 方法的顺序?

java - 如何将图像 dpi 从 96 dpi 调整为 72 dpi

java - 在Java中,为什么@Nullable有运行时保留