Spring boot Spring自定义安全,MySQL和JPA提供403访问被拒绝

Spring boot Spring自定义安全,MySQL和JPA提供403访问被拒绝,spring-boot,spring-security,spring-data-jpa,spring-security-rest,Spring Boot,Spring Security,Spring Data Jpa,Spring Security Rest,我试图通过使用UserDetailsService提供身份验证来访问postman上的RESTAPI,但每次我都会在403访问被拒绝时触发请求。POST和GET方法的行为相同。我已经阅读了论坛上的其他问题,但每个答案都说这是由于CSRF,我禁用了它,但问题仍然是一样的 完整代码位于: 请帮帮我,我从3天以来一直在努力解决这个问题 @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true)

我试图通过使用UserDetailsService提供身份验证来访问postman上的RESTAPI,但每次我都会在403访问被拒绝时触发请求。POST和GET方法的行为相同。我已经阅读了论坛上的其他问题,但每个答案都说这是由于CSRF,我禁用了它,但问题仍然是一样的

完整代码位于:

请帮帮我,我从3天以来一直在努力解决这个问题

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class ApplicationSecurityConfig extends WebSecurityConfigurerAdapter implements WebMvcConfigurer{

@Autowired
UserDetailsService userDetailsService;

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth
        .userDetailsService(userDetailsService)
        .passwordEncoder(passwordEncoder());
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable();
    http
        .authorizeRequests()
            .antMatchers("/api/**").authenticated().anyRequest().hasAnyRole("ADMIN");
}

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

@Override
public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**").allowedMethods("*");
}
}



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

@Autowired
private UserService userService;

@GetMapping(path = "/users")
public User getUserById(@RequestParam("userId") Integer userId) {
    return userService.getUserById(userId);
}

@PostMapping(path = "/users", consumes = MediaType.APPLICATION_JSON_VALUE)
public User addUser(@RequestBody User user) {
    return userService.addUser(user);
}
}

我发现您的安全配置存在两个问题:

  • 基本身份验证未启用,但您正在尝试在postman中执行基本身份验证
  • 执行以下操作以启用基本身份验证

            http
                .authorizeRequests()
                    ...
                    .and()
                    .httpBasic();
    
  • 我猜POST/api/users是一个用户注册端点。您必须将此端点列入白名单,以便任何人都可以注册
  • 测试:

    创建用户

    POST: localhost:8080/api/users
    
    {
            "userName" : "user1",
            "password": "pass"
    }
    
    获取用户信息

    
    GET: localhost:8080/api/users?userId=1   //use the correct ID
    
    With Basic Auth: userName = user1, password = pass
    
    
    奖金反馈:

  • User.userName-->您可能希望使此字段唯一
  • @Repository
    存储库界面中不需要此注释
  • 用户服务接口。我看不出有任何理由使用接口和impl

  • 你们有在控制台上打印的东西吗?这似乎不是一个春季安全问题。spring通常返回401,如果安全性不允许控制台出现错误,请您帮助理解代码中的错误。我已经提供了有问题的git存储库url。我下载了repo。但无法在本地导入。看起来构建也有一些问题。让我再试一次,我仍然无法加载您的项目并运行。获取一些配置问题。如果我成功,将更新。好的。非常感谢。请让我知道,如果你发现一些不正确的地方。谢谢你,我已经按照建议做了更改,代码现在正在按预期工作。
    
    GET: localhost:8080/api/users?userId=1   //use the correct ID
    
    With Basic Auth: userName = user1, password = pass