Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add header for hsts security #1175

Open
wants to merge 6 commits into
base: v2.2
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion configs
51 changes: 33 additions & 18 deletions src/main/java/org/opensrp/web/config/security/SecurityConfig.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/**
*
*
*/
package org.opensrp.web.config.security;

Expand Down Expand Up @@ -42,13 +42,13 @@
*/
@KeycloakConfiguration
public class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter {

@Value("#{opensrp['opensrp.cors.allowed.source']}")
private String opensrpAllowedSources;

@Value("#{opensrp['opensrp.cors.max.age']}")
private long corsMaxAge;

@Value("${keycloak.configurationFile:WEB-INF/keycloak.json}")
private Resource keycloakConfigFileResource;

Expand All @@ -58,24 +58,33 @@ public class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
@Value("#{opensrp['metrics.permitAll'] ?: false }")
private boolean metricsPermitAll;

@Value("#{opensrp['hsts.header.on'] ?: false }")
private boolean hstsHeaderOn;

@Value("#{opensrp['hsts.include.subdomain'] ?: false }")
private boolean hstsIncludeSubdomain;

@Value("#{opensrp['hsts.max.age.in.seconds']}")
private Integer hstsMaxAgeInSeconds;

@Autowired
private KeycloakClientRequestFactory keycloakClientRequestFactory;

private static final String CORS_ALLOWED_HEADERS = "origin,content-type,accept,x-requested-with,Authorization";

/**
* Registers the KeycloakAuthenticationProvider with the authentication manager.
*/
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
SimpleAuthorityMapper grantedAuthorityMapper = new SimpleAuthorityMapper();
grantedAuthorityMapper.setPrefix("ROLE_");

KeycloakAuthenticationProvider keycloakAuthenticationProvider = keycloakAuthenticationProvider();
keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(grantedAuthorityMapper);
auth.authenticationProvider(keycloakAuthenticationProvider);
}

/**
* Defines the session authentication strategy.
*/
Expand All @@ -84,7 +93,7 @@ public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception
protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
}

@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
Expand Down Expand Up @@ -114,9 +123,15 @@ protected void configure(HttpSecurity http) throws Exception {
.and()
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("logout.do", "GET"));
if(hstsHeaderOn){
http.headers()
.httpStrictTransportSecurity()
.includeSubDomains(hstsIncludeSubdomain)
.maxAgeInSeconds(hstsMaxAgeInSeconds);
}
/* @formatter:on */
}

@Override
public void configure(WebSecurity web) throws Exception {
/* @formatter:off */
Expand All @@ -125,7 +140,7 @@ public void configure(WebSecurity web) throws Exception {
.and().ignoring().mvcMatchers("/images/**");
/* @formatter:on */
}

@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
Expand All @@ -137,24 +152,24 @@ public CorsConfigurationSource corsConfigurationSource() {
source.registerCorsConfiguration("/**", configuration);
return source;
}

@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public KeycloakRestTemplate keycloakRestTemplate() {
return new KeycloakRestTemplate(keycloakClientRequestFactory);
}

@Bean
public KeycloakDeployment keycloakDeployment() throws IOException {
if (!keycloakConfigFileResource.isReadable()) {
throw new FileNotFoundException(String.format("Unable to locate Keycloak configuration file: %s",
keycloakConfigFileResource.getFilename()));
keycloakConfigFileResource.getFilename()));
}
try(InputStream inputStream=keycloakConfigFileResource.getInputStream()){

try (InputStream inputStream = keycloakConfigFileResource.getInputStream()) {
return KeycloakDeploymentBuilder.build(inputStream);
}

}

}
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ public ResponseEntity<String> thisMonthDataSendTODHIS2(HttpServletRequest reques
FileOutputStream fileOutputStream = new FileOutputStream(qrCodesDir + File.separator + fileName);
OutputStream os = response.getOutputStream();) {
user = openmrsUserService.getUser(currentPrincipalName);
if (!checkRoleIfRoleExitst(user.getRoles(), "opensrp-generate-qr-code")) {
if (!checkRoleIfRoleExits(user.getRoles(), "opensrp-generate-qr-code")) {
return new ResponseEntity<>("Sorry, insufficient privileges to generate ID QR codes", HttpStatus.OK);
}

Expand All @@ -120,7 +120,7 @@ public ResponseEntity<String> thisMonthDataSendTODHIS2(HttpServletRequest reques
return new ResponseEntity<>(new Gson().toJson("" + message), HttpStatus.OK);
}

boolean checkRoleIfRoleExitst(List<String> roleList, String role) {
boolean checkRoleIfRoleExits(List<String> roleList, String role) {
for (String roleName : roleList)
if (StringUtils.containsIgnoreCase(roleName, role))
return true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,20 @@ public void testThisMonthDataSendTODHIS2ThrowsException() throws Exception {
}
assertEquals(responseString,ERROR_MESSAGE);
}

@Test
public void testCheckIfRoleExistsReturnsTrueIfRoleExists(){
List<String> roles = new ArrayList<>();
roles.add("role-1");
assertEquals(true, uniqueIdController.checkRoleIfRoleExits(roles,"role-1"));
}

@Test
public void testCheckIfRoleExistsReturnsFalseIfRoleDoesNotExist(){
List<String> roles = new ArrayList<>();
roles.add("role-1");
assertEquals(false, uniqueIdController.checkRoleIfRoleExits(roles,"role-2"));
}

private Authentication getMockedAuthentication() {
Authentication authentication = new Authentication() {
Expand Down

Large diffs are not rendered by default.