我第一次使用 Spring Security 做一个全栈应用程序。 帐户的身份验证和激活工作正常。只有登录不起作用。
这是我的用户控制器:
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;
}
}
当我使用 Postman 在此 URL 上发出 POST 请求时:http://localhost:8080/api/user/login,每次都会收到 403 Forbidden,但控制台中没有错误。我的身体要求看起来像这样:
{
"username": "[email protected]",
"password": "mdp"
}
并且我已经使用此邮件和此密码拥有一个经过验证的帐户。
有人有答案吗? 非常感谢!!
根据我使用 Spring 的经验,我记得一些错误可能无法正确抛出,特别是对于安全端点,我想说也许您在本地以调试模式运行它,然后您必须知道运行哪些代码来验证您的请求在其中设置调试断点,然后尝试跟踪它将执行的所有调用堆栈,也许您会发现一些捕获异常并默默地将它们转换为 403 的地方...