如何使用Spring Security解决403 Forbidden错误?

niwlg2el  于 2023-10-16  发布在  Spring
关注(0)|答案(1)|浏览(197)

我第一次使用spring security做一个全栈应用程序。帐户的身份验证和激活工作正常。只是登录不起作用。
下面是我的UserController:

package com.example.PassMasterbackend.controller;

import com.example.PassMasterbackend.dto.AuthenticationDTO;
import com.example.PassMasterbackend.entity.Chest;
import com.example.PassMasterbackend.entity.User;
import com.example.PassMasterbackend.security.JwtService;
import com.example.PassMasterbackend.service.UserService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@Slf4j
@AllArgsConstructor
@RestController
@RequestMapping("/api/user")
public class UserController {

    private AuthenticationManager authenticationManager;
    private UserService userService;
    private JwtService jwtService;

    @PostMapping(path = "registration")
    public void register(@RequestBody User user) {
        this.userService.registration(user);
    }

    @PostMapping(path = "activation")
    public void activate(@RequestBody Map<String, String> activation) {
        this.userService.activation(activation);
    }

    @PostMapping(path = "login")
    public Map<String, String> login(@RequestBody AuthenticationDTO authenticationDTO) {
        System.out.println("username : " + authenticationDTO.username() + " - password : " + authenticationDTO.password());
        final Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(
                        authenticationDTO.username(),
                        authenticationDTO.password()
                )
        );

        if (authentication.isAuthenticated()) {
            return this.jwtService.generate(authenticationDTO.username());
        }
        return null;
    }

    @GetMapping
    public List<User> getAllUsers() {
        return userService.getAllUsers();
    }

    @GetMapping("/{id}")
    public User getUserById(@PathVariable Long id) {
        return userService.getUserById(id);
    }
}

这是我的安全文件

package com.example.PassMasterbackend.security;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import static org.springframework.http.HttpMethod.*;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    private final BCryptPasswordEncoder bCryptPasswordEncoder;
    private final JwtFilter jwtFilter;
    private final UserDetailsService userDetailsService;

    public SecurityConfig(BCryptPasswordEncoder bCryptPasswordEncoder, JwtFilter jwtFilter, UserDetailsService userDetailsService) {
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
        this.jwtFilter = jwtFilter;
        this.userDetailsService = userDetailsService;
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
        return httpSecurity
                .csrf(AbstractHttpConfigurer::disable)
                .authorizeHttpRequests(authorize ->
                        authorize
                                .requestMatchers(POST, "/api/user/registration").permitAll()
                                .requestMatchers(POST, "/api/user/activation").permitAll()
                                .requestMatchers(POST, "/api/user/login").permitAll()
                                .requestMatchers(GET, "/api/user").permitAll()
                                .requestMatchers(GET, "/api/user/{id}").permitAll()
                                .requestMatchers(GET, "/api/chests").permitAll()
                                .requestMatchers(GET, "/api/chests/{id}").permitAll()
                                .requestMatchers(POST, "/api/chests").permitAll()
                                .requestMatchers(PUT, "/api/chests/{id}").permitAll()
                                .requestMatchers(DELETE, "/api/chests/{id}").permitAll()
                                .anyRequest().authenticated()
                )
                .sessionManagement(httpSecuritySessionManagementConfigurer ->
                        httpSecuritySessionManagementConfigurer.sessionCreationPolicy(
                                SessionCreationPolicy.STATELESS
                        )
                )
                .addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class)
                .build();
    }

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }

    @Bean
    public AuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setUserDetailsService(userDetailsService);
        daoAuthenticationProvider.setPasswordEncoder(bCryptPasswordEncoder);
        return daoAuthenticationProvider;
    }
}

当我在这个URL上使用Postman发出POST请求时:http://localhost:8080/api/user/login,我每次都得到一个403 Forbidden,控制台没有错误。我的身体请求看起来像这样:

{
    "username": "[email protected]",
    "password": "mdp"
}

我已经有一个验证过的帐户和这个邮件和密码。
有人有答案吗?非常感谢您!!

r1zk6ea1

r1zk6ea11#

正如我在Spring中所经历的那样,我记得有些错误可能不会被正确抛出,特别是对于安全端点,我会说也许你在调试模式下在本地运行它,然后你必须知道运行什么代码来验证你的请求以在其中设置调试断点,然后尝试并遵循它将去的所有调用堆栈,也许你会发现一些捕获异常的地方并将它们悄悄地转换为403.

相关问题