ashwin karki
ashwin karki

Reputation: 673

Angular7 : has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource

I tried to access the URL : http://localhost:8080/hello-world/path-variable from angular to spring boot.The project was fine before adding spring security.I have used basic authentication security in spring boot.So,I need to add the headers for authorization before sending the request.I have added the headers in angular while accessing the resource from spring boot ,but it is showing me error like :

enter image description here

It's a service class as:

   import { Injectable } from '@angular/core';
    import { HttpClient, HttpHeaders } from '@angular/common/http';

    export class HelloWorldBean{
      constructor(public message:String){

      }
    }


    @Injectable({
      providedIn: 'root'
    })
    export class WelcomeDataService {

      constructor(private httpClient:HttpClient) { }

      executeHelloWorldBeanService(){
       return this.httpClient.get<HelloWorldBean>('http://localhost:8080/hello-world-bean');
        console.log("hello world bean service executed");
      }


      executeHelloWorldBeanServiceWithPathVariable(name){
        console.log("hitting to get data")
       let basicAuthHeaderString=this.createBasicAuthenticationHeader();


       console.log(basicAuthHeaderString);

       let headers=new HttpHeaders({
      Authorization: basicAuthHeaderString
       })

//i have added headers here in the URL

        return this.httpClient.get<HelloWorldBean>(
          `http://localhost:8080/hello-world/path-variable/${name}`,
        {headers});
         console.log("hello world bean service executed");
       }

       createBasicAuthenticationHeader(){
         let username='ashwin'
         let password='karki'

         let basicAuthHeaderString='Basic '+ window.btoa(username + ':' + password);

         return basicAuthHeaderString;
       }
    }

I tried to send the username and password by adding it as let basicAuthHeaderString='Basic '+ window.btoa(username + ':' + password); but it is saying me blocked by CORS policy.

Here,in my spring boot I added:

spring.security.user.name=ashwin    
spring.security.user.password=karki 

In this security configuration class i have disabled csrf() :

package com.ashwin.rws.basic.auth;

import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SpringSecurityConfigurationBasicAuth extends WebSecurityConfigurerAdapter {


    @Override
    protected void configure(HttpSecurity http) throws Exception {


        http.csrf().disable()
            .authorizeRequests()
            .antMatchers(HttpMethod.OPTIONS,"/**").permitAll()
                .anyRequest().authenticated()
                .and()
            //.formLogin().and()
            .httpBasic();
    }

}

In the controller class:

package com.ashwin.rws.rest.controller;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.ashwin.rws.model.HelloWorldBean;

@CrossOrigin(origins="http://localhost:4200")
@RestController
public class HelloWorldController {


    @GetMapping(path="/hello-world/path-variable/{name}")  
    public HelloWorldBean helloWorldBeanPathVariable(@PathVariable("name") String name) {
        System.out.print("name is"+name);
        return new HelloWorldBean(String.format("Hello world %s", name));
    }

}

enter image description here

Message from Network tab

Request URL: http://localhost:8080/hello-world/path-variable/in28minutes
Request Method: GET
Status Code: 401 
Remote Address: [::1]:8080
Referrer Policy: no-referrer-when-downgrade
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Content-Length: 0
Date: Sat, 27 Jul 2019 08:17:09 GMT
Expires: 0
Pragma: no-cache
WWW-Authenticate: Basic realm="Realm", Basic realm="Realm"
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
Provisional headers are shown
Accept: application/json, text/plain, */*
Authorization: Basic YXNod2luOmthcmtp
Origin: http://localhost:4200
Referer: http://localhost:4200/welcome/in28minutes
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36

Upvotes: 1

Views: 14975

Answers (2)

NIRAJ
NIRAJ

Reputation: 21

Based on the code snippets you have shared, I found two issues here.

1.

executeHelloWorldBeanService() {
  console.log("hello world bean service executed");
  return this.httpClient.get<HelloWorldBean>('http://localhost:8080/hello-world-bean'},{headers : headers});
}

you need to pass the header object what have you generated basic authorization: {headers: headers} inside the get url.

2. Your request is aunthenticated by spring security. So its throwing an error. Now inside the SpringSecurityConfigurationBasicAuth.java use the

http.authorizeRequests().antMatchers(HttpMethod.OPTIONS, "/**").permitAll().and().csrf().disable();

and it will work.

Upvotes: 2

GnanaJeyam
GnanaJeyam

Reputation: 3170

Please add this property inside your configure method.

cors().configurationSource( 
           request -> {             
              CorsConfiguration cors = new CorsConfiguration();                 
              cors.setAllowedMethods(
                Arrays.asList( 
                  HttpMethod.GET.name(),
                  HttpMethod.POST.name()
             ));   
             cors.applyPermitDefaultValues();           
             return cors;   
         })
        })

Append this above property. If you need to support cross origin for PUT, DELETE please add in it.

Upvotes: 0

Related Questions