Search This Blog

Friday, August 2, 2019

Cors - Cross Site - Angular 2 7 8 Spring boot

1. Create a java file, add spring security jar in pom.xml
2. Angular just set what you want as custom header

SecurityConfig.java

package com.product.rpa.api.config;

import java.util.Arrays;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

/**
 * @author drvijay
 * @description main class
 * @version 1.0
 * @date 02-08-2019 1:30 PM
 */

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter
{

/* (non-Javadoc)
* @see org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter#configure(org.springframework.security.config.annotation.web.builders.HttpSecurity)
*/
@Override
protected void configure ( HttpSecurity http ) throws Exception
{
http.cors ().and ().csrf ().disable ();
}

/**
* Cors configuration source.
*
* @return the cors configuration source
*/
@Bean
CorsConfigurationSource corsConfigurationSource ()
{
CorsConfiguration configuration = new CorsConfiguration ();
configuration.setAllowedOrigins ( Arrays.asList ( "*" ) );
configuration.setAllowedMethods ( Arrays.asList ( "*" ) );
configuration.setAllowedHeaders ( Arrays.asList ( "*" ) );
configuration.setAllowCredentials ( true );
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource ();
source.registerCorsConfiguration ( "/**", configuration );
return source;
}

}



Angular JS

DataTableComponent.ts

import { HttpHeaders } from  '@angular/common/http';

export class DataTableComponent implements OnInit {
    public tableData;

 
    public baseURL = "http://localhost:8080/";

    constructor(private _httphelperService: HttphelperService) { }

    ngOnInit() {
        this.loadData();
    }

    loadData() {
        console.log("loadData calling");

        let jsonBody = {                     
            "key": "value"
        }

        let headers = new HttpHeaders({
            "Access-Control-Allow-Origin": "*",
            "Content-Type": "application/json",
            "appToken": "abcde12345"
        })

        let response = this._httphelperService.performPOST(this.baseURL + "/api", jsonBody , headers)
            .subscribe(data => {
                this.tableData = data;
                //alert (JSON.stringify(this.tableData));
            },
            err => {
                console.log(err.message);
            }
            );
        //console.log(response);
    }
}



HttphelperService.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from  '@angular/common/http';
import { CustomPromisify } from 'util';
import { Observable } from 'rxjs/Observable';
import { catchError, map } from "rxjs/operators";

@Injectable()
export class HttphelperService {
    public httpOptions: any;

    constructor(private _http: HttpClient) {
        //Http Headers Options
        this.httpOptions = {
            headers: new HttpHeaders(
                {
                    "Access-Control-Allow-Origin": "*",
                    "Content-Type": "application/json"
                })
        }
    }

    public performPOST(baseUrl: string, inputBody: any, apiHeaders: any) {
        if (apiHeaders === "" || apiHeaders === null || typeof apiHeaders === "undefined") {
            return this._http.post(baseUrl, inputBody, this.httpOptions);
        }
        else {
            console.log (apiHeaders);
            return this._http.post(baseUrl, inputBody, { headers: apiHeaders });
        }
    }


    public performGET(baseUrl: string, apiHeaders: any) {
        if (apiHeaders === "" || apiHeaders === null || typeof apiHeaders === "undefined") {
            return this._http.get(baseUrl, this.httpOptions);
        }
        else {
            return this._http.get(baseUrl, { headers: apiHeaders });
        }
    }

}



ENJOY


No comments:

Hit Counter


View My Stats