Cannot access a URL on my backend due to Access / CORS issue in Spring 5 [duplicate]










1
















This question already has an answer here:



  • CORS issue - No 'Access-Control-Allow-Origin' header is present on the requested resource

    3 answers



I added in Security into my Spring app and suddenly I am getting CORS issues. I have tried many different CORS settings in Spring (see some of the commented out code). Nothing is working.



I am passing basic auth in my front end Angular app as so:



const httpOptions = 
headers: new HttpHeaders(
'Content-Type': 'application/json',
'Authorization': 'Basic mybase64basicauth'
)
;

...
this.campaignsSubscription = this.http.get<Campaign>(this.campaignsUrl, httpOptions)


And I have my app configured for CrossOrigin both locally and globally.



Global:



@Configuration
@EnableWebFlux
public class WebConfig implements WebFluxConfigurer

@Override
public void addCorsMappings(CorsRegistry registry)

registry.addMapping("/**")
.allowedOrigins("http://localhost:4200")
.allowedMethods("PUT", "DELETE", "GET", "OPTIONS", "POST", "PATCH")
.allowedHeaders("Authorization", "Content-Type")
// .allowedHeaders("Content-Type")
.allowCredentials(true).maxAge(3600);

// Add more mappings...




And locally:



/*@CrossOrigin(origins = "http://localhost:4200",
allowedHeaders = "*",
methods = RequestMethod.DELETE, RequestMethod.GET, RequestMethod.HEAD, RequestMethod.OPTIONS, RequestMethod.PATCH, RequestMethod.PUT,
allowCredentials = "true"
)*/
@CrossOrigin
@RestController
@RequestMapping("/api/campaign")
public class CampaignResource {

private CampaignRepository campaignRepository;

public CampaignResource(CampaignRepository campaignRepository)
this.campaignRepository = campaignRepository;



@GetMapping("/all")
public Flux<Campaign> getAll() {
return campaignRepository
.findAll();

...


But I get these errors in the Chrome console:



 zone.js:2969 OPTIONS http://localhost:8081/api/campaign/all 401 (Unauthorized)

'http://localhost:8081/api/campaign/all' from origin
'http://localhost:4200' 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.


I know the basic auth is correct as it works in Postman.










share|improve this question















marked as duplicate by dur, sideshowbarker, eyllanesc, Pearly Spencer, Paul Roub Nov 14 '18 at 20:12


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.


















  • @DavidGoate Yes: The port 4200 is what an Angular app runs on in development mode when you run ng serve. Also, its obviously served up via localhost. Both my Spring server and my front end are running on my local machine for dev purposes. I have spring running at localhost:8081

    – Peter S
    Nov 13 '18 at 20:41











  • Request headers: Accept: / Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.9 Access-Control-Request-Headers: authorization,content-type Access-Control-Request-Method: GET Connection: keep-alive DNT: 1 Host: localhost:8081 Origin: localhost:4200 User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36

    – Peter S
    Nov 13 '18 at 20:43












  • I don't see an immediate issue. It's very similar to the config I use in a spring boot 1 project (not web flux). To be sure, if you remove the local @CrossOrigin applied to the endpoint and rely just on the global config does the behaviour change at all?

    – David Goate
    Nov 13 '18 at 20:49











  • In case it helps, this is the configuration i used in spring boot 1 with spring mvc: pastebin.com/ignRZ0p0 The main difference being that I enable CORS via the security configuration adapter and define a bean of type UrlBasedCorsConfigurationSource with name corsConfigurationSource. I am not sure what has to be done in webflux to get a similar setup though. This looks promising; baeldung.com/spring-webflux-cors I mainly wonder whether you mixture of local and global approach is somehow conflicting, maybe try removing the local annoation

    – David Goate
    Nov 13 '18 at 20:52












  • If it were me, I'd first try without any cross origin annotation on the resource (just the global config) . If that fails, I'd try removing the global config and on the annotation explicitly set the appropriate attributes on the annotation. e.g. @CrossOrigin(methods=, origins=, allowCredentials=true) etc...

    – David Goate
    Nov 13 '18 at 21:20















1
















This question already has an answer here:



  • CORS issue - No 'Access-Control-Allow-Origin' header is present on the requested resource

    3 answers



I added in Security into my Spring app and suddenly I am getting CORS issues. I have tried many different CORS settings in Spring (see some of the commented out code). Nothing is working.



I am passing basic auth in my front end Angular app as so:



const httpOptions = 
headers: new HttpHeaders(
'Content-Type': 'application/json',
'Authorization': 'Basic mybase64basicauth'
)
;

...
this.campaignsSubscription = this.http.get<Campaign>(this.campaignsUrl, httpOptions)


And I have my app configured for CrossOrigin both locally and globally.



Global:



@Configuration
@EnableWebFlux
public class WebConfig implements WebFluxConfigurer

@Override
public void addCorsMappings(CorsRegistry registry)

registry.addMapping("/**")
.allowedOrigins("http://localhost:4200")
.allowedMethods("PUT", "DELETE", "GET", "OPTIONS", "POST", "PATCH")
.allowedHeaders("Authorization", "Content-Type")
// .allowedHeaders("Content-Type")
.allowCredentials(true).maxAge(3600);

// Add more mappings...




And locally:



/*@CrossOrigin(origins = "http://localhost:4200",
allowedHeaders = "*",
methods = RequestMethod.DELETE, RequestMethod.GET, RequestMethod.HEAD, RequestMethod.OPTIONS, RequestMethod.PATCH, RequestMethod.PUT,
allowCredentials = "true"
)*/
@CrossOrigin
@RestController
@RequestMapping("/api/campaign")
public class CampaignResource {

private CampaignRepository campaignRepository;

public CampaignResource(CampaignRepository campaignRepository)
this.campaignRepository = campaignRepository;



@GetMapping("/all")
public Flux<Campaign> getAll() {
return campaignRepository
.findAll();

...


But I get these errors in the Chrome console:



 zone.js:2969 OPTIONS http://localhost:8081/api/campaign/all 401 (Unauthorized)

'http://localhost:8081/api/campaign/all' from origin
'http://localhost:4200' 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.


I know the basic auth is correct as it works in Postman.










share|improve this question















marked as duplicate by dur, sideshowbarker, eyllanesc, Pearly Spencer, Paul Roub Nov 14 '18 at 20:12


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.


















  • @DavidGoate Yes: The port 4200 is what an Angular app runs on in development mode when you run ng serve. Also, its obviously served up via localhost. Both my Spring server and my front end are running on my local machine for dev purposes. I have spring running at localhost:8081

    – Peter S
    Nov 13 '18 at 20:41











  • Request headers: Accept: / Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.9 Access-Control-Request-Headers: authorization,content-type Access-Control-Request-Method: GET Connection: keep-alive DNT: 1 Host: localhost:8081 Origin: localhost:4200 User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36

    – Peter S
    Nov 13 '18 at 20:43












  • I don't see an immediate issue. It's very similar to the config I use in a spring boot 1 project (not web flux). To be sure, if you remove the local @CrossOrigin applied to the endpoint and rely just on the global config does the behaviour change at all?

    – David Goate
    Nov 13 '18 at 20:49











  • In case it helps, this is the configuration i used in spring boot 1 with spring mvc: pastebin.com/ignRZ0p0 The main difference being that I enable CORS via the security configuration adapter and define a bean of type UrlBasedCorsConfigurationSource with name corsConfigurationSource. I am not sure what has to be done in webflux to get a similar setup though. This looks promising; baeldung.com/spring-webflux-cors I mainly wonder whether you mixture of local and global approach is somehow conflicting, maybe try removing the local annoation

    – David Goate
    Nov 13 '18 at 20:52












  • If it were me, I'd first try without any cross origin annotation on the resource (just the global config) . If that fails, I'd try removing the global config and on the annotation explicitly set the appropriate attributes on the annotation. e.g. @CrossOrigin(methods=, origins=, allowCredentials=true) etc...

    – David Goate
    Nov 13 '18 at 21:20













1












1








1


1







This question already has an answer here:



  • CORS issue - No 'Access-Control-Allow-Origin' header is present on the requested resource

    3 answers



I added in Security into my Spring app and suddenly I am getting CORS issues. I have tried many different CORS settings in Spring (see some of the commented out code). Nothing is working.



I am passing basic auth in my front end Angular app as so:



const httpOptions = 
headers: new HttpHeaders(
'Content-Type': 'application/json',
'Authorization': 'Basic mybase64basicauth'
)
;

...
this.campaignsSubscription = this.http.get<Campaign>(this.campaignsUrl, httpOptions)


And I have my app configured for CrossOrigin both locally and globally.



Global:



@Configuration
@EnableWebFlux
public class WebConfig implements WebFluxConfigurer

@Override
public void addCorsMappings(CorsRegistry registry)

registry.addMapping("/**")
.allowedOrigins("http://localhost:4200")
.allowedMethods("PUT", "DELETE", "GET", "OPTIONS", "POST", "PATCH")
.allowedHeaders("Authorization", "Content-Type")
// .allowedHeaders("Content-Type")
.allowCredentials(true).maxAge(3600);

// Add more mappings...




And locally:



/*@CrossOrigin(origins = "http://localhost:4200",
allowedHeaders = "*",
methods = RequestMethod.DELETE, RequestMethod.GET, RequestMethod.HEAD, RequestMethod.OPTIONS, RequestMethod.PATCH, RequestMethod.PUT,
allowCredentials = "true"
)*/
@CrossOrigin
@RestController
@RequestMapping("/api/campaign")
public class CampaignResource {

private CampaignRepository campaignRepository;

public CampaignResource(CampaignRepository campaignRepository)
this.campaignRepository = campaignRepository;



@GetMapping("/all")
public Flux<Campaign> getAll() {
return campaignRepository
.findAll();

...


But I get these errors in the Chrome console:



 zone.js:2969 OPTIONS http://localhost:8081/api/campaign/all 401 (Unauthorized)

'http://localhost:8081/api/campaign/all' from origin
'http://localhost:4200' 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.


I know the basic auth is correct as it works in Postman.










share|improve this question

















This question already has an answer here:



  • CORS issue - No 'Access-Control-Allow-Origin' header is present on the requested resource

    3 answers



I added in Security into my Spring app and suddenly I am getting CORS issues. I have tried many different CORS settings in Spring (see some of the commented out code). Nothing is working.



I am passing basic auth in my front end Angular app as so:



const httpOptions = 
headers: new HttpHeaders(
'Content-Type': 'application/json',
'Authorization': 'Basic mybase64basicauth'
)
;

...
this.campaignsSubscription = this.http.get<Campaign>(this.campaignsUrl, httpOptions)


And I have my app configured for CrossOrigin both locally and globally.



Global:



@Configuration
@EnableWebFlux
public class WebConfig implements WebFluxConfigurer

@Override
public void addCorsMappings(CorsRegistry registry)

registry.addMapping("/**")
.allowedOrigins("http://localhost:4200")
.allowedMethods("PUT", "DELETE", "GET", "OPTIONS", "POST", "PATCH")
.allowedHeaders("Authorization", "Content-Type")
// .allowedHeaders("Content-Type")
.allowCredentials(true).maxAge(3600);

// Add more mappings...




And locally:



/*@CrossOrigin(origins = "http://localhost:4200",
allowedHeaders = "*",
methods = RequestMethod.DELETE, RequestMethod.GET, RequestMethod.HEAD, RequestMethod.OPTIONS, RequestMethod.PATCH, RequestMethod.PUT,
allowCredentials = "true"
)*/
@CrossOrigin
@RestController
@RequestMapping("/api/campaign")
public class CampaignResource {

private CampaignRepository campaignRepository;

public CampaignResource(CampaignRepository campaignRepository)
this.campaignRepository = campaignRepository;



@GetMapping("/all")
public Flux<Campaign> getAll() {
return campaignRepository
.findAll();

...


But I get these errors in the Chrome console:



 zone.js:2969 OPTIONS http://localhost:8081/api/campaign/all 401 (Unauthorized)

'http://localhost:8081/api/campaign/all' from origin
'http://localhost:4200' 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.


I know the basic auth is correct as it works in Postman.





This question already has an answer here:



  • CORS issue - No 'Access-Control-Allow-Origin' header is present on the requested resource

    3 answers







spring spring-boot spring-security






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 14 '18 at 0:04







Peter S

















asked Nov 13 '18 at 20:30









Peter SPeter S

6611




6611




marked as duplicate by dur, sideshowbarker, eyllanesc, Pearly Spencer, Paul Roub Nov 14 '18 at 20:12


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.









marked as duplicate by dur, sideshowbarker, eyllanesc, Pearly Spencer, Paul Roub Nov 14 '18 at 20:12


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.














  • @DavidGoate Yes: The port 4200 is what an Angular app runs on in development mode when you run ng serve. Also, its obviously served up via localhost. Both my Spring server and my front end are running on my local machine for dev purposes. I have spring running at localhost:8081

    – Peter S
    Nov 13 '18 at 20:41











  • Request headers: Accept: / Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.9 Access-Control-Request-Headers: authorization,content-type Access-Control-Request-Method: GET Connection: keep-alive DNT: 1 Host: localhost:8081 Origin: localhost:4200 User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36

    – Peter S
    Nov 13 '18 at 20:43












  • I don't see an immediate issue. It's very similar to the config I use in a spring boot 1 project (not web flux). To be sure, if you remove the local @CrossOrigin applied to the endpoint and rely just on the global config does the behaviour change at all?

    – David Goate
    Nov 13 '18 at 20:49











  • In case it helps, this is the configuration i used in spring boot 1 with spring mvc: pastebin.com/ignRZ0p0 The main difference being that I enable CORS via the security configuration adapter and define a bean of type UrlBasedCorsConfigurationSource with name corsConfigurationSource. I am not sure what has to be done in webflux to get a similar setup though. This looks promising; baeldung.com/spring-webflux-cors I mainly wonder whether you mixture of local and global approach is somehow conflicting, maybe try removing the local annoation

    – David Goate
    Nov 13 '18 at 20:52












  • If it were me, I'd first try without any cross origin annotation on the resource (just the global config) . If that fails, I'd try removing the global config and on the annotation explicitly set the appropriate attributes on the annotation. e.g. @CrossOrigin(methods=, origins=, allowCredentials=true) etc...

    – David Goate
    Nov 13 '18 at 21:20

















  • @DavidGoate Yes: The port 4200 is what an Angular app runs on in development mode when you run ng serve. Also, its obviously served up via localhost. Both my Spring server and my front end are running on my local machine for dev purposes. I have spring running at localhost:8081

    – Peter S
    Nov 13 '18 at 20:41











  • Request headers: Accept: / Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.9 Access-Control-Request-Headers: authorization,content-type Access-Control-Request-Method: GET Connection: keep-alive DNT: 1 Host: localhost:8081 Origin: localhost:4200 User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36

    – Peter S
    Nov 13 '18 at 20:43












  • I don't see an immediate issue. It's very similar to the config I use in a spring boot 1 project (not web flux). To be sure, if you remove the local @CrossOrigin applied to the endpoint and rely just on the global config does the behaviour change at all?

    – David Goate
    Nov 13 '18 at 20:49











  • In case it helps, this is the configuration i used in spring boot 1 with spring mvc: pastebin.com/ignRZ0p0 The main difference being that I enable CORS via the security configuration adapter and define a bean of type UrlBasedCorsConfigurationSource with name corsConfigurationSource. I am not sure what has to be done in webflux to get a similar setup though. This looks promising; baeldung.com/spring-webflux-cors I mainly wonder whether you mixture of local and global approach is somehow conflicting, maybe try removing the local annoation

    – David Goate
    Nov 13 '18 at 20:52












  • If it were me, I'd first try without any cross origin annotation on the resource (just the global config) . If that fails, I'd try removing the global config and on the annotation explicitly set the appropriate attributes on the annotation. e.g. @CrossOrigin(methods=, origins=, allowCredentials=true) etc...

    – David Goate
    Nov 13 '18 at 21:20
















@DavidGoate Yes: The port 4200 is what an Angular app runs on in development mode when you run ng serve. Also, its obviously served up via localhost. Both my Spring server and my front end are running on my local machine for dev purposes. I have spring running at localhost:8081

– Peter S
Nov 13 '18 at 20:41





@DavidGoate Yes: The port 4200 is what an Angular app runs on in development mode when you run ng serve. Also, its obviously served up via localhost. Both my Spring server and my front end are running on my local machine for dev purposes. I have spring running at localhost:8081

– Peter S
Nov 13 '18 at 20:41













Request headers: Accept: / Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.9 Access-Control-Request-Headers: authorization,content-type Access-Control-Request-Method: GET Connection: keep-alive DNT: 1 Host: localhost:8081 Origin: localhost:4200 User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36

– Peter S
Nov 13 '18 at 20:43






Request headers: Accept: / Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.9 Access-Control-Request-Headers: authorization,content-type Access-Control-Request-Method: GET Connection: keep-alive DNT: 1 Host: localhost:8081 Origin: localhost:4200 User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36

– Peter S
Nov 13 '18 at 20:43














I don't see an immediate issue. It's very similar to the config I use in a spring boot 1 project (not web flux). To be sure, if you remove the local @CrossOrigin applied to the endpoint and rely just on the global config does the behaviour change at all?

– David Goate
Nov 13 '18 at 20:49





I don't see an immediate issue. It's very similar to the config I use in a spring boot 1 project (not web flux). To be sure, if you remove the local @CrossOrigin applied to the endpoint and rely just on the global config does the behaviour change at all?

– David Goate
Nov 13 '18 at 20:49













In case it helps, this is the configuration i used in spring boot 1 with spring mvc: pastebin.com/ignRZ0p0 The main difference being that I enable CORS via the security configuration adapter and define a bean of type UrlBasedCorsConfigurationSource with name corsConfigurationSource. I am not sure what has to be done in webflux to get a similar setup though. This looks promising; baeldung.com/spring-webflux-cors I mainly wonder whether you mixture of local and global approach is somehow conflicting, maybe try removing the local annoation

– David Goate
Nov 13 '18 at 20:52






In case it helps, this is the configuration i used in spring boot 1 with spring mvc: pastebin.com/ignRZ0p0 The main difference being that I enable CORS via the security configuration adapter and define a bean of type UrlBasedCorsConfigurationSource with name corsConfigurationSource. I am not sure what has to be done in webflux to get a similar setup though. This looks promising; baeldung.com/spring-webflux-cors I mainly wonder whether you mixture of local and global approach is somehow conflicting, maybe try removing the local annoation

– David Goate
Nov 13 '18 at 20:52














If it were me, I'd first try without any cross origin annotation on the resource (just the global config) . If that fails, I'd try removing the global config and on the annotation explicitly set the appropriate attributes on the annotation. e.g. @CrossOrigin(methods=, origins=, allowCredentials=true) etc...

– David Goate
Nov 13 '18 at 21:20





If it were me, I'd first try without any cross origin annotation on the resource (just the global config) . If that fails, I'd try removing the global config and on the annotation explicitly set the appropriate attributes on the annotation. e.g. @CrossOrigin(methods=, origins=, allowCredentials=true) etc...

– David Goate
Nov 13 '18 at 21:20












1 Answer
1






active

oldest

votes


















1














When using Spring Security 5.x...



The answer is two fold:



1) In your SecurityWebFilterChain you must add:



.pathMatchers(HttpMethod.OPTIONS, "/**").permitAll()**strong text**


2) In your Resource you must add the following CORS statement:



@CrossOrigin(origins = "http://localhost:4200",
allowedHeaders = "*",
methods = RequestMethod.DELETE, RequestMethod.GET, RequestMethod.HEAD, RequestMethod.OPTIONS, RequestMethod.PATCH, RequestMethod.PUT,
allowCredentials = "true"
)


Here is my complete SecurityConfig class:



@Configuration
@EnableWebFluxSecurity
@EnableReactiveMethodSecurity
public class SecurityConfig

@Bean
SecurityWebFilterChain springWebFilterChain(ServerHttpSecurity http)
return http
.authorizeExchange()
.pathMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.pathMatchers("/login", "/logout").permitAll()
.pathMatchers("/i18n/**",
"/css/**",
"/fonts/**",
"/icons-reference/**",
"/img/**",
"/js/**",
"/vendor/**").permitAll()
.pathMatchers(HttpMethod.GET,"/api/**").authenticated()
.anyExchange()
.authenticated()
.and()
.formLogin()
.and()
.httpBasic()
/*.loginPage("/login")
.and()
.logout()
.logoutUrl("/logout")*/
.and()
.csrf().disable()
.build();



//in case you want to encrypt password
@Bean
public BCryptPasswordEncoder passwordEncoder()
return new BCryptPasswordEncoder();







share|improve this answer





























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    When using Spring Security 5.x...



    The answer is two fold:



    1) In your SecurityWebFilterChain you must add:



    .pathMatchers(HttpMethod.OPTIONS, "/**").permitAll()**strong text**


    2) In your Resource you must add the following CORS statement:



    @CrossOrigin(origins = "http://localhost:4200",
    allowedHeaders = "*",
    methods = RequestMethod.DELETE, RequestMethod.GET, RequestMethod.HEAD, RequestMethod.OPTIONS, RequestMethod.PATCH, RequestMethod.PUT,
    allowCredentials = "true"
    )


    Here is my complete SecurityConfig class:



    @Configuration
    @EnableWebFluxSecurity
    @EnableReactiveMethodSecurity
    public class SecurityConfig

    @Bean
    SecurityWebFilterChain springWebFilterChain(ServerHttpSecurity http)
    return http
    .authorizeExchange()
    .pathMatchers(HttpMethod.OPTIONS, "/**").permitAll()
    .pathMatchers("/login", "/logout").permitAll()
    .pathMatchers("/i18n/**",
    "/css/**",
    "/fonts/**",
    "/icons-reference/**",
    "/img/**",
    "/js/**",
    "/vendor/**").permitAll()
    .pathMatchers(HttpMethod.GET,"/api/**").authenticated()
    .anyExchange()
    .authenticated()
    .and()
    .formLogin()
    .and()
    .httpBasic()
    /*.loginPage("/login")
    .and()
    .logout()
    .logoutUrl("/logout")*/
    .and()
    .csrf().disable()
    .build();



    //in case you want to encrypt password
    @Bean
    public BCryptPasswordEncoder passwordEncoder()
    return new BCryptPasswordEncoder();







    share|improve this answer



























      1














      When using Spring Security 5.x...



      The answer is two fold:



      1) In your SecurityWebFilterChain you must add:



      .pathMatchers(HttpMethod.OPTIONS, "/**").permitAll()**strong text**


      2) In your Resource you must add the following CORS statement:



      @CrossOrigin(origins = "http://localhost:4200",
      allowedHeaders = "*",
      methods = RequestMethod.DELETE, RequestMethod.GET, RequestMethod.HEAD, RequestMethod.OPTIONS, RequestMethod.PATCH, RequestMethod.PUT,
      allowCredentials = "true"
      )


      Here is my complete SecurityConfig class:



      @Configuration
      @EnableWebFluxSecurity
      @EnableReactiveMethodSecurity
      public class SecurityConfig

      @Bean
      SecurityWebFilterChain springWebFilterChain(ServerHttpSecurity http)
      return http
      .authorizeExchange()
      .pathMatchers(HttpMethod.OPTIONS, "/**").permitAll()
      .pathMatchers("/login", "/logout").permitAll()
      .pathMatchers("/i18n/**",
      "/css/**",
      "/fonts/**",
      "/icons-reference/**",
      "/img/**",
      "/js/**",
      "/vendor/**").permitAll()
      .pathMatchers(HttpMethod.GET,"/api/**").authenticated()
      .anyExchange()
      .authenticated()
      .and()
      .formLogin()
      .and()
      .httpBasic()
      /*.loginPage("/login")
      .and()
      .logout()
      .logoutUrl("/logout")*/
      .and()
      .csrf().disable()
      .build();



      //in case you want to encrypt password
      @Bean
      public BCryptPasswordEncoder passwordEncoder()
      return new BCryptPasswordEncoder();







      share|improve this answer

























        1












        1








        1







        When using Spring Security 5.x...



        The answer is two fold:



        1) In your SecurityWebFilterChain you must add:



