Skip to content
GitLab
Explore
Sign in
Primary navigation
Search or go to…
Project
P
portal-backend
Manage
Activity
Members
Labels
Plan
Issues
0
Issue boards
Milestones
Wiki
Code
Merge requests
0
Repository
Branches
Commits
Tags
Repository graph
Compare revisions
Snippets
Build
Pipelines
Jobs
Pipeline schedules
Artifacts
Deploy
Releases
Package Registry
Container Registry
Operate
Environments
Terraform modules
Monitor
Incidents
Analyze
Value stream analytics
Contributor analytics
CI/CD analytics
Repository analytics
Help
Help
Support
GitLab documentation
Compare GitLab plans
Community forum
Contribute to GitLab
Provide feedback
Keyboard shortcuts
?
Snippets
Groups
Projects
Show more breadcrumbs
HBP Medical Informatics Platform
portal-backend
Commits
0f2f8bf0
Commit
0f2f8bf0
authored
5 years ago
by
jerrypan44
Browse files
Options
Downloads
Plain Diff
fix merge
parents
9e28626e
a8a6d692
No related branches found
Branches containing commit
No related tags found
Tags containing commit
2 merge requests
!7
Features/keycloak integration
,
!6
Features/keycloak integration
This commit is part of merge request
!6
. Comments created here will be created in the context of that merge request.
Changes
3
Hide whitespace changes
Inline
Side-by-side
Showing
3 changed files
build.sh
+0
-1
0 additions, 1 deletion
build.sh
pom.xml
+13
-2
13 additions, 2 deletions
pom.xml
src/main/java/eu/hbp/mip/configuration/SecurityConfiguration.java
+203
-164
203 additions, 164 deletions
.../java/eu/hbp/mip/configuration/SecurityConfiguration.java
with
216 additions
and
167 deletions
build.sh
+
0
−
1
Edit
View file @
0f2f8bf0
...
@@ -36,7 +36,6 @@ docker build --build-arg BUILD_DATE=$(date -Iseconds) \
...
@@ -36,7 +36,6 @@ docker build --build-arg BUILD_DATE=$(date -Iseconds) \
--tag
"
$IMAGE
:latest"
\
--tag
"
$IMAGE
:latest"
\
--tag
"jerrypan44/portal-backend:latest"
\
--tag
"jerrypan44/portal-backend:latest"
\
.
.
docker push
"jerrypan44/portal-backend:latest"
docker push
"jerrypan44/portal-backend:latest"
BUGSNAG_KEY
=
""
BUGSNAG_KEY
=
""
...
...
This diff is collapsed.
Click to expand it.
pom.xml
+
13
−
2
Edit
View file @
0f2f8bf0
...
@@ -16,6 +16,7 @@
...
@@ -16,6 +16,7 @@
<artifactId>
spring-boot-starter-parent
</artifactId>
<artifactId>
spring-boot-starter-parent
</artifactId>
<version>
1.3.8.RELEASE
</version>
<version>
1.3.8.RELEASE
</version>
<relativePath/>
<relativePath/>
</parent>
</parent>
<properties>
<properties>
...
@@ -256,8 +257,7 @@
...
@@ -256,8 +257,7 @@
</dependency>
</dependency>
<dependency>
<dependency>
<groupId>
org.keycloak
</groupId>
<groupId>
org.keycloak
</groupId>
<artifactId>
keycloak-spring-boot-2-starter
</artifactId>
<artifactId>
keycloak-spring-boot-starter
</artifactId>
<version>
4.0.0.Final
</version>
</dependency>
</dependency>
...
@@ -354,4 +354,15 @@
...
@@ -354,4 +354,15 @@
</plugins>
</plugins>
</build>
</build>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>
org.keycloak.bom
</groupId>
<artifactId>
keycloak-adapter-bom
</artifactId>
<version>
7.0.0
</version>
<type>
pom
</type>
<scope>
import
</scope>
</dependency>
</dependencies>
</dependencyManagement>
</project>
</project>
This diff is collapsed.
Click to expand it.
src/main/java/eu/hbp/mip/configuration/SecurityConfiguration.java
+
203
−
164
Edit
View file @
0f2f8bf0
...
@@ -49,177 +49,216 @@ import java.io.IOException;
...
@@ -49,177 +49,216 @@ import java.io.IOException;
/**
/**
* Configuration for security.
* Configuration for security.
*/
*/
@Configuration
@KeycloakConfiguration
@EnableOAuth2Client
public
class
SecurityConfiguration
extends
KeycloakWebSecurityConfigurerAdapter
{
public
class
SecurityConfiguration
extends
WebSecurityConfigurerAdapter
{
private
static
final
Logger
LOGGER
=
LoggerFactory
.
getLogger
(
SecurityConfiguration
.
class
);
@Autowired
@Autowired
private
OAuth2ClientContext
oauth2ClientContext
;
public
void
configureGlobal
(
AuthenticationManagerBuilder
auth
)
throws
Exception
{
auth
.
authenticationProvider
(
keycloakAuthenticationProvider
());
/**
}
* Enable HBP collab authentication (1) or disable it (0). Default is 1
*/
@Value
(
"#{'${hbp.authentication.enabled:1}'}"
)
private
boolean
authentication
;
/**
* Absolute URL to redirect to when login is required
*/
@Value
(
"#{'${frontend.loginUrl:/login/hbp}'}"
)
private
String
loginUrl
;
/**
* Absolute URL to redirect to after successful login
*/
@Value
(
"#{'${frontend.redirectAfterLoginUrl:http://frontend/home}'}"
)
private
String
frontendRedirectAfterLogin
;
/**
* Absolute URL to redirect to after logout has occurred
*/
@Value
(
"#{'${frontend.redirectAfterLogoutUrl:/login/hbp}'}"
)
private
String
redirectAfterLogoutUrl
;
/**
/**
*
URL to revoke auth token
*
Defines the session authentication strategy.
*/
*/
@Value
(
"#{'${hbp.resource.revokeTokenUri:https://services.humanbrainproject.eu/oidc/revoke}'}"
)
private
String
revokeTokenURI
;
// @Autowired
// private HttpServletRequest request;
@Override
protected
void
configure
(
HttpSecurity
http
)
throws
Exception
{
// @formatter:off
http
.
addFilterBefore
(
new
CORSFilter
(),
ChannelProcessingFilter
.
class
);
if
(
authentication
)
{
http
.
antMatcher
(
"/**"
)
.
authorizeRequests
()
.
antMatchers
(
"/"
,
"/login/**"
,
"/health/**"
,
"/info/**"
,
"/metrics/**"
,
"/trace/**"
,
"/frontend/**"
,
"/webjars/**"
,
"/v2/api-docs"
,
"/swagger-ui.html"
,
"/swagger-resources/**"
).
permitAll
()
.
anyRequest
().
authenticated
()
.
and
().
exceptionHandling
().
authenticationEntryPoint
(
new
CustomLoginUrlAuthenticationEntryPoint
(
loginUrl
))
.
and
().
logout
().
addLogoutHandler
(
new
CustomLogoutHandler
()).
logoutSuccessUrl
(
redirectAfterLogoutUrl
)
.
and
().
logout
().
permitAll
()
.
and
().
csrf
().
ignoringAntMatchers
(
"/logout"
).
csrfTokenRepository
(
csrfTokenRepository
())
.
and
().
addFilterAfter
(
csrfHeaderFilter
(),
CsrfFilter
.
class
)
.
addFilterBefore
(
ssoFilter
(),
BasicAuthenticationFilter
.
class
);
}
else
{
//keycloak
KeycloakConfiguration
.
getKeycloakSecurityContext
();
// http.antMatcher("/**")
// .authorizeRequests()
// .antMatchers("/**").permitAll().and().csrf().disable();
}
}
private
Filter
ssoFilter
()
{
OAuth2ClientAuthenticationProcessingFilter
hbpFilter
=
new
OAuth2ClientAuthenticationProcessingFilter
(
"/login/hbp"
);
OAuth2RestTemplate
hbpTemplate
=
new
OAuth2RestTemplate
(
hbp
(),
oauth2ClientContext
);
hbpFilter
.
setAuthenticationSuccessHandler
(
new
SimpleUrlAuthenticationSuccessHandler
(
frontendRedirectAfterLogin
));
hbpFilter
.
setRestTemplate
(
hbpTemplate
);
hbpFilter
.
setTokenServices
(
new
UserInfoTokenServices
(
hbpResource
().
getUserInfoUri
(),
hbp
().
getClientId
()));
return
hbpFilter
;
}
@Bean
@Bean
public
FilterRegistrationBean
oauth2ClientFilterRegistration
(
@Override
OAuth2ClientContextFilter
filter
)
{
protected
SessionAuthenticationStrategy
sessionAuthenticationStrategy
()
{
FilterRegistrationBean
registration
=
new
FilterRegistrationBean
();
return
new
NullAuthenticatedSessionStrategy
();
registration
.
setFilter
(
filter
);
registration
.
setOrder
(-
100
);
return
registration
;
}
@Bean
(
name
=
"hbp"
)
@ConfigurationProperties
(
"hbp.client"
)
public
OAuth2ProtectedResourceDetails
hbp
()
{
return
new
AuthorizationCodeResourceDetails
();
}
@Bean
(
name
=
"hbpResource"
)
@ConfigurationProperties
(
"hbp.resource"
)
public
ResourceServerProperties
hbpResource
()
{
return
new
ResourceServerProperties
();
}
public
boolean
isAuthentication
()
{
return
authentication
;
}
public
String
getFrontendRedirectAfterLogin
()
{
return
frontendRedirectAfterLogin
;
}
private
Filter
csrfHeaderFilter
()
{
return
new
OncePerRequestFilter
()
{
@Override
protected
void
doFilterInternal
(
HttpServletRequest
request
,
HttpServletResponse
response
,
FilterChain
filterChain
)
throws
ServletException
,
IOException
{
CsrfToken
csrf
=
(
CsrfToken
)
request
.
getAttribute
(
CsrfToken
.
class
.
getName
());
if
(
csrf
!=
null
)
{
Cookie
cookie
=
WebUtils
.
getCookie
(
request
,
"XSRF-TOKEN"
);
String
token
=
csrf
.
getToken
();
if
(
cookie
==
null
||
token
!=
null
&&
!
token
.
equals
(
cookie
.
getValue
()))
{
cookie
=
new
Cookie
(
"XSRF-TOKEN"
,
token
);
cookie
.
setPath
(
"/"
);
response
.
addCookie
(
cookie
);
}
}
filterChain
.
doFilter
(
request
,
response
);
}
};
}
}
private
CsrfTokenRepository
csrfTokenRepository
()
{
@Override
HttpSessionCsrfTokenRepository
repository
=
new
HttpSessionCsrfTokenRepository
();
protected
void
configure
(
HttpSecurity
http
)
throws
Exception
repository
.
setHeaderName
(
"X-XSRF-TOKEN"
);
{
return
repository
;
super
.
configure
(
http
);
http
.
authorizeRequests
()
.
antMatchers
(
"/user*"
).
authenticated
()
.
antMatchers
(
"/public1*"
).
hasAuthority
(
"public13"
)
.
antMatchers
(
"/public2*"
).
hasAuthority
(
"public2"
)
.
antMatchers
(
"/public3*"
).
hasAuthority
(
"public3"
)
.
antMatchers
(
"/admin*"
).
authenticated
()
.
anyRequest
().
permitAll
()
.
and
()
.
logout
()
.
addLogoutHandler
(
keycloakLogoutHandler
())
//.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.
logoutUrl
(
"/logout"
).
permitAll
()
.
logoutSuccessUrl
(
"/"
);
// .anyRequest().permitAll().and().logout().addLogoutHandler(new KeycloakLogoutHandler(new RestTemplate())).logoutRequestMatcher(new AntPathRequestMatcher("/logout"));
;
}
}
private
class
CustomLogoutHandler
implements
LogoutHandler
{
@Override
public
void
logout
(
HttpServletRequest
httpServletRequest
,
HttpServletResponse
httpServletResponse
,
Authentication
authentication
)
{
// Hackish way of accessing to this information...
final
UserInfo
userInfo
=
(
UserInfo
)
httpServletRequest
.
getSession
().
getAttribute
(
"userInfo"
);
if
(
userInfo
!=
null
)
{
userInfo
.
setFakeAuth
(
false
);
}
if
(
oauth2ClientContext
==
null
||
oauth2ClientContext
.
getAccessToken
()
==
null
)
{
return
;
}
String
idToken
=
oauth2ClientContext
.
getAccessToken
().
getAdditionalInformation
().
get
(
"id_token"
).
toString
();
StringBuilder
query
=
new
StringBuilder
();
query
.
append
(
"{"
);
query
.
append
(
"\"token\":"
);
query
.
append
(
"\""
).
append
(
idToken
).
append
(
"\""
);
query
.
append
(
"}"
);
try
{
int
responseCode
=
HTTPUtil
.
sendPost
(
revokeTokenURI
,
query
.
toString
(),
new
StringBuilder
());
if
(
responseCode
!=
200
)
{
LOGGER
.
warn
(
"Cannot send request to OIDC server for revocation ! "
);
}
else
{
LOGGER
.
info
(
"Should be logged out"
);
}
}
catch
(
IOException
e
)
{
LOGGER
.
warn
(
"Cannot notify logout to OIDC server !"
);
LOGGER
.
trace
(
"Cannot notify logout"
,
e
);
}
}
}
}
}
//@Configuration
//@EnableOAuth2Client
//public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(SecurityConfiguration.class);
//
// @Autowired
// private OAuth2ClientContext oauth2ClientContext;
//
// /**
// * Enable HBP collab authentication (1) or disable it (0). Default is 1
// */
// @Value("#{'${hbp.authentication.enabled:1}'}")
// private boolean authentication;
//
// /**
// * Absolute URL to redirect to when login is required
// */
// @Value("#{'${frontend.loginUrl:/login/hbp}'}")
// private String loginUrl;
//
// /**
// * Absolute URL to redirect to after successful login
// */
// @Value("#{'${frontend.redirectAfterLoginUrl:http://frontend/home}'}")
// private String frontendRedirectAfterLogin;
//
// /**
// * Absolute URL to redirect to after logout has occurred
// */
// @Value("#{'${frontend.redirectAfterLogoutUrl:/login/hbp}'}")
// private String redirectAfterLogoutUrl;
//
// /**
// * URL to revoke auth token
// */
// @Value("#{'${hbp.resource.revokeTokenUri:https://services.humanbrainproject.eu/oidc/revoke}'}")
// private String revokeTokenURI;
//
//// @Autowired
//// private HttpServletRequest request;
//
// @Override
// protected void configure(HttpSecurity http) throws Exception {
// // @formatter:off
// http.addFilterBefore(new CORSFilter(), ChannelProcessingFilter.class);
//
// if (authentication) {
// http.antMatcher("/**")
// .authorizeRequests()
// .antMatchers(
// "/", "/login/**", "/health/**", "/info/**", "/metrics/**", "/trace/**", "/frontend/**", "/webjars/**", "/v2/api-docs", "/swagger-ui.html", "/swagger-resources/**"
// ).permitAll()
// .anyRequest().authenticated()
// .and().exceptionHandling().authenticationEntryPoint(new CustomLoginUrlAuthenticationEntryPoint(loginUrl))
// .and().logout().addLogoutHandler(new CustomLogoutHandler()).logoutSuccessUrl(redirectAfterLogoutUrl)
// .and().logout().permitAll()
// .and().csrf().ignoringAntMatchers("/logout").csrfTokenRepository(csrfTokenRepository())
// .and().addFilterAfter(csrfHeaderFilter(), CsrfFilter.class)
// .addFilterBefore(ssoFilter(), BasicAuthenticationFilter.class);
// }
// else {
// //keycloak
// //KeycloakConfiguration.getKeycloakSecurityContext();
//// http.antMatcher("/**")
//// .authorizeRequests()
//// .antMatchers("/**").permitAll().and().csrf().disable();
// }
// }
//
// private Filter ssoFilter() {
// OAuth2ClientAuthenticationProcessingFilter hbpFilter = new OAuth2ClientAuthenticationProcessingFilter("/login/hbp");
// OAuth2RestTemplate hbpTemplate = new OAuth2RestTemplate(hbp(), oauth2ClientContext);
// hbpFilter.setAuthenticationSuccessHandler(new SimpleUrlAuthenticationSuccessHandler(frontendRedirectAfterLogin));
// hbpFilter.setRestTemplate(hbpTemplate);
// hbpFilter.setTokenServices(new UserInfoTokenServices(hbpResource().getUserInfoUri(), hbp().getClientId()));
// return hbpFilter;
// }
//
// @Bean
// public FilterRegistrationBean oauth2ClientFilterRegistration(
// OAuth2ClientContextFilter filter) {
// FilterRegistrationBean registration = new FilterRegistrationBean();
// registration.setFilter(filter);
// registration.setOrder(-100);
// return registration;
// }
//
// @Bean(name="hbp")
// @ConfigurationProperties("hbp.client")
// public OAuth2ProtectedResourceDetails hbp() {
// return new AuthorizationCodeResourceDetails();
// }
//
// @Bean(name="hbpResource")
// @ConfigurationProperties("hbp.resource")
// public ResourceServerProperties hbpResource() {
// return new ResourceServerProperties();
// }
//
// public boolean isAuthentication() {
// return authentication;
// }
//
// public String getFrontendRedirectAfterLogin() {
// return frontendRedirectAfterLogin;
// }
//
// private Filter csrfHeaderFilter() {
// return new OncePerRequestFilter() {
// @Override
// protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
// FilterChain filterChain) throws ServletException, IOException {
// CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
// if (csrf != null) {
// Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
// String token = csrf.getToken();
// if (cookie == null || token != null && !token.equals(cookie.getValue())) {
// cookie = new Cookie("XSRF-TOKEN", token);
// cookie.setPath("/");
// response.addCookie(cookie);
// }
// }
// filterChain.doFilter(request, response);
// }
// };
// }
//
// private CsrfTokenRepository csrfTokenRepository() {
// HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
// repository.setHeaderName("X-XSRF-TOKEN");
// return repository;
// }
//
// private class CustomLogoutHandler implements LogoutHandler {
// @Override
// public void logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) {
//
// // Hackish way of accessing to this information...
// final UserInfo userInfo = (UserInfo) httpServletRequest.getSession().getAttribute("userInfo");
// if (userInfo != null) {
// userInfo.setFakeAuth(false);
// }
//
// if (oauth2ClientContext == null || oauth2ClientContext.getAccessToken() == null)
// {
// return;
// }
//
// String idToken = oauth2ClientContext.getAccessToken().getAdditionalInformation().get("id_token").toString();
//
// StringBuilder query = new StringBuilder();
// query.append("{");
// query.append("\"token\":");
// query.append("\"").append(idToken).append("\"");
// query.append("}");
//
// try {
// int responseCode = HTTPUtil.sendPost(revokeTokenURI, query.toString(), new StringBuilder());
// if (responseCode != 200)
// {
// LOGGER.warn("Cannot send request to OIDC server for revocation ! ");
// }
// else{
// LOGGER.info("Should be logged out");
// }
// } catch (IOException e) {
// LOGGER.warn("Cannot notify logout to OIDC server !");
// LOGGER.trace("Cannot notify logout", e);
// }
//
// }
// }
//}
This diff is collapsed.
Click to expand it.
Preview
0%
Try again
or
attach a new file
.
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Save comment
Cancel
Please
register
or
sign in
to comment