Spring Security Spring Boot 应用中的403响应

nfg76nw0  于 2023-10-20  发布在  Spring
关注(0)|答案(2)|浏览(178)

我正在尝试编写一个spring Boot 应用程序,但是当我尝试通过向它发送POST请求来测试它时,无论请求如何,它都会返回403响应。即使我请求一个无效的链接,它仍然会响应403而不是404。我目前使用的是Spring版本3.1.3,但我也尝试过回到2.7.15等旧版本,以使用一些旧功能,如'WebSecurityConfigurerAdapter',我仍然无法修复它。我也试过禁用csrf,但似乎也不起作用。下面是一些文件,如“pom.xml”、“SecurityConfig.java”、“SecurityController.java”和“application.properties”。
pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.1.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>register</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>register</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>20</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</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-web</artifactId>
        </dependency>

        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.28</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

SecurityConfig.java

package register;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

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

    @Bean
    SecurityFilterChain web(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests((authorize) -> authorize
                        .requestMatchers("/api/**").hasAuthority("ROLE_myAuthority")
                        .anyRequest().authenticated()
                );
        // ...

        return http.build();
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        return http.csrf(AbstractHttpConfigurer::disable)
                .authorizeHttpRequests((requests) -> requests
                        .requestMatchers("/**").permitAll())
                .build();
    }

/*
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.authorizeRequests(authorizeRequests -> authorizeRequests.anyRequest()
                .permitAll());
        return http.build();
    }

 */
}

EmployeeController.java

package register;

//import com.example.RegisterLogin.Dto.EmployeeDTO;
//import com.example.RegisterLogin.Dto.LoginDTO;
//import com.example.RegisterLogin.Service.EmployeeService;
//import com.example.RegisterLogin.response.LoginResponse;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

@RestController
// @Secured("ROLE_myAuthority")
@CrossOrigin
@RequestMapping("/api/v1/employee")
public class EmployeeController {

    private EmployeeService employeeService;

    @PostMapping(path = "/save")
    public String saveEmployee(@RequestBody EmployeeDTO employeeDTO)
    {
        return employeeService.addEmployee(employeeDTO);
    }
}

application.properties

spring.application.name=register
server.port=8080

spring.jpa.hibernate.ddl-auto=create
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

spring.datasource.url=jdbc:mysql://localhost:3306/dbkms?createDatabaseIfNotExist=true
spring.datasource.username=username
spring.datasource.password=password

#jpa vendor adapter configuration

spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect
spring.jpa.generate-ddl=true
spring.jpa.show-sql=true
2sbarzqh

2sbarzqh1#

您面临的Spring Security为所有请求返回403 Forbidden错误的问题可能与您配置安全规则的方式有关。
确保SecurityConfig.java中的安全规则针对您的用例进行了正确配置。SecurityFilterChainSecurityFilterChain web(HttpSecurity http)配置可能相互冲突。尝试简化安全配置以隔离问题。
SecurityConfig.java中,定义了两个SecurityFilterChain bean。删除其中一个以避免冲突。例如,您可以保留SecurityFilterChain web(HttpSecurity http) bean并删除其他bean。

@Configuration
public class SecurityConfig {
    // ... (existing beans)

    @Bean
    SecurityFilterChain web(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests((authorize) -> authorize
                        .requestMatchers("/api/**").hasAuthority("ROLE_myAuthority")
                        .anyRequest().authenticated()
                );
        // ...

        return http.build();
    }
}

确保您在SecurityConfig.javaROLE_myAuthority)中签入的角色名称与分配给用户或端点的实际角色名称匹配。如果不匹配,Spring Security将不会授予访问权限,从而导致403错误。
此外,您可以启用Spring Security调试日志记录以获取有关身份验证和授权期间发生的事情的更多信息。将以下内容添加到application.properties文件中:

logging.level.org.springframework.security=DEBUG
zi8p0yeb

zi8p0yeb2#

修改您的FilterChain bean以:

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .csrf(AbstractHttpConfigurer::disable)
                .authorizeRequests(authorizeRequests -> authorizeRequests.anyRequest()
                .permitAll());
        return http.build();
}

最有可能的是,你应该使用你的第二个注解掉的代码片段,而不是:

@Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        return http.csrf(AbstractHttpConfigurer::disable)
                .authorizeHttpRequests(requests -> requests
                        .anyRequest().permitAll())
                .build();
    }

但是,一般来说,要么严格使用CSRF,要么禁用它,让你的安全性更细粒度,而不是只允许所有请求通过。

相关问题