首页 > 解决方案 > 在我的 Spring Boot 项目中保护 REST API 的 spring 安全实现

问题描述

我有一个 RestController,它有一个用于对用户进行身份验证的 API。我希望任何人都可以访问这个 API,无论他们是否经过身份验证,也不管他们的角色如何。换句话说,当有人输入他们的用户名和密码并按下提交按钮时,应该调用这个 API。

这里是security config java文件的config(HttpSecurity http)方法

    @Override
protected void configure(HttpSecurity http) throws Exception {
    http/* .csrf().disable() */
            .authorizeRequests()
            .antMatchers("/admin/**").hasRole("ADMIN")
            .antMatchers("/customer/**").hasRole("CUSTOMER")
            .antMatchers("/supplier/**").hasRole("SUPPLIER")
            .antMatchers("/user/authenticate").permitAll()
            .antMatchers("/user/**").authenticated()
            .and()
            .formLogin().permitAll()
            .and()
            .logout()
            .permitAll();
      }

在上面的代码中,我写了 ''antMatchers("/user/authenticate").permitAll()'' 因为我希望每个人都可以访问这个 url,并且应该执行控制器中写入的任何逻辑。

这是我的控制器

    @RestController
    @RequestMapping("/user")
    public class AuthenticationController {
    @Autowired
    private AuthenticationManager authenticationManager;

    @PostMapping("/authenticate")
    public void authenticate(@RequestBody AuthenticationRequest request) {
    Authentication token = authenticationManager.authenticate(new 
    UsernamePasswordAuthenticationToken(request.getUsername(), request.getPassword()));
    // more code
   }
}

但我不知道为什么它不起作用。当我从 POSTMAN 发送 POST 请求时,我收到以下响应:

    {
       "timestamp": "2020-07-24T08:50:02.514+00:00",
       "status": 403,
       "error": "Forbidden",
       "message": "Forbidden",
       "path": "/user/authenticate"
    }

有人请建议我应该怎么做才能让它到达我的 REST 控制器

标签: springspring-bootspring-securitycsrfspring-security-rest

解决方案


推荐阅读