spring security 403尝试添加新用户时出错

fbcarpbf  于 2021-07-06  发布在  Java
关注(0)|答案(3)|浏览(373)

我一直在尝试向我的spring boot安全应用程序添加create方法,但是,当我使用postMap时,我得到了那个错误。另外,我的id以db为单位自动递增。我不确定,但可能是因为它的错误。我不知道如何在请求体中写入自动递增的值。

{"timestamp":"2020-08- 
   23T00:43:31.062+00:00","status":403,"error":"Forbidden","message":"","path":"/createUser"}
The body that i am trying to post:
{
    "id": 3,
    "userName": "Adminn",
    "password": "pss",
    "active": true,
    "role": "ROLE_ADMIN"
}

postMap的请求正文[1]:https://i.stack.imgur.com/uqod0.png
我的家庭资源类

package io.javabrains.springsecurity.jpa;

@RestController
public class HomeResource {
@Autowired
private UserRepository userRepo;

@GetMapping("/")
public String home() {
    return ("<h1>Welcome</h1>");
}

@GetMapping("/user")
public String user() {
    return ("Welcome User");
}

@GetMapping("/admin")
public String admin() {
    return ("<h1>Welcome Admin</h1>");
}

@GetMapping("/users/{id}")  
public Optional<User> retriveUser(@PathVariable int id)  
{  
    return userRepo.findById(id);

}  

@PostMapping("/createUser")
public void createUser(@RequestBody User myuser) {

    User savedUser=userRepo.save(myuser);

}
/*@GetMapping("/createUser") // it is working
public String addUser() {
    User newuser= new User();
    newuser.setUserName("new");
    newuser.setPassword(new BCryptPasswordEncoder().encode("pass"));
    newuser.setRole("ROLE_ADMIN");
    newuser.setActive(true);
    userRepo.save(newuser);

    return  "user booked";
}*/

}

我的spring应用程序类

@SpringBootApplication
@EnableJpaRepositories(basePackageClasses = UserRepository.class)
public class SpringsecurityApplication implements CommandLineRunner{

@Autowired
 UserRepository userRepository;

public static void main(String[] args) {
    SpringApplication.run(SpringsecurityApplication.class, args);
}

@Override
public void run(String... args) throws Exception {
    // TODO Auto-generated method stub
    System.out.println("Application Running.");
    User adminUser= new User();
    adminUser.setUserName("Admin");
    adminUser.setPassword(new BCryptPasswordEncoder().encode("pass"));
    adminUser.setRole("ROLE_ADMIN");
    adminUser.setActive(true);
    userRepository.save(adminUser);
    User newUser= new User();
    newUser.setUserName("User");
    newUser.setPassword(new BCryptPasswordEncoder().encode("pass"));
    newUser.setRole("ROLE_USER");
    newUser.setActive(true);
    userRepository.save(newUser);
}

}

用户类

package io.javabrains.springsecurity.jpa.models;
    @Entity
    @Table(name="app_user")
    public class User {
    @Id
    @GeneratedValue(strategy =GenerationType.AUTO)
    private int id;
    private String userName;
    private String password;
    private boolean active;
    private String role;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public boolean isActive() {
        return active;
    }
    public void setActive(boolean active) {
        this.active = active;
    }
    public String getRole() {
        return role;
    }
    public void setRole(String role) {
        this.role = role;
    }

    }

安全配置类

package io.javabrains.springsecurity.jpa;
   @EnableWebSecurity
   public class SecurityConfiguration extends WebSecurityConfigurerAdapter{

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

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

    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()

            .antMatchers("/admin").hasAnyRole("ADMIN")
            .antMatchers("/user").hasAnyRole("ADMIN","USER")
            .antMatchers("/","/createUser").permitAll()
            .and().formLogin();
    }

    }
qhhrdooz

qhhrdooz1#

因为默认情况下启用了对状态更改http predicate (如post)的csrf保护。您可以禁用它,或者在您的网页中包括csrf令牌,然后在您的http请求中包括。

eagi6jfj

eagi6jfj2#

首先,将json请求Map到实体类是一种不好的做法。首先应该使用dto类。先这么做,看看会发生什么

mlmc2os5

mlmc2os53#

如果这样修改代码会怎样:

.antMatchers(HttpMethod.POST, "/createUser").permitAll()

相关问题