Issue
"Access to XMLHttpRequest at 'http://localhost:8080/authenticate/login' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status."
Spring Boot backend, Angular front. Tried sending an Http post, in the form of a login object containing a username and password. It's supposed to receive a jwt token in return. Works perfectly in postman, so it leads me to believe google chrome is the issue. I'm using the Allow CORS Chrome extention as well.
Weirdly enough the http GET requests work.
I tried making a proxy in angular which didn't fix the issue. I also might have done it wrong too, I'm new to making web applications so all the vague instructions on some websites really frustrate me.
auth.service.ts Which sends the request
import { Injectable, ɵCompiler_compileModuleAndAllComponentsSync__POST_R3__ } from "@angular/core";
import { BehaviorSubject, Observable } from "rxjs";
import { map } from "rxjs/operators";
import { environment } from "src/environments/environment";
@Injectable({ providedIn: 'root' })
export class AuthService {
isAuthenticatedSubject = new BehaviorSubject<boolean>(false);
constructor(private httpClient: HttpClient) { }
login(username: string, password: string): Observable<any> {
const data = {
username: username,
password: password
};
let headers = new HttpHeaders();
headers.set('Contact-Type', 'application/json');
const url = `${environment.AUTH_ROUTE}`;
return this.httpClient.post<any>(url, data, { headers: headers })
.pipe(
map(response => {
localStorage.setItem('token', response.token);
this.isAuthenticatedSubject.next(true);
return response;
})
);
// { token: "vrijednost-tokena" }
}
logout() {
localStorage.removeItem('token');
this.isAuthenticatedSubject.next(null);
}
}
AuthController.java Which receives the request
import com.example.stevan.madsapp.security.jwt.JwtTokenProvider;
import com.example.stevan.madsapp.web.dto.LoginDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.awt.*;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping(value = "/authenticate", produces = MediaType.APPLICATION_JSON_VALUE)
public class AuthController {
@Autowired
private JwtTokenProvider jwtTokenProvider;
@Autowired
private AuthenticationManager authenticationManager;
@PostMapping(value = "/login")
public ResponseEntity<Object> login(@RequestBody LoginDTO loginDTO)
{
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
loginDTO.getUsername(), loginDTO.getPassword()
);
try
{
Authentication authentication = authenticationManager.authenticate(authenticationToken);
SecurityContextHolder.getContext().setAuthentication(authentication);
String token = jwtTokenProvider.createToken(authentication);
Map<String, String> responsePayload = new HashMap<>();
responsePayload.put("token", token);
return new ResponseEntity<>(responsePayload, HttpStatus.OK);
}catch (Exception e)
{
return new ResponseEntity<>("Error while login", HttpStatus.UNAUTHORIZED);
}
}
}
I'm sorry in advance for my lack of basic knowledge on the subject.
Solution
adding @CrossOrigin(origins = "http://localhost:4200")
to the controller method should solve your issue. Take a look at Enabling Cross Origin Requests for a RESTful Web Service
Answered By - vincendep
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.