Code Lღver
Code Lღver

Reputation: 185

the server responded with a status of 403 (Forbidden) angular

When I try to call with this.http.get and @GetMapping I am able to send the call to spring controller,

When I try to change from this.http.get to this.http.post and from @GetMapping to @PostMapping I am not able to call the spring controller /api/v1/basicauth method.

As I am having username and password I want to use PostMapping only

My code as below:-

Angular

var formData: any = new FormData();
formData.append("userName", username);
formData.append("password", password);

let params = new HttpParams();
params = params.append('username', username);
params = params.append('password', password);
return this.http.post<any>('/api/v1/basicauth', { formData }).pipe(map((res) => {
    this.username = username;
    this.password = password;
}));

Spring boot:-

@PostMapping(path = "/basicauth")
public AuthenticationBean helloWorldBean(@RequestBody UserDetails user) {
log.info("Start helloWorldBean method");

UserDetails.java

    public class UserDetails {

        private int userId;
        private String userName;
        private String password;
   }

Upvotes: 2

Views: 16314

Answers (2)

Yogesh Prajapati
Yogesh Prajapati

Reputation: 4870

Do not use FormData (Angular) as your controller is accepting @RequestBody

your formData should be something like

var formData = {"username": username, "password": password};

Rest will deserilize automatically it to UserDetails class

Upvotes: 1

Penguin74
Penguin74

Reputation: 488

Client side

login(username: string, password: string) {
        return this.http.post<any>('/api/v1/basicauth', { username, password })
            .pipe(map(user => {
                // eg.
                // localStorage.setItem('currentUser', JSON.stringify(user));
                return user;
            }));

Example from: https://jasonwatmore.com/post/2019/06/22/angular-8-jwt-authentication-example-tutorial

Server side

You are retrieving paramaters with @RequestParam, which means you're expeting parametes as http://host:8080/api/auth?password=abc&....

Please check https://www.baeldung.com/spring-request-response-body

Upvotes: 1

Related Questions