Skip to content

Commit

Permalink
custom authorities extractor using UserInfo Url
Browse files Browse the repository at this point in the history
  • Loading branch information
selvaebi committed Mar 20, 2019
1 parent 3617a28 commit 15a25fd
Show file tree
Hide file tree
Showing 8 changed files with 104 additions and 134 deletions.
25 changes: 10 additions & 15 deletions Jenkinsfile
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,7 @@ pipeline {
stagingHost = credentials('STAGINGHOST')
fallbackHost = credentials('FALLBACKHOST')
productionHost = credentials('PRODUCTIONHOST')
egaAAIClientId = credentials('EGAAAICLIENTID')
egaAAIClientSecret = credentials('EGAAAICLIENTSECRET')
egaAAITokenIntrospectUrl = credentials('EGAAAITOKENINTROSPECTURL')
egaAAIUserInfoUrl = credentials('EGAAAIUSERINFOURL')
}
parameters {
choice(choices: ['validate', 'create'], description: 'Behaviour at connection time (initialize/validate schema)',
Expand All @@ -28,10 +26,9 @@ pipeline {
stage('Default Build pointing to Staging DB') {
steps {
sh "mvn clean package -DskipTests -DbuildDirectory=staging/target \
-DegaAcccession-db.url=${stagingPostgresDbUrl} -DegaAccession-db.username=${postgresDbUserName} \
-DegaAcccession-db.password=${postgresDbPassword} -Dinstance.id=ega-accession-01-staging \
-Dddl-behaviour=${params.DbBehaviour} -Dega-aai-client-id=${egaAAIClientId} \
-Dega-aai-client-secret=${egaAAIClientSecret} -Dega-aai-token-introspect-url=${egaAAITokenIntrospectUrl}"
-DegaAccession-db.url=${stagingPostgresDbUrl} -DegaAccession-db.username=${postgresDbUserName} \
-DegaAccession-db.password=${postgresDbPassword} -Dinstance.id=ega-accession-01-staging \
-Dddl-behaviour=${params.DbBehaviour} -Dega-aai-user-info-url=${egaAAIUserInfoUrl}"
}
}
stage('Build For FallBack And Production') {
Expand All @@ -43,16 +40,14 @@ pipeline {
steps {
echo 'Build pointing to FallBack DB'
sh "mvn clean package -DskipTests -DbuildDirectory=fallback/target \
-DegaAcccession-db.url=${fallBackPostgresDbUrl} -DegaAccession-db.username=${postgresDbUserName} \
-DegaAcccession-db.password=${postgresDbPassword} -Dinstance.id=ega-accession-01-fallback \
-Dddl-behaviour=${params.DbBehaviour} -Dega-aai-client-id=${egaAAIClientId} \
-Dega-aai-client-secret=${egaAAIClientSecret} -Dega-aai-token-introspect-url=${egaAAITokenIntrospectUrl}"
-DegaAccession-db.url=${fallBackPostgresDbUrl} -DegaAccession-db.username=${postgresDbUserName} \
-DegaAccession-db.password=${postgresDbPassword} -Dinstance.id=ega-accession-01-fallback \
-Dddl-behaviour=${params.DbBehaviour} -Dega-aai-user-info-url=${egaAAIUserInfoUrl}"
echo 'Build pointing to Production DB'
sh "mvn clean package -DskipTests -DbuildDirectory=production/target \
-DegaAcccession-db.url=${productionPostgresDbUrl} -DegaAccession-db.username=${postgresDbUserName} \
-DegaAcccession-db.password=${postgresDbPassword} -Dinstance.id=ega-accession-01-production \
-Dddl-behaviour=${params.DbBehaviour} -Dega-aai-client-id=${egaAAIClientId} \
-Dega-aai-client-secret=${egaAAIClientSecret} -Dega-aai-token-introspect-url=${egaAAITokenIntrospectUrl}"
-DegaAccession-db.url=${productionPostgresDbUrl} -DegaAccession-db.username=${postgresDbUserName} \
-DegaAccession-db.password=${postgresDbPassword} -Dinstance.id=ega-accession-01-production \
-Dddl-behaviour=${params.DbBehaviour} -Dega-aai-user-info-url=${egaAAIUserInfoUrl}"
}
}
stage('Deploy To Staging') {
Expand Down
4 changes: 2 additions & 2 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<groupId>uk.ac.ebi.ega</groupId>
<artifactId>accessioning-service</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<packaging>${packaging.type}</packaging>

<name>accessioning-service</name>
<url>http://github.com/EBIvariation/ega-accession</url>
Expand Down Expand Up @@ -81,7 +81,7 @@
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.4-1206-jdbc42</version>
<version>42.2.5</version>
</dependency>
<!-- documentation -->
<dependency>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/*
*
* Copyright 2019 EMBL - European Bioinformatics Institute
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/

package uk.ac.ebi.ega.accession.configuration.security;

import org.springframework.boot.autoconfigure.security.oauth2.resource.AuthoritiesExtractor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import uk.ac.ebi.ega.accession.user.AccessioningUser;
import uk.ac.ebi.ega.accession.user.AccessioningUserRepository;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
* This class provides custom authorities for the EGA AAI authenticated user.
*/
public class CustomAuthoritiesExtractor implements AuthoritiesExtractor {

private AccessioningUserRepository accessioningUserRepository;

public CustomAuthoritiesExtractor(AccessioningUserRepository accessioningUserRepository) {
this.accessioningUserRepository = accessioningUserRepository;
}

@Override
public List<GrantedAuthority> extractAuthorities(Map<String, Object> map) {
String email = (String) map.get("email");
AccessioningUser accessioningUser = accessioningUserRepository.findByUserId(email);
if (accessioningUser == null) {
accessioningUser = new AccessioningUser(email, AccessioningUser.Role.ROLE_USER);
accessioningUserRepository.save(accessioningUser);
return Arrays.asList(new SimpleGrantedAuthority(AccessioningUser.Role.ROLE_USER.name()));
}
return Arrays.asList(new SimpleGrantedAuthority(accessioningUser.getRole().toString()));
}
}

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -18,16 +18,14 @@

package uk.ac.ebi.ega.accession.configuration.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.security.oauth2.resource.AuthoritiesExtractor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
import uk.ac.ebi.ega.accession.user.AccessioningUserRepository;

@ConditionalOnProperty(value = "security.enabled", havingValue = "true")
Expand All @@ -45,19 +43,6 @@ public class EnableSecurityConfig extends ResourceServerConfigurerAdapter {
"/"
};

@Autowired
private RemoteTokenServices remoteTokenServices;

@Autowired
private AccessioningUserRepository accessioningUserRepository;

@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
DefaultAccessTokenConverter defaultAccessTokenConverter = new DefaultAccessTokenConverter();
defaultAccessTokenConverter.setUserTokenConverter(new CustomUserAuthenticationConverter(accessioningUserRepository));
remoteTokenServices.setAccessTokenConverter(defaultAccessTokenConverter);
}

@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
Expand All @@ -69,4 +54,9 @@ public void configure(HttpSecurity http) throws Exception {
.antMatchers(HttpMethod.DELETE).hasAnyRole("EDITOR", "ADMIN")
.anyRequest().authenticated();
}

@Bean
public AuthoritiesExtractor authoritiesExtractor(AccessioningUserRepository accessioningUserRepository) {
return new CustomAuthoritiesExtractor(accessioningUserRepository);
}
}
5 changes: 2 additions & 3 deletions src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,5 @@ eureka.instance.preferIpAddress=true
#####################################################################################

security.enabled=true
security.oauth2.client.client-id=@ega-aai-client-id@
security.oauth2.client.client-secret=@ega-aai-client-secret@
security.oauth2.resource.token-info-uri=@ega-aai-token-introspect-url@
security.oauth2.resource.user-info-uri=@ega-aai-user-info-url@

11 changes: 10 additions & 1 deletion src/main/resources/data.sql
Original file line number Diff line number Diff line change
@@ -1 +1,10 @@
insert into accessioning_user VALUES ('[email protected]','ROLE_ADMIN');
INSERT INTO accessioning_user
SELECT
'[email protected]',
'ROLE_ADMIN'
WHERE
NOT EXISTS(
SELECT user_id
FROM accessioning_user
WHERE user_id = '[email protected]'
);
Original file line number Diff line number Diff line change
Expand Up @@ -23,48 +23,48 @@
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import uk.ac.ebi.ega.accession.configuration.AccessioningUserConfiguration;
import uk.ac.ebi.ega.accession.user.AccessioningUserRepository;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = AccessioningUserConfiguration.class)
@DataJpaTest
public class CustomUserAuthenticationConverterTest {
public class CustomAuthoritiesExtractorTest {

@Autowired
private AccessioningUserRepository accessioningUserRepository;

@Test
public void testRoles() throws Exception {
CustomUserAuthenticationConverter customUserAuthenticationConverter = new
CustomUserAuthenticationConverter(accessioningUserRepository);
Map<String, Object> userIdMap = new HashMap<>();
userIdMap.put("user_id", "[email protected]");
Authentication authentication = customUserAuthenticationConverter.extractAuthentication(userIdMap);
Assert.assertEquals("ROLE_EDITOR", getAuthority(authentication));
CustomAuthoritiesExtractor customAuthoritiesExtractor = new
CustomAuthoritiesExtractor(accessioningUserRepository);
Map<String, Object> userInfoMap = new HashMap<>();
userInfoMap.put("email", "[email protected]");
List<GrantedAuthority> authorities = customAuthoritiesExtractor.extractAuthorities(userInfoMap);
Assert.assertEquals("ROLE_EDITOR", getAuthority(authorities));

userIdMap.put("user_id", "[email protected]");
authentication = customUserAuthenticationConverter.extractAuthentication(userIdMap);
Assert.assertEquals("ROLE_USER", getAuthority(authentication));
userInfoMap.put("email", "[email protected]");
authorities = customAuthoritiesExtractor.extractAuthorities(userInfoMap);
Assert.assertEquals("ROLE_USER", getAuthority(authorities));

userIdMap.put("user_id", "[email protected]");
authentication = customUserAuthenticationConverter.extractAuthentication(userIdMap);
Assert.assertEquals("ROLE_ADMIN", getAuthority(authentication));
userInfoMap.put("email", "[email protected]");
authorities = customAuthoritiesExtractor.extractAuthorities(userInfoMap);
Assert.assertEquals("ROLE_ADMIN", getAuthority(authorities));

userIdMap.put("user_id", "[email protected]");
authentication = customUserAuthenticationConverter.extractAuthentication(userIdMap);
Assert.assertEquals("ROLE_USER", getAuthority(authentication));
userInfoMap.put("email", "[email protected]");
authorities = customAuthoritiesExtractor.extractAuthorities(userInfoMap);
Assert.assertEquals("ROLE_USER", getAuthority(authorities));
}

private String getAuthority(Authentication authentication) {
return ((SimpleGrantedAuthority) authentication.getAuthorities().toArray()[0]).getAuthority();
private String getAuthority(List<GrantedAuthority> authorities) {
return authorities.get(0).getAuthority();
}

}

0 comments on commit 15a25fd

Please sign in to comment.