spring-security 403禁止-带 Spring Boot 的Spring安全装置

6ie5vjzr  于 2022-11-11  发布在  Spring
关注(0)|答案(1)|浏览(201)

我有我的Spring Boot 应用程序,我试图添加 Spring 安全,但当我通过 Postman 做一个请求,我不断得到一个403禁止,在线我发现我应该添加:“.csrf().disable()”添加到我的配置中,但它不起作用(如果我将路径为:许可证中的“人/**”All())
这里是我代码:

@Data
@AllArgsConstructor
@NoArgsConstructor
@Document("User")
public class User {
    @Id
    private String id;
    private String name;
    private String password;
    private String email;
    private Set<UserRole> roles;
}

public class SecurityConfig extends WebSecurityConfigurerAdapter {
    private final UserDetailsService userDetailsService;
    private final BCryptPasswordEncoder encoder;
  @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(encoder);}

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        log.info("HttpSecurity: {}",http);
        http.authorizeRequests()
                .antMatchers( "/user/saveUser").permitAll()
                .antMatchers("/person/**").hasAnyRole()
                .and().csrf().disable().cors().disable();}
}

public class UserService implements UserDetailsService{
    private final UserRepository userRepo;
    private final BCryptPasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
        log.info("mail request: {}",email);
        Optional<User> opt = userRepo.findUserByEmail(email);
        log.info("Find user: {}", opt);
        org.springframework.security.core.userdetails.User springUser=null;

        if(opt.isEmpty()) {
            throw new UsernameNotFoundException("User with email: " +email +" not found");
        }else {
            User user =opt.get();
            Set<UserRole> roles = user.getRoles();
            Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
            for(UserRole role:roles) {
                grantedAuthorities.add(new SimpleGrantedAuthority(role.name()));
            }
            springUser = new org.springframework.security.core.userdetails.User(
                    email,
                    user.getPassword(),
                    grantedAuthorities );

        }
        return springUser;
    }

我的用户控制器:

@RestController
    @RequestMapping("user")
public class UserController {
    private final UserService userService;
    @PostMapping("/saveUser")
    public ResponseEntity<String> saveUser(@RequestBody User user) {
        log.info("Registering User: {}", user);
        userService.saveUser(user);
        return ResponseEntity.ok("registered User");
    }
}

我的个人控制器:(我得到403的方法)@ REST控制器
@请求Map(“人”)公共类PersonController { @自动连线的PersonService个人服务;返回响应实体.ok(“/获取全部”);}
这是我第一次使用Spring Security,我在网上看了一个教程,但我真的不明白为什么每次我把我的请求放在安全系统中,它仍然得到403禁止

w41d8nur

w41d8nur1#

我认为您可能需要将@Configuration@EnableWebSecurity注解添加到SecurityConfig类中,因为如果没有它们,spring-security将无法看到您的安全配置。
参见参考文档:https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/config/annotation/web/configuration/EnableWebSecurity.html
还要注意的是,WebSecurityConfigurerAdapter在5.7.0-M2之后是deprecated,所以如果您使用更高版本的spring-security,您可以考虑创建一个类型为SecurityFilterChain的bean来配置应用中的安全性。

相关问题