Using two API Key on Swagger Security Scheme with Spring Boot - 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.

Related

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

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?

Keep session id in case of presence of special parameter in request. Spring Security

Does anybody know if there any way to configure Spring Security in the way that it doesn't change session id if there is some parameter in the request.
For example:
somesite.com/home.jsp?password=encrypted- change session id after
authentication
somesite.com/home.jsp?password=encrypted& keepsessionid - don't
change session id after authentication
I was thinking about filter chain, maybe removing conditionally SessionManagementFilter, but not sure if this is a proper way, and even if this will be working
For someone with the same question. I found the answer. Different session management strategy can be achieved by using multiple http security configuration (inner classes of main security classes). The special case http security configurer should be adjusted to some special request
#Configuration
#Order(1)
public class SpecialCaseSessionHandlingConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.requestMatcher(request -> Check1(request))
.authorizeRequests()
.anyRequest().authenticated();
}
}

How to authenticate some URL and ignore anything else

I want to manage security policy like below. ( HTTP Basic Authorization)
Apply authentication following URLs.
"/foo/", "/bar/"
Ignore anything else URLs. ( Even though requests have Authorization field in header)
I know permitall(). But permitall() is not suitable because it apply security policy when request has Authorization field in headers.
If you want ignore particular url then you need to implement this method.
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
public void configure(final WebSecurity web) throws Exception {
web.ignoring()
.antMatchers("/static/**");
}
}
You can put your url in place of /static/** in which you want no authentication apply.
Your example means that Spring (Web) Security is ignoring URL patterns
that match the expression you have defined ("/static/**"). This URL is
skipped by Spring Security, therefore not secured.
Read the Spring Security reference for more details:
Click here for spring security details

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);
}
}

Resources