如何使用Spring Security和RESTful进行POST请求?

时间:2019-01-10 12:05:05

标签: java spring-boot spring-security restful-authentication

我正在学习Spring Rest,并且我有一个Restful控制器,可以处理GET,PUT,POST和DELETE请求。之后,我添加了具有2个角色用户和管理员的Spring Security。而且我不明白为什么我只能执行GET请求,如果我尝试执行POST,PUT或DELETE请求,则会收到403 Forbidden。

其他控制器:

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TaskController {

    @Autowired
    private TaskRepository taskRepository;

    @GetMapping("/task")
    public List<Task> getTasks() {
        return taskRepository.findAll();
    }

    @PostMapping("/task")
    public void addTask(@RequestBody Task task) {
        System.out.println("Here 111"); 
        taskRepository.save(task);
    }

    @PutMapping("/task/{id}")
    public void editTask(@PathVariable long id, @RequestBody Task task) {
        Task existingTask = taskRepository.findById(id).get();
        Assert.notNull(existingTask, "Task not found");
        existingTask.setDescription(task.getDescription());
        taskRepository.save(existingTask);
    }

    @DeleteMapping("/task/{id}")
    public void deleteTask(@PathVariable long id) {
        Task taskToDel = taskRepository.findById(id).get();
        taskRepository.delete(taskToDel);
    }
}

Spring安全配置:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class BasicConfiguration extends WebSecurityConfigurerAdapter {

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

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
            .withUser("ady")
                .password(passwordEncoder().encode("12345"))
                .roles("USER")
                .and()
            .withUser("gigel")
                .password(passwordEncoder().encode("abcde"))
                .roles("USER", "ADMIN");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
            .antMatchers("/task").hasRole("USER")
            .antMatchers("/movie").hasRole("ADMIN")
            .anyRequest()
            .authenticated()
            .and()
            .httpBasic();
    }

}

更新

该问题归因于CSRF保护。我禁用了CSRF,效果很好。

1 个答案:

答案 0 :(得分:-1)

有趣的事情,

我认为您得到403是因为您输入了错误的密码,请在此处进行检查:https://spring.io/guides/gs/securing-web/

应该是

   auth
        .inMemoryAuthentication()
        .withUser("ady")
            .password("12345")
            .roles("USER")
            .and()
        .withUser("gigel")
            .password("abcde")
            .roles("USER", "ADMIN");