CORS error on accessing route URL - angularjs

I am running my code using java and angularjs. The server is hosted in port http://localhost:8080
When I hit http://localhost:8080/data, I get below error
XMLHttpRequest cannot load
http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?.
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:8080' is therefore not allowed
access.
$routeProvider
.when('/', {
templateUrl: 'views/home.html',
controller: 'MainCtrl'
})
.when('/data', {
templateUrl: 'http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?'
})
I am new to Angular. Can any one help what I am doing wrong in my code. I have searched in google and found some suggestions to enable headers at server side or at the browser end. I am looking if something I can do from my code itself. I know there are lot of similar question asked in this forum but not able to find the right solution. If anyone can help me by providing any link instead of giving me downvote

Put these in your headers :
HttpServletResponse resp = (HttpServletResponse) servletResponse;
resp.addHeader("Access-Control-Allow-Origin","*");
resp.addHeader("Access-Control-Allow-Methods","GET,POST");
resp.addHeader("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept");`

If you use spring at the server side, you can config your backend to allow origin access from foreign server (flickr in your case)
If you are JEE-Configuration, you should find another xml-config sample like below.
An Example can you find in spring guiedes under
https://spring.io/blog/2015/06/08/cors-support-in-spring-framework
#Configuration
#EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("http://domain2.com")
.allowedMethods("PUT", "DELETE")
.allowedHeaders("header1", "header2", "header3")
.exposedHeaders("header1", "header2")
.allowCredentials(false).maxAge(3600);
}
}
In case of xml configuration:
<mvc:cors>
<mvc:mapping path="/**" />
</mvc:cors>
<mvc:cors>
<mvc:mapping path="/api/**"
allowed-origins="http://domain1.com, http://domain2.com"
allowed-methods="GET, PUT"
allowed-headers="header1, header2, header3"
exposed-headers="header1, header2" allow-credentials="false"
max-age="123" />
<mvc:mapping path="/resources/**"
allowed-origins="http://domain1.com" />
</mvc:cors>
Please read the guide for more information.

Related

Keycloak and Spring Oauth2 - CORS issue [duplicate]

I am using keycloak to secure my rest service. I am refering to the tutorial given here. I created the rest and front end. Now when I add keycloak on the backend I get CORS error when my front end makes api call.
Application.java file in spring boot looks like
#SpringBootApplication
public class Application
{
public static void main( String[] args )
{
SpringApplication.run(Application.class, args);
}
#Bean
public WebMvcConfigurer corsConfiguration() {
return new WebMvcConfigurerAdapter() {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/*")
.allowedMethods(HttpMethod.GET.toString(), HttpMethod.POST.toString(),
HttpMethod.PUT.toString(), HttpMethod.DELETE.toString(), HttpMethod.OPTIONS.toString())
.allowedOrigins("*");
}
};
}
}
The keycloak properties in the application.properties file look like
keycloak.realm = demo
keycloak.auth-server-url = http://localhost:8080/auth
keycloak.ssl-required = external
keycloak.resource = tutorial-backend
keycloak.bearer-only = true
keycloak.credentials.secret = 123123-1231231-123123-1231
keycloak.cors = true
keycloak.securityConstraints[0].securityCollections[0].name = spring secured api
keycloak.securityConstraints[0].securityCollections[0].authRoles[0] = admin
keycloak.securityConstraints[0].securityCollections[0].authRoles[1] = user
keycloak.securityConstraints[0].securityCollections[0].patterns[0] = /api/*
The sample REST API that I am calling
#RestController
public class SampleController {
#RequestMapping(value ="/api/getSample",method=RequestMethod.GET)
public string home() {
return new string("demo");
}
}
the front end keycloak.json properties include
{
"realm": "demo",
"auth-server-url": "http://localhost:8080/auth",
"ssl-required": "external",
"resource": "tutorial-frontend",
"public-client": true
}
The CORS error that I get
XMLHttpRequest cannot load http://localhost:8090/api/getSample. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access. The response had HTTP status code 401.
I know.. the Problem is quite Old.
But if you've Problems with the local development with Spring Boot + Keycloak you can use the Config
keycloak.cors=true
in your application.properties.
Cheers :)
Try creating your CORS bean like my example. I recently went through the same thing (getting CORS to work) and it was a nightmare because the SpringBoot CORS support is currently not as robust or straightforward as the MVC CORS.
#Bean
public FilterRegistrationBean corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
bean.setOrder(0);
return bean;
}
This is how I set it up to accept any origin application-wide, but if you change a few of the parameters you should be able to replicate what you want. ie. if you wanted to add only the methods you mentioned, chain some addAllowedMethod(). Allowed origins would be the same, and then your addMapping("/api/*") would become source.registerCorsConfiguration("/api/*", config);.
Edit:
Spring Data Rest and Cors
Take a look at this. Sebastian is on the Spring engineering team so this is about as good as you're going to get for an official answer.
I came here with the same problem and fix it ommiting authentication for OPTIONS method only, like this:
keycloak.securityConstraints[0].security-collections[0].omitted-methods[0]=OPTIONS
It worked for me because the OPTIONS request Keycloack does, does not include Authentication header.
UPDATE
There was something with my browser's cache so I could not see the real impact of a change in my backend code. It looks like what really worked for me was enabling all CORS origins at #RestController level, like this:
#CrossOrigin(origins = "*")
#RestController
public class UsersApi {...}
I don't have access to code examples, but based on the code configurations you have included, it looks like a missing configuration is causing spring to exclude CORS headers.
J. West's response is similar to recent issues I encountered with Spring and CORS, I would however caution you to look into which implementation a spring example references, because there are two. Spring Security and Spring MVC Annotations. Both of these implementations work independent of each other, and can not be combined.
When using the filter based approach as you are (even boiled down), the key was to set allow credentials to true, in order for the authentication headers to be sent by the browser across domains. I would also advise using the full code method proposed above, as this will allow you to create a far more configurable web application for deployment across multiple domains or environments by property injection or a service registry.
Access-Control-Allow-Origin header is supposed to be set by the server application basis the Origin request header provided in the request to the server application. Usually browsers set the Origin header in request whenever they sense a cross origin request being made. And they expect a Access-Control-Allow-Origin header in response to allow it.
Now, for keycloak, I struggled with the same issue. Looking at this, it seems like keycloak does not add Access-Control-Allow-Origin header in case of error response. However, for me it was not adding this header in the response even in case of success response.
Looking into the code and adding breakpoints, I noticed that the webOrigin for client object was not getting populated from the Origin header even if passed and hence CORS was not adding the access control response header.
I was able to get it working by adding the following line of code just before the CORS build call:
client.addWebOrigin(headers.getRequestHeader("Origin").get(0));
before:
Cors.add(request, Response.ok(res, MediaType.APPLICATION_JSON_TYPE)).auth().allowedOrigins(client).allowedMethods("POST").exposedHeaders(Cors.ACCESS_CONTROL_ALLOW_METHODS).build();
Once I built the code with this change and started the server, I started getting the three access control response headers:
Access-Control-Expose-Headers: Access-Control-Allow-Methods
Access-Control-Allow-Origin: http://localhost:9000
Access-Control-Allow-Credentials: true
I am using client credentials grant type; hence i added it only in the buildClientCredentialsGrant at TokenEndpoint.java#L473.
I still need to do some more code diving in order to say for sure that it is a bug for success responses at well and to find a better place to set this on the client object in keycloak code (like where client object is being constructed)
You are welcome to give it a try.
UPDATE:
I take this back. I re-registered my client in keycloak with Root URL as http://localhost:9000 (which is my front-end's application port) and i started getting the proper access control response headers. Hope this helps you.
I know the problem is too old but, I found better solution.
Read more at official documentation
Inside your application.yml file
keycloak:
auth-server-url: http://localhost:8180/auth
realm: CollageERP
resource: collage-erp-web
public-client: true
use-resource-role-mappings: true
cors: true
cors-max-age: 0
principal-attribute: preferred_username
cors-allowed-methods: POST, PUT, DELETE, GET
cors-allowed-headers: X-Requested-With, Content-Type, Authorization, Origin, Accept, Access-Control-Request-Method, Access-Control-Request-Headers
or you can config using application.properties file
keycloak.auth-server-url= http://localhost:8180/auth
keycloak.realm= CollageERP
keycloak.resource= collage-erp-web
keycloak.public-client= true
keycloak.use-resource-role-mappings= true
keycloak.cors= true
keycloak.cors-max-age= 0
keycloak.principal-attribute= preferred_username
keycloak.cors-allowed-methods= POST, PUT, DELETE, GET
keycloak.cors-allowed-headers= X-Requested-With, Content-Type, Authorization, Origin, Accept, Access-Control-Request-Method, Access-Control-Request-Headers
and my java adaper class
import org.keycloak.adapters.KeycloakConfigResolver;
import org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver;
import org.keycloak.adapters.springsecurity.KeycloakConfiguration;
import org.keycloak.adapters.springsecurity.config.KeycloakWebSecurityConfigurerAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.web.authentication.session.RegisterSessionAuthenticationStrategy;
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
import javax.ws.rs.HttpMethod;
#KeycloakConfiguration
#EnableGlobalMethodSecurity(jsr250Enabled = true)
public class KeycloakSecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http.cors().and().authorizeRequests()
.antMatchers(HttpMethod.OPTIONS).permitAll()
.antMatchers("/api/**")
.authenticated()
.anyRequest().permitAll();
http.csrf().disable();
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) {
auth.authenticationProvider(keycloakAuthenticationProvider());
}
#Bean
#Override
protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
}
#Bean
public KeycloakConfigResolver KeycloakConfigResolver() {
return new KeycloakSpringBootConfigResolver();
}
}
I want to share with you the solution that worked for me hoping to help whoever is facing the same issue. I am going to give you two solutions actually.
Spring reactive:
#Configuration
#EnableWebFluxSecurity
public class SecurityConfig {
#Autowired
private ReactiveClientRegistrationRepository clientRegistrationRepository;
#Bean
SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
CorsConfiguration cors_config = new CorsConfiguration();
cors_config.setAllowCredentials(true);
cors_config.applyPermitDefaultValues();
cors_config.setAllowedOrigins(Arrays.asList("http://localhost:3000", "null"));
cors_config.setAllowedMethods(List.of("GET","POST","OPTIONS","DELETE"));
cors_config.setAllowedHeaders(List.of("*"));
http.cors().configurationSource(source -> cors_config)
.and()
.csrf().disable()
.authorizeExchange(exchanges -> exchanges.anyExchange().authenticated())
.oauth2Login()//Setting Oauth2Login
.authenticationSuccessHandler(new RedirectServerAuthenticationSuccessHandler("")).and()
.logout(logout -> logout //Setting Oauth2Logout
.logoutHandler(logoutHandler())
.logoutSuccessHandler(oidcLogoutSuccessHandler()));
return http.build();
}
private ServerLogoutSuccessHandler oidcLogoutSuccessHandler() {
OidcClientInitiatedServerLogoutSuccessHandler oidcLogoutSuccessHandler =
new OidcClientInitiatedServerLogoutSuccessHandler(this.clientRegistrationRepository);
// Sets the location that the End-User's User Agent will be redirected to
// after the logout has been performed at the Provider
oidcLogoutSuccessHandler.setPostLogoutRedirectUri("");
return oidcLogoutSuccessHandler;
}
private DelegatingServerLogoutHandler logoutHandler() {
//Invalidate session on logout
return new DelegatingServerLogoutHandler(
new SecurityContextServerLogoutHandler(), new WebSessionServerLogoutHandler());
}
}
Spring MVC:
#Configuration
public class SecurityConfig {
#Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
CorsConfiguration cors_config = new CorsConfiguration();
cors_config.setAllowCredentials(true);
cors_config.applyPermitDefaultValues();
cors_config.setAllowedOrigins(Arrays.asList("http://localhost:3000", "null"));
cors_config.setAllowedMethods(List.of("GET","POST","OPTIONS","DELETE"));
cors_config.setAllowedHeaders(List.of("*"));
http.cors().configurationSource(source -> cors_config).and()...
return http.build();
}
}
Be sure to have cors enabled on Keycloak too, navigate to
realm->clients->settings->weborigins
and submit your permitted origins.
If you are sending credentials or cookies in your requests, be sure to configure it, for example, if you are using ReactJS:
const httpConfig = { withCredentials: true };
axios.get('YourUrl', httpConfig)
.then(response => {})
.catch(error => {})
.finally(() => {});
When your client is sending an Authentication header, you cannot use
allowedOrigins("*"). You must configure a specific origin URL.
Since you have set the property keycloak.cors = true in your application.properties file, you have to mention the CORS enabled origins in the Keycloak server. To do that follow the below steps.
Go to Clients -> Select the client (Token owner) -> Settings -> Web Origins
Add origins one by one or add * to allow all.
After doing this you have to get a new token. (If you decode the token you will see your origins as allowed-origins": ["*"])
Setting the property keycloak.cors = false is another option. But this completely disables CORS.

How can I add CORS functionality into my http-gateway (spring-integration-dsl)?

I have got a reactjs frontend which sends a request to my api based on spring-integration.
The problem I got is, that I don't know how to bind the CORS functionality in my gateway.
I tried something like this
#Bean
public CrossOrigin cors(){
CrossOrigin c = new CrossOrigin();
c.setOrigin("/**");
return c;
}
#Bean
public IntegrationFlow httpGetTest() {
return IntegrationFlows.from(httpGetGateTest()).channel("http.test.channel").handle("testEndpoint", "hello").get();
}
#Bean
public MessagingGatewaySupport httpGetGateTest() {
HttpRequestHandlingMessagingGateway handler = new HttpRequestHandlingMessagingGateway();
handler.setRequestMapping(createMapping(new HttpMethod[]{HttpMethod.GET}, "/test"));
handler.setCrossOrigin(cors());
handler.setHeaderMapper(headerMapper());
return handler;
}
Request:
axios.get('http://localhost:8080/test')
.then(res=>{console.log(res)})
My endpoint returns "Hello World"
Failed to load resource: the server responded with a status of 415 ()
Access to XMLHttpRequest at 'http://localhost:8080/test' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
First of all, please, be sure that your client really send an Origin HTTP request header.
Otherwise the CORS filtering is not applied to the request: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
Although it sounds like it is there anyway: from origin 'http://localhost:3000'.
Consider to change your setOrigin("/**") to the setOrigin("*"). The Cross-Origin policy is about the whole ULR (domain to be precise), not relative path.
BTW, there is a Java DSL factory in Spring Integration for HTTP components:
#Bean
public IntegrationFlow httpGetTest() {
return IntegrationFlows.from(Http.inboundGateway("/test")
.requestMapping(r -> r.methods(HttpMethod.GET))
.crossOrigin(cors -> cors.origin("*"))
.headerMapper(headerMapper()))
.channel("http.test.channel")
.handle("testEndpoint", "hello")
.get();
}

Web Api 2 Preflight CORS request for Bearer Token

I have a web-app with an AngularJS front-end and a Web Api 2 back-end, and it uses bearer-tokens for authentication.
All is well in FireFox & IE, but with Chrome, my initial login request is SOMETIMES pre-flighted.
Here's the call from the AngularJS service:
$http.post(http://localhost:55483/token, data, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }).success(function (response) { ... });
The preflight request gets kicked back with an "Allow-Access-Control-Origin" error.
However, if I click the Login button again (thereby re-sending the above request) all is well.
Any idea on how to prevent/trap/handle this?
PS: I use the LOC
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
in the ApplicationOAuthProvider.cs file to put the CORS allow-header on the /Token request, which works fine in IE, FireFox and sometimes in Chrome.
The below is Fancy comment:
Figured this out with help from post by LeftyX on Jun 29: - Move
this LOC app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); to the
FIRST LINE in the ConfigureAuth method of Startup.Auth.cs. - Then,
REMOVE this LOC
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin",
new[] { "*" }); from the GrantResourceOwnerCredentials() method of
ApplicationOAuthProvide.cs. Preflight CORS-request them gets
handled properly, and then the actual requet goes through
Thank man, you save my whole day.
Cause it happens for many guys, I bring your comment to answer box for other guys can see it.
I don't want to get vote up for this. Please comment on my answer instead
Thank you
I hope this is able to help somebody out there. For me:
adding the app.useCors(); LOC did not work.
Adding the app.useCors(); LOC worked for other people on my team.
So I needed a solution that would work across everyone's environments.
Ultimately what I ended up doing was adding the header and value right into the Web.config with the following (where localhost:9000 is my node application that is serving up angular):
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="http://localhost:9000" />
<add name="Access-Control-Allow-Headers" value="Content-Type"/>
</customHeaders>
</httpProtocol>
</system.webServer>
Then in production you can just change the origin value to the production front-end url.
If you want CORS enabled for all origins, change the value to "*".
By default - Access-Control-Max-Age: seconds is 0 and your requests not caching.
Try set it to max value: (Owin selfhost). It solve problem with extra OPTIONS requests
app.UseCors(new CorsOptions
{
PolicyProvider = new CorsPolicyProvider
{
PolicyResolver = context => Task.FromResult(new CorsPolicy
{
AllowAnyHeader = true,
AllowAnyMethod = true,
AllowAnyOrigin = true,
SupportsCredentials = false,
PreflightMaxAge = Int32.MaxValue // << ---- THIS
})
}
});
Let me add one thing I have learned today. This sample:
app.UseCors(CorsOptions.AllowAll);
worked for me since the beginning. I just wasn't aware, becuase the requests I have been doing to verify, did not have following headers:
Origin: http://hostname
Access-Control-Request-Method: GET
Only after I added those, the correct headers started to appear in responses.

How do you escape a . (full stop) or / so it doesn't change URL's meaning?

I have a Web API 2.0 service which defines a particular route:
/api/someEntityGroup/{entityName}
I'm calling this enpoint using Angular $resource service.
The problem is when user wants to provide an entity name with characters that have a specific meaning in URL:
404 Not found - . (full stop), /, +
400 Bad request - ?, :, &, %, *, <, >
And these are the ones I've encountered. There may be others that may be problematic as well and I'm not even aware of them (yet).
If I use window.escape() function these still don't work, but I mainly get 404 back (the only exception being * which still returns 400 Bad request).
My code
Angular resource creation:
.factory("entityResource", ["$resource", function() {
return $resource("/api/entities/:id", null, {
search: {
method: "GET",
url: "/api/entities/:name",
isArray: true
}
});
}]);
How I call it in my code:
entityResource.search({ query: scope.name }, function(data) {
...
});
My Api controller action:
[RoutePrefix("/api/entities")]
public class EntitiesController: ApiController
{
[Route("{searchQuery}")]
public IEnumerable<Interest> Get(string searchQuery)
{
return this.interestService.Search(searchQuery);
}
...
}
I can shed some light on your 404 Not found issue when using ., /, + characters.
The issue isn't with Angular but rather with Web API and the way it resolves routes. Urls that Web API interprets as being managed resources (e.g. static content, pages etc.) it will try to resolve independently.
Set the following in your web.config to disable this behavior and force WebAPI to run all requests through your modules:
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
</system.webServer>
Just a warning - If your Web API is hosted together with something like MVC or a static website, the above is not recommended as it will force all managed resources (pages, MVC routes, content[css,js,images]) through your API modules and there will be a performance impact. However, if all the API is doing is serving resource routes I would recommend enabling the above.

NetworkError: 405 Method Not Allowed AngularJS REST

In AngularJS, I had the following function, which worked fine:
$http.get( "fruits.json" ).success( $scope.handleLoaded );
Now I would like to change this from a file to a url (that returns json using some sweet Laravel 4):
$http.get( "http://localhost/fruitapp/fruits").success( $scope.handleLoaded );
The error I get is:
"NetworkError: 405 Method Not Allowed - http://localhost/fruitapp/fruits"
What's the problem? Is it because fruit.json was "local" and localhost is not?
From w3:
10.4.6 405 Method Not Allowed
The method specified in the Request-Line is not allowed for the resource
identified by the Request-URI. The response MUST include an Allow header
containing a list of valid methods for the requested resource.
It means the for the URL: http://localhost/fruitapp/fruits The server is responding that the GET method isn't allowed. Is it a POST or PUT?
The angular js version you are using would be <= 1.2.9.
If Yes, try this.
return $http({
url: 'http://localhost/fruitapp/fruits',
method: "GET",
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
});
I had a similar issue with my SpringBoot project, I was getting the same error in the browser console but I saw a different error message when I looked at the back-end log, It was throwing this error: "org.springframework.web.HttpRequestMethodNotSupportedException, message=Request method 'DELETE' not supported " It turned out that I was missing the {id} parameter in the back-end controller:
** Wrong code :**
#RequestMapping(value="books",method=RequestMethod.DELETE)
public Book delete(#PathVariable long id){
Book deletedBook = bookRepository.findOne(id);
bookRepository.delete(id);
return deletedBook;
}
** Correct code :**
#RequestMapping(value="books/{id}",method=RequestMethod.DELETE)
public Book delete(#PathVariable long id){
Book deletedBook = bookRepository.findOne(id);
bookRepository.delete(id);
return deletedBook;
}
For me, it was the server not being configured for CORS.
Here is how I did it on Azure: CORS enabling on Azure
I hope something similar works with your server, too.
I also found a proposal how to configure CORS on the web.config, but no guarantee: configure CORS in the web.config. In general, there is a preflight request to your server, and if you did a cross-origin request (that is from another url than your server has), you need to allow all origins on your server (Access-Control-Allow-Origin *).

Resources