403禁止 - 带有弹簧靴的弹簧安全

发布于 2025-02-11 09:05:27 字数 3004 浏览 0 评论 0 原文

我有我的Spring Boot应用程序,并且正在尝试增加Spring Security,但是当我通过Postman提出请求时,我会继续获得403 Forbbiden, 在线我发现我shoud添加了:“ .csrf()。disable()”到我的配置中,但它不起作用 (如果我将方法放在路径上:“ person/**'在许可证())的

(我的代码:

@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) @RestController
@requestmapping(“人”) 公共类PersonController { @Autowired Persemservice Perservice; @getMapping(“/getall”) 公共响应性&lt; list&gt; getall()抛出ioexception { 返回响应词。ok(personService.findall()); }

这是我第一次使用春季安全性,我在线遵循了一个教程,但我真的无法弄清楚为什么我将请求放在安全状态下,它仍然被禁止403

I have my spring boot application and I'm trying to add spring security but when I do a request through postman I keep getting a 403 Forbbiden,
Online I found I shoud add: ".csrf().disable()" to my configure but it didn't work
(Everithing works if I put the method with path: "person/**" in the permitAll())

here my code:

@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;
    }

My controller for User:

    @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");
    }
}

My person controller: (method whereI get 403)
@RestController
@RequestMapping("person")
public class PersonController {
@Autowired
PersonService personService;
@GetMapping("/getAll")
public ResponseEntity<List> getAll() throws IOException {
return ResponseEntity.ok(PersonService.findAll());
}

This is first time I use spring security, I followed a tutorial online but I realy can't figure out why evetime I put my request in security it still get 403 Forbidden

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

榕城若虚 2025-02-18 09:05:27

I think you might need to add @Configuration and @EnableWebSecurity annotations to your SecurityConfig class, because spring-security can't see your security configuration without them.

See reference documentation: https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/config/annotation/web/configuration/EnableWebSecurity.html

Mind also, that WebSecurityConfigurerAdapter was deprecated since 5.7.0-M2, so you might consider creating a bean of type SecurityFilterChain to configure security in your app if you use later versions of spring-security.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文