web.cors.allowed-origins in application.properties isn't allowing the CORS for specific urls - spring-boot

I'm trying to enable the CORS throughout the app for "http://localhost/4200". Since I'm using Springboot 2 and accord. to its docs, I just have to add this property in application.properties file:
management.endpoints.web.cors.allowed-origins=http://localhost:4200
But this doesn't work. Secondly since there is a request I'm making through a restController, for the testing purpose, I tried to add the inline :
CrossOrigin(origins = "http://localhost:4401")
This allowed the flow of data through 4401 port too.

It is not possible to set CORS settings from the application.properties file.
The property management.endpoints.web.cors.allowed-origins is related to Spring Actuator.
If you want to use the setting for a specific endpoint, you can use the #CrossOrigin annotation as you mentioned in your question.
If you want to set a global policy for your application, you can add a configuration class / bean for setting the CORS settings.
See: https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-cors
Related question:
Spring Boot enabling CORS by application.properties

Related

Setting end session endpoint

With a Spring Boot client configured in the DMZ and Spring Security OAuth configured using:
issuer-uri: https://authentication_server/auth/realms/my-realm
I get this error from Spring Security:
The Issuer "https://external_url/auth/realms/my-realm" provided in the configuration metadata did not match the requested issuer "https://authentication_server/auth/realms/my-realm
From this post I have learned that I need to specify authorization-uri, token-uri and jwk-set-uri instead of issuer-uri, and then it also works.
authorization-uri: https://external_url/auth/realms/my-realm/protocol/openid-connect/auth
token-uri: https://authentication_server/auth/realms/my-realm/protocol/openid-connect/token
jwk-set-uri: https://authentication_server/auth/realms/my-realm/protocol/openid-connect/certs
(I do not get why Spring Security cannot auto-configure with the same values from the issuer-uri when it works setting the values individually)
Now the problem is that logout stops working. When using issuer-uri the OAuth is auto-configured and end_session_endpoint is fetched from the answer, but when specifying each setting there is no way to specify the end_session_endpoint.
Is this an outstanding issue in Spring Security OAuth, or do I need to configure it differently?
I had to make a work around for this. With little time I started by copying the existing OidcClientInitiatedLogoutSuccessHandler which I already were using in configuring LogoutRedirectUri.
I simply copied the class and changed the implementation of the method endSessionEndpoint() to return the URI which is returned by our OAuth server as end_session_endpoint.
This issue is tracked in spring-security GitHub.
Probable fix will be allowing to add "Additional attributes for ClientRegistration and ProviderDetails".

Session cookie custom path

