dEs12ZER
dEs12ZER

Reputation: 848

Why i'm getting Unauthorized when trying to send PUT request from angular5 to spring-boot?

I'm trying to send a PUT request from angular5 to to spring API , but i'm getting an error .

This is angular intervention.service.ts :

updateIntervention(id:number){
        if(this.authService.getToken()==null) {
          this.authService.loadToken();
        }
        return this.http.put(this.host+"/updateIntervention/"+id,
       {headers:new 
       HttpHeaders({'Authorization':this.authService.getToken()})});
      }

  Intervention.component.ts 

    valider(ref: Intervention){
        this.intervService.updateIntervention(ref.id)
          .subscribe((data:any)=>{
            console.log('there is no error ! ');
          },err=>{
            console.log('there is an error ! ');
          })

        ref.valid = !ref.valid;

       }

In Spring-boot :

@RequestMapping(value="/updateIntervention/{id}",method = RequestMethod.PUT)
    public Intervention update(@PathVariable Long id){

        System.out.println("in intevention update");
        Intervention I = new Intervention();
        I = interventionRepo.getOne(id);
        I.setValid(true); // it's boolean , this is the goal from this update
        interventionRepo.save(I);

        return I  
    }

As error i get in angular :

{"timestamp":1527443447949,"status":401,"error":"Unauthorized"}

As error In spring-boot :

access.AccessDeniedException: Access is denied

PS : this works when i send in angular both id and the object Ref , in spring , i write

 public Intervention update(@PathVariable Long id , @RequestBody Intervention I){ ... }

But i don't need this as all what i want is to modify the attribut valid in the entity Intervention .

I'm using httpClient .

Any idea ?

Upvotes: 0

Views: 844

Answers (1)

Anis Tissaoui
Anis Tissaoui

Reputation: 894

The put method you are using has the following definition:

put(url: string, body: any | null, options)

You are providing the options object as a body parameter.And that's why you are getting unauthorized 401 which stands for "unauthenticated". Means that you have wrong or missing credentials.

You should change

return this.http.put(this.host+"/updateIntervention/"+id,
   {headers:new 
   HttpHeaders({'Authorization':this.authService.getToken()})});
  }

To:

return this.http.put(this.host+"/updateIntervention/"+id,
       null,
       {headers:new 
       HttpHeaders({'Authorization':this.authService.getToken()})});
      }

Upvotes: 1

Related Questions