How to do IP whitelisting dynamically in the spring boot application? - spring

I want to give access to whitelisted users without considering the token from them. The authorization server is different spring boot application which provides token to access resource on spring boot application that I am working on. Now I have one API endpoint to add IP in whitelist. Currently I am using IP whitelisting in following manner-
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
#Autowired
IpWhitelistingProvider ipWhitelistingProvider;
#Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/api/**").access(ipWhitelistingProvider.acessString()+"#oauth2.hasScope('resourcescope')")
//...
}
The ipwhitelistingprovider.accessString() provides expression- hasIpAdress(1st ip in list) or hasIpAddress(2nd ip in list) and so on ....
The problem here is I can't update these expression dynamically, it only updated at application startup. So when I add new IP through API that I have previously mentioned, it won't update the expression inside access method. For updating that I need to restart the application. So how can I do it so that ip added dynamically will be available to the security?

Related

Using two API Key on Swagger Security Scheme with Spring Boot

Is it possible to have two API Keys on Swagger and give them different privileges in my API?
For example:
API_KEY_1 : Has access to one Post method
API_KEY_2 : Has access to all of my API
Many thanks
In terms of Spring Security, that all depends on how you authenticate the API keys in your application. Once you've set up the application to validate an API key and create a SecurityContext, your best bet would be to map to one of two different roles, one for limited access, and one for all access. For example:
#Configuration
public static class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
// ...
.authorizeRequests()
.mvcMatchers(HttpMethod.POST, "/some/api").hasAnyRole("BASIC", "ADMIN")
.anyRequest().hasRole("ADMIN");
}
}
More information and examples of authorization can be found in the docs.

Spring boot admin: Full authentication is required to access this resource

we are using netflix oss for reverse proxying and security of microservices, we are following the jhipster pattern mentioned here https://www.jhipster.tech/microservices-architecture/, where request from UI application goes to gateway which is Api Gateway and it proxies the request to our backend microservices , we are using jwt for authentication, we wanted a dashboard to monitor our microservices and api gateway which registers with eureka server , we started a separate spring boot admin server so that it registers with eureka server and poll microservices and gateway for metrics endpoint but we are getting exception
Full authentication is required to access this resource
which is thrown by filters which are filtering for jwts at both api gateway and microservices level,
we also tried disabled
management.security.enabled: false
but still no luck ,can some one please help to guide what changes i need to make to enable spring boot admin to successfully poll the microservices and api gateway?
I tried the following approach
firstly i enabled web.ignoring().antMatchers("/actuator/**"), so that actuator endpoints are ignored by spring security but this approach will risk my api's
Second idea:
if i enable 2 filters in spring security , the first filter would be for spring boot admin with basic authentication for actuator endpoints and second filter will be of my jwt authentication for rest all api's and downstream api's not sure will it be feasible?
i enabled the 2 filters one filter for actuator end points and 1 filter for api's but these filters are working perfectly but not able to connect to SBA
public class SpringSecurityAdminFilter extends WebSecurityConfigurerAdapter {
#Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
String password = passwordEncoder().encode("xxxx");
auth.inMemoryAuthentication().passwordEncoder(passwordEncoder()).withUser("sam").password(password).roles("ADMIN");
}
#Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/actuator/**").hasRole("ADMIN")
.and().httpBasic()
.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);//We don't need sessions to be created.
}
}
i enabled basic authentication for spring boot admin server added the property in microservices
eureka.instance.metadata-map.user.name:
eureka.instance.metadata-map.user.password:
now actuator endpoints are protected by basic authentication
I have had a similar issue. On my spring boot application we had a cors filter to block Http Head requests. So head requests cannot be accepted from spring boot admin.
Check maybe filter is blocking HEAD Http requests .
Setting management.security.enabled=false in the application.properties also necessary.

Protect specific resources id with OAuth2 on Spring Boot

I have a working OAUTH2 implementation on Spring Boot, with AuthorizationServer and ResourceServer on the same implementation, using password grant.
About the server:
The TokenStore is custom and uses a WebService to store the token remotely.
I have a custom AuthenticationProvider.
This works for controlling access to resources based on given authorities, for instance, in the ResourceServer config:
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/api/resource/**")
.hasAnyAuthority("USER", "ADMIN")
.antMatchers("/api/admin/**")
.hasAnyAuthority("ADMIN");
}
Now, I need to control that USER can access to "/api/resource/1" but not "/api/resource/2", this IDs can change and I fetch the list during the authentication.
I've tried to add the ID's list to OAuth2AccessToken additional information and adding a custom filter in the ResourceServer configuration but it always comes empty.
So, How's the proper way for implementing this without using JWT?
After some thinking and research, If someone is trying to achieve something similar, this is what I'll do:
Map the allowed ID's to authorities, e.g. ID_201 and the modules as roles, so I will have a ROLE_ADMIN.
It's possible to refer to path variables in Web Security Expressions, as explained in here. So the idea is to pass the variable (resource id) and check whether it's allowed or not.
public class WebSecurity {
public boolean checkResourceId(Authentication authentication, int id) {
//check if the list of authorities contains ID_{id}.
}
}
And in the Web Security config:
http
.authorizeRequests()
.antMatchers("/resource/{resourceId}/**").access("#webSecurity.checkResourceId(authentication,#resourceId)")
...
If you're working on Spring Boot with spring-security 4.0.4 be sure to upgrade to 4.1.1 as reported in this bug.

Add a filter to validate path variable for every HTTP request in spring security

I'm working on Server application build in spring-boot based on micro service architecture which is already having Spring Security to handle form based authentication. Now the requirement is that each of the incoming Restful requests will have a country code and area code. I need to validate if the codes passed in path variable are same as local codes or not.
I am not able to figure out how and where to trigger or hook on to Spring Security to add the filter so that each of the requests is validated before it comes to rest controller and in case the codes are not valid, the filter itself sends 400 status code as the response.
I thought there should be something in Spring Security that can be extended or customized to do this?
You need to create your custom filter by extending the GenericFilterBean override the doFilter method.
Then in your custom implementation of WebSecurityConfigurerAdapter add the above custom filter in HttpSecurity.
#Configuration
public class CustomWebSecurityConfigurerAdapter
extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilterAfter(
new MyCountryCodeFilter(), BasicAuthenticationFilter.class);
}
}

How to configure web security in spring security to allow some url to access?

How to configure WebSecurity in java based to allow some urls to be accessed. i tried as below
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeUrls()
.antMatchers("/rest/**").permitAll().antMatchers("/admin/**").hasRole("ADMIN");
}
Here on above i want to allow "/rest/" **to all (it means this url should not be under security) and "/admin/**" should be secured and have authority of Admin. FYI i am using this with Spring oauth too so "/oauth/token" also should be accessible to all.
Try this to make all urls that you need open by admin scope:
http.authorizeRequests()
.antMatchers("/admin/**").access("hasRole('ADMIN')")
I think you do not need to specify urls that are not have access permission in your configure method because they will be accessed normally.

Resources