0

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)

enter image description here

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?

desertnaut
  • 57,590
  • 26
  • 140
  • 166
racketman
  • 29
  • 9

1 Answers1

-3

If you haven't tried, please try to create a class which extends BasicAuthenticationFilter and override doFilterInternal() method, use request argument, read header using getHeader() and log. Find whether your backed getting token or not in right format.

In React code too, use the log and cross check whether localStorage.getItem('token') returns valid token (Bearer YOUR SECRET KEY)

  • Thank you for your reply. Yes it returns. I need to pass that token to header to access other contents. – racketman Jul 19 '21 at 19:44