I created an simple application with spring boot and react. I got jwt token from backend when I log. I need to access data using that token after passing header automatically. (As bellow postmon ss)
This is my react code
useEffect(()=>{
const config ={
headers:{
Authorization: 'Bearer '+ localStorage.getItem('token')
}
}
axios.get('http://localhost:8090/dashboard',config).then(res=>{
console.log(res);
})
})
This is my spring controller class
@RestController
@CrossOrigin(origins = "http://localhost:3000")
public class AuthController {
@Autowired
private UserRepository userRepository;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private UserService userService;
@Autowired
private JwtUtils jwtUtils;
@GetMapping("/dashboard")
public String testingToken(){
return "Welcome to dashboard.";
}
@PostMapping("/register")
private ResponseEntity<?> subscribeClient(@RequestBody AuthenticationRequest authenticationRequest){
String userName = authenticationRequest.getUserName();
String password = authenticationRequest.getPassword();
String userType = authenticationRequest.getUserType();
Users userModel = new Users();
userModel.setUserName(userName);
userModel.setPassword(password);
userModel.setUserType(userType);
try{
userRepository.save(userModel);
}catch (Exception e){
return ResponseEntity.ok(new AuthenticationResponse("Error while subscription."+ userName));
}
return ResponseEntity.ok(new AuthenticationResponse("Successfully authenticated."+ userName));
}
@PostMapping("/login")
private ResponseEntity<?> authenticateClient(@RequestBody AuthenticationRequest authenticationRequest){
String userName = authenticationRequest.getUserName();
String password = authenticationRequest.getPassword();
try {
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(userName,password));
}catch (Exception e){
return ResponseEntity.ok(new AuthenticationResponse("Error during client authentication."+ userName));
}
UserDetails userDetails = userService.loadUserByUsername(userName);
String generatedToken = jwtUtils.generateToken(userDetails);
return ResponseEntity.ok(new AuthenticationResponse(generatedToken));
}
}
When I run this, the console result is
Access to XMLHttpRequest at 'http://localhost:8090/dashboard' from origin
'http://localhost:3000' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
How to fix this?