        .pathMatchers(HttpMethod.OPTIONS, "/**").permitAll()**strong text**


        2) In your Resource you must add the following CORS statement:



        @CrossOrigin(origins = "http://localhost:4200",
        allowedHeaders = "*",
        methods = RequestMethod.DELETE, RequestMethod.GET, RequestMethod.HEAD, RequestMethod.OPTIONS, RequestMethod.PATCH, RequestMethod.PUT,
        allowCredentials = "true"
        )


        Here is my complete SecurityConfig class:



        @Configuration
        @EnableWebFluxSecurity
        @EnableReactiveMethodSecurity
        public class SecurityConfig

        @Bean
        SecurityWebFilterChain springWebFilterChain(ServerHttpSecurity http)
        return http
        .authorizeExchange()
        .pathMatchers(HttpMethod.OPTIONS, "/**").permitAll()
        .pathMatchers("/login", "/logout").permitAll()
        .pathMatchers("/i18n/**",
        "/css/**",
        "/fonts/**",
        "/icons-reference/**",
        "/img/**",
        "/js/**",
        "/vendor/**").permitAll()
        .pathMatchers(HttpMethod.GET,"/api/**").authenticated()
        .anyExchange()
        .authenticated()
        .and()
        .formLogin()
        .and()
        .httpBasic()
        /*.loginPage("/login")
        .and()
        .logout()
        .logoutUrl("/logout")*/
        .and()
        .csrf().disable()
        .build();



        //in case you want to encrypt password
        @Bean
        public BCryptPasswordEncoder passwordEncoder()
        return new BCryptPasswordEncoder();







        share|improve this answer













        When using Spring Security 5.x...



        The answer is two fold:



        1) In your SecurityWebFilterChain you must add:



        .pathMatchers(HttpMethod.OPTIONS, "/**").permitAll()**strong text**


        2) In your Resource you must add the following CORS statement:



        @CrossOrigin(origins = "http://localhost:4200",
        allowedHeaders = "*",
        methods = RequestMethod.DELETE, RequestMethod.GET, RequestMethod.HEAD, RequestMethod.OPTIONS, RequestMethod.PATCH, RequestMethod.PUT,
        allowCredentials = "true"
        )


        Here is my complete SecurityConfig class:



        @Configuration
        @EnableWebFluxSecurity
        @EnableReactiveMethodSecurity
        public class SecurityConfig

        @Bean
        SecurityWebFilterChain springWebFilterChain(ServerHttpSecurity http)
        return http
        .authorizeExchange()
        .pathMatchers(HttpMethod.OPTIONS, "/**").permitAll()
        .pathMatchers("/login", "/logout").permitAll()
        .pathMatchers("/i18n/**",
        "/css/**",
        "/fonts/**",
        "/icons-reference/**",
        "/img/**",
        "/js/**",
        "/vendor/**").permitAll()
        .pathMatchers(HttpMethod.GET,"/api/**").authenticated()
        .anyExchange()
        .authenticated()
        .and()
        .formLogin()
        .and()
        .httpBasic()
        /*.loginPage("/login")
        .and()
        .logout()
        .logoutUrl("/logout")*/
        .and()
        .csrf().disable()
        .build();



        //in case you want to encrypt password
        @Bean
        public BCryptPasswordEncoder passwordEncoder()
        return new BCryptPasswordEncoder();








        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 14 '18 at 0:10









        Peter SPeter S

        6611




        6611













            這個網誌中的熱門文章

            How to read a connectionString WITH PROVIDER in .NET Core?

            Node.js Script on GitHub Pages or Amazon S3

            Museum of Modern and Contemporary Art of Trento and Rovereto