2

I have an Angular front end that is unable to pick up a user that is authenticated using spring in my back end server. I confirmed my back end authentication worked locally but I get a CORS error from Angular when trying to call my getCurrentUser method (simply returns the current authenticated user). How can I resolve this CORS error?

I know I would have to configure CORS in spring as it acts as my back end server and my angular front end would need to talk to it to get the results from my api method.

  • Does this answer your question? [How to add CORS request in header in Angular 5](https://stackoverflow.com/questions/47345282/how-to-add-cors-request-in-header-in-angular-5) – porgo Feb 28 '20 at 13:49
  • 1
    Have you tried configuring Spring for proper CORS handling? – jonrsharpe Feb 28 '20 at 13:49
  • I believe the cors configuration should be taking place in Spring not angular. When attempting to access my backend server with Angular, that is when I receive a Cors error – student4806 Feb 28 '20 at 14:22

2 Answers2

2

For Cors handling with spring security, you should have a CorsConfigurationSource in your class that extends WebSecurityConfigurerAdapter like the following.

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        final CorsConfiguration configuration = new CorsConfiguration();
        configuration.applyPermitDefaultValues();
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

As for getting angular to recognize the authenticated user, you most likely want to have a controller in Spring that returns the status of the login. Remember to enable cors on this method as well.

  @CrossOrigin
  @RequestMapping(value = "/login", method = RequestMethod.GET)
  public String login(Model model, String error, String logout) {
    if (error != null) {
      model.addAttribute("error", "Your username and password is invalid.");
    }

    if (logout != null) {
      model.addAttribute("message", "You have been logged out successfully.");
    }

    return "login";
  }

Hope this helps.

nsnan9
  • 161
  • 6
  • 1
    The Cors configuration was what I was looking for! I did already have a controller for spring security but I like how simple the one you presented is. Thanks. – student4806 Feb 28 '20 at 14:31
1

Have you tried to add @CrossOrigin(origins = "") in your controller?.

Mark Score
  • 52
  • 2
  • 6