I have an spring boot application and want to deploy it to wildfly12. What I'm trying to achieve is that to set a custom path for JSESSIONID cookie. But after all, my efforts haven't had any results.
I have tried to use this property in my application.properties file:
server.servlet.session.cookie.path=/
When I run the application with the embedded tomcat, everything works fine; But when I deploy my app to wildfly, regardless of the value of that property, it always sets the cookie path to the "context-path" of the application.
I have also tried to use this property also:
server.servlet.context-path=/
but no success so far!
There is also this tag inside the standalone.xml file:
<session-cookie http-only="true" secure="true"/>
but it seems that it has nothing to do with the cookie path, as it doesn't have any property regarding that.
The configuration you are doing is for the embedded server of spring boot application.
Embedded server settings present in application properties (can be check here the section # EMBEDDED SERVER CONFIGURATION and the namespace server.servlet.session.cookie.*).
To modify cookie related configuration on external servers, you have to create CookieSerializer bean which can be used to customize cookie configuration. e.g.
#Bean
public CookieSerializer cookieSerializer() {
DefaultCookieSerializer serializer = new DefaultCookieSerializer();
serializer.setCookieName("JSESSIONID");
serializer.setCookiePath("/");
serializer.setDomainNamePattern("^.+?\\.(\\w+\\.[a-z]+)$");
return serializer;
}
You can refer spring guide for more information.

Spring Boot Actuator paths not enabled by default?

While updating my Spring Boot application to the latest build snapshot and I am seeing that none of the actuator endpoints are enabled by default. If I specify them to be enabled in application.properties, they show up.
1) Is this behavior intended? I tried searching for an issue to explain it but couldn't find one. Could somebody link me to the issue / documentation?
2) Is there a way to enable all the actuator endpoints? I often find myself using them during development and would rather not maintain a list of them inside my properties file.
Two parts to this answer:
"Is there a way to enable all the actuator endpoints?"
Add this property endpoints.enabled=true rather than enabling them individually with endpoints.info.enabled=true, endpoints.beans.enabled=true etc
Update: for Spring Boot 2.x the relevant property is:
endpoints.default.web.enabled=true
"Is this behavior intended?"
Probably not. Sounds like you might have spotted an issue with the latest milestone. If you have a reproducible issue with a Spring Boot milestone then Spring's advice is ...
Reporting Issues
Spring Boot uses GitHub’s integrated issue tracking system to record bugs and feature requests. If you want to raise an issue, please follow the recommendations below:
Before you log a bug, please search the issue tracker to see if someone has already reported the problem.
If the issue doesn’t already exist, create a new issue.
Even if we enable all the actuator endpoints as below
management.endpoints.web.exposure.include=* (In case of YAML the star character should be surrounded by double quotes as "*" because star is one of the special characters in YAML syntax)
The httptrace actuator endpoint will still not be enabled in web by default. HttpTraceRepository interface need to be implemented to enable httptrace (See Actuator default endpoints, Actuator endpoints, Actuator httptrace).
#Component
public class CustomHttpTraceRepository implements HttpTraceRepository {
AtomicReference<HttpTrace> lastTrace = new AtomicReference<>();
#Override
public List<HttpTrace> findAll() {
return Collections.singletonList(lastTrace.get());
}
#Override
public void add(HttpTrace trace) {
if ("GET".equals(trace.getRequest().getMethod())) {
lastTrace.set(trace);
}
}
}
Now the endpoints can be accessed using the url,
http://localhost:port/actuator/respective-actuator-endpoint
(Example http://localhost:8081/actuator/httptrace)
If there is a management.servlet.context-path value present in properties file then the URL will be,
http://localhost:port/<servlet-context-path>/respective-actuator-endpoint
(Example http://localhost:8081/management-servlet-context-path-value/httptrace)
UPDATE: use this only in dev environment, not in production!
Is there a way to enable all the actuator endpoints?
Using Spring Boot 2.2.2 Release, this worked for me:
On the file src/main/resources/application.properties add this:
management.endpoints.web.exposure.include=*
To check enabled endpoints go to http://localhost:8080/actuator
Source: docs.spring.io

Spring boot disable Custom HealthIndicator

I've created a custom HealthIndicator which I wants to disable in production until we go live fully.
I'm aware there is a property to disable default health indicators (management.health.defaults.enabled=false), but not for custom HealthIndicators.
Is there any way I can temporarily turn off MyCustomHealthIndicator in application property configuration level?
You can use Spring Boot's mechanism without using custom properties. Start by adding an annotation on your class:
#ConditionalOnEnabledHealthIndicator("your-health")
You can now disable your own health indicator by using the Spring Boot suggested property:
management.health.your-health.enabled=false
It has the same effect, but it allows you to group your enabled and disabled health indicators together.
Your health indicator bean,
#ConditionalOnProperty(value='health.indicator.enabled')
#Bean
class MyHealthIndicator {
}
In your application.properties file,
health.indicator.enabled=true/false
Hope this helps !
#ConditionalOnEnabledHealthIndicator("your-health")
You can now disable your own health indicator by using the Spring Boot suggested property:
management.health.your-health.enabled=false
This works when we re-start the app. should it work without re-start?

Set/override Spring / Spring Boot properties at runtime

At the project with Spring Boot we use application.properties but need to configure some of these properties (like port number of logging level) based on an external configuration. We access the configuration via API so it is known only at runtime.
Is there a way to override or set some Spring properties at runtime (for example using a bean) and if yes how can this be achieved?
You could do this with Spring Cloud Config
Just for the purpose of illustration, here's a relatively quick way to see dynamic property overrides at runtime:
First, for your bean to be able to pick up changed properties, you need to annotate it with
#RefreshScope
Add the spring cloud dependency to your spring boot app, eg for gradle
compile group: 'org.springframework.cloud', name: 'spring-cloud-starter', version: '1.1.1.RELEASE'
( NB You also need the spring boot actuator dependency.)
With the app running, you can view your current config at eg
http://localhost:8080/env
eg if you have a property 'my.property' in application.properties, you'll see something like:
"applicationConfig: [classpath:/application.properties]": {
"my.property": "value1",
etc
To change the value, POST my.property=value2 to /env as application/x-www-form-urlencoded
eg
curl -X POST http://localhost:8080 -d my.property=value2
GET /env again and you'll see the new value appears under the "manager" section
To apply the changed properties, do an empty POST to /refresh. Now your bean will have the new value.
Could you use system properties to pass in the variable? If you configure the PropertyPlaceholderConfigurer you can set the precedence of system properties vs file properties.
For example, something like:
#Bean public PropertyPlaceholderConfigurer placeHolderConfigurer() {
PropertyPlaceholderConfigurer props = new PropertyPlaceholderConfigurer()
props.setSystemPropertiesMode( PropertyPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_OVERRIDE )
props.setLocations(new
PathMatchingResourcePatternResolver().getResources("classpath:/**.properties"));
props
}
The above would load your .properties file, but we set the priority to be system variables first, so if you set a system variable that will override the same variable in the config.
Alternatively, looking at the docs, Spring recommends defining a search order in your Environment:
[PropertyPlaceholderConfigurer is still appropriate for use when]
existing configuration makes use of the "systemPropertiesMode" and/or "systemPropertiesModeName" properties. Users are encouraged to
move away from using these settings, and rather configure property
source search order through the container's Environment; however,
exact preservation of functionality may be maintained by continuing to
use PropertyPlaceholderConfigurer.
Hopefully one of the above should sort out what you need?

Resources