Spring RequestMapping DELETE和未授权访问JWT

Posted

技术标签:

【中文标题】Spring RequestMapping DELETE和未授权访问JWT【英文标题】:Spring RequestMapping DELETE and unauthorized access JWT 【发布时间】:2020-04-06 08:24:38 【问题描述】:

春天的 DELETE 方法有问题。我正在使用 JWT 并将其发送到请求标头中,但 GET/POST/PATCH 有效,DELETE 无效..我真的不知道为什么。即使通过邮递员,我也无权 401 删除项目,但我可以获取/修补/发布新项目...这是我的控制器代码:

@CrossOrigin(origins = "http://localhost:8081", maxAge = 3600)
@RestController
public class JwtAuthenticationController 

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private JwtUserDetailsService userDetailsService;

    @Autowired
    private CarDetailsService carDetailsService;


    @RequestMapping(value = "/authenticate", method = RequestMethod.POST)
    public ResponseEntity<?> createAuthenticationToken(@RequestBody JwtRequest authenticationRequest) throws Exception 

        authenticate(authenticationRequest.getUsername(), authenticationRequest.getPassword());

        final UserDetails userDetails = userDetailsService.loadUserByUsername(authenticationRequest.getUsername());

        final String token = jwtTokenUtil.generateToken(userDetails);

        return ResponseEntity.ok(new JwtResponse(token));
    

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public ResponseEntity<?> saveUser(@RequestBody UserDTO user) throws Exception 
        return ResponseEntity.ok(userDetailsService.save(user));
    

    private void authenticate(String username, String password) throws Exception 
        try 
            authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
         catch (DisabledException e) 
            throw new Exception("USER_DISABLED", e);
         catch (BadCredentialsException e) 
            throw new Exception("INVALID_CREDENTIALS", e);
        
    

    @RequestMapping(value = "/car", method = RequestMethod.POST)
    public ResponseEntity<?> getRents(@RequestBody CarDTO car) throws Exception 
        return ResponseEntity.ok(carDetailsService.saveCar(car));
    



    @RequestMapping(value ="/cars", method = RequestMethod.GET)
    public ResponseEntity<?> getCars() throws Exception
        return ResponseEntity.ok(carDetailsService.getAllCars());
    


    @PatchMapping("/cars/id")
    public ResponseEntity<?>  partialUpdate(@RequestBody PartialCarDTO partialCar, @PathVariable("id") Integer id)
        return ResponseEntity.ok(carDetailsService.updateCar(partialCar,id));
    

    @RequestMapping(value = "/cars/id", method = RequestMethod.DELETE)
    public ResponseEntity<?> deleteCar(@RequestBody PartialCarDTO partialCar, @PathVariable("id") Integer id)
        return ResponseEntity.ok(carDetailsService.deleteCar(partialCar,id));
    

【问题讨论】:

您的网络安全配置是什么?也许this 文章可以提供帮助?更多可能solutions 【参考方案1】:

我从 requestmapping 中删除了 PartialCarDTO,并且通过邮递员可以删除实体,但在我的休息 api 中它不是 .. :/ 我尝试了很多变体但没有成功。即使我在 axios 中传递 NULL 而不是有效负载,同时使用我的令牌保留诸如授权之类的标头,内容类型和访问控制允许来源。不,我真的不知道问题出在哪里。总是 401。你有什么想法吗?

  return new Promise((resolve, reject) => 
                    let id=payload.id;
                    let url="http://localhost:8080/cars/"+id
                    let config = 
                        headers: 
                            "Authorization": "Bearer "+localStorage.getItem('token'),
                            "Content-Type": "application/json",
                            "Access-Control-Allow-Origin": "*"
                          
                          

                    axios.delete(url, payload, config)
                    .then((data,status) => 
                        if(status === 200)
                            resolve(true);
                        
                    )
                    .catch(error=> 
                        reject(error);
                    )
                

【讨论】:

【参考方案2】:

这里有一个很好的答案:https://***.com/a/299696/4573580

如果 DELETE 请求包含实体主体,则该主体将被忽略 [...]

【讨论】:

我的请求正文为空,我正在使用 axios.delete(url,null,config)

以上是关于Spring RequestMapping DELETE和未授权访问JWT的主要内容,如果未能解决你的问题,请参考以下文章

Spring 3 RequestMapping:获取路径值

Spring MVC — @RequestMapping原理讲解-1

spring @RequestMapping注解技巧

Spring MVC 基础注解之@RequestMapping@Controller

Spring MVC - 02 RequestMapping映射请求

Spring @RequestMapping 注解使用技巧