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

[Fix] Websockets authentication #291

Merged
merged 10 commits into from
Sep 4, 2024
Merged
Show file tree
Hide file tree
Changes from 9 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
37 changes: 31 additions & 6 deletions doc/setup.md
Original file line number Diff line number Diff line change
Expand Up @@ -172,10 +172,35 @@ termit:

TermIt can operate in two authentication modes:

1. Internal authentication means
2. [Keycloak](https://www.keycloak.org/) -based
1. Internal authentication
2. OAuth2 based (e.g. [Keycloak](https://www.keycloak.org/))

By default, OAuth2 is disabled and internal authentication is used
To enable it, set termit security provider to `oidc`
and provide issuer-uri and jwk-set-uri.

**`application.yml` example:**
```yml
spring:
security:
oauth2:
resourceserver:
jwt:
issuer-uri: http://keycloak.lan/realms/termit
jwk-set-uri: http://keycloak.lan/realms/termit/protocol/openid-connect/certs
termit:
security:
provider: "oidc"
```

**Environmental variables example:**
```
SPRING_SECURITY_OAUTH2_RESOURCESERVER_JWT_ISSUERURI=http://keycloak.lan/realms/termit
SPRING_SECURITY_OAUTH2_RESOURCESERVER_JWT_JWKSETURI=http://keycloak.lan/realms/termit/protocol/openid-connect/certs
TERMIT_SECURITY_PROVIDER=oidc
```

TermIt will automatically configure its security accordingly
(it is using Spring's [`ConditionalOnProperty`](https://www.baeldung.com/spring-conditionalonproperty)).

By default, Keycloak is disabled (see `keycloak.enabled` in `application.yml`). To enable it, set `keycloak.enabled` to `true` and
provide additional required Keycloak parameters - see the [Keycloak Spring Boot integration docs](https://www.keycloak.org/docs/latest/securing_apps/#_spring_boot_adapter).
TermIt will automatically configure its security (it is using Spring's [`ConditionalOnProperty`](https://www.baeldung.com/spring-conditionalonproperty))
accordingly.
**Note that termit-ui needs to be configured for mathcing authentication mode.**
56 changes: 13 additions & 43 deletions src/main/java/cz/cvut/kbss/termit/config/OAuth2SecurityConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,39 +19,29 @@

import cz.cvut.kbss.termit.security.AuthenticationSuccess;
import cz.cvut.kbss.termit.security.HierarchicalRoleBasedAuthorityMapper;
import cz.cvut.kbss.termit.security.JwtUtils;
import cz.cvut.kbss.termit.security.SecurityConstants;
import cz.cvut.kbss.termit.security.WebSocketJwtAuthorizationInterceptor;
import cz.cvut.kbss.termit.service.security.TermItUserDetailsService;
import cz.cvut.kbss.termit.util.oidc.OidcGrantedAuthoritiesExtractor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.core.convert.converter.Converter;
import org.springframework.messaging.Message;
import org.springframework.messaging.simp.SimpMessageType;
import org.springframework.messaging.simp.annotation.support.SimpAnnotationMethodMessageHandler;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authorization.AuthorizationManager;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.annotation.web.socket.EnableWebSocketSecurity;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.messaging.access.intercept.MessageMatcherDelegatingAuthorizationManager;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationProvider;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.session.RegisterSessionAuthenticationStrategy;
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.cors.CorsConfigurationSource;

import java.util.Collection;
Expand Down Expand Up @@ -96,6 +86,17 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http.build();
}

/**
* Supplies auth provider which is not exposed by HttpSecurity
* @see cz.cvut.kbss.termit.security.WebSocketJwtAuthorizationInterceptor
*/
@Bean
public JwtAuthenticationProvider jwtAuthenticationProvider(JwtDecoder jwtDecoder) {
final JwtAuthenticationProvider provider = new JwtAuthenticationProvider(jwtDecoder);
provider.setJwtAuthenticationConverter(grantedAuthoritiesExtractor());
return provider;
}

private CorsConfigurationSource corsConfigurationSource() {
return SecurityConfig.createCorsConfiguration(config.getCors());
}
Expand All @@ -108,35 +109,4 @@ private Converter<Jwt, AbstractAuthenticationToken> grantedAuthoritiesExtractor(
new HierarchicalRoleBasedAuthorityMapper().mapAuthorities(authorities));
};
}

/**
* Part of {@link EnableWebSocketSecurity @EnableWebSocketSecurity} replacement
*
* @see WebSocketConfig
*/
@Bean
@Scope("prototype")
public MessageMatcherDelegatingAuthorizationManager.Builder messageAuthorizationManagerBuilder(
ApplicationContext context) {
return MessageMatcherDelegatingAuthorizationManager.builder().simpDestPathMatcher(
() -> (context.getBeanNamesForType(SimpAnnotationMethodMessageHandler.class).length > 0)
? context.getBean(SimpAnnotationMethodMessageHandler.class).getPathMatcher()
: new AntPathMatcher());
}

/**
* WebSocket endpoint authorization
*/
@Bean
public AuthorizationManager<Message<?>> messageAuthorizationManager(
MessageMatcherDelegatingAuthorizationManager.Builder messages) {
return messages.simpTypeMatchers(SimpMessageType.DISCONNECT).permitAll()
.anyMessage().authenticated().build();
}

@Bean
public WebSocketJwtAuthorizationInterceptor webSocketJwtAuthorizationInterceptor(JwtUtils jwtUtils,
TermItUserDetailsService userDetailsService) {
return new WebSocketJwtAuthorizationInterceptor(jwtUtils, userDetailsService);
}
}
63 changes: 25 additions & 38 deletions src/main/java/cz/cvut/kbss/termit/config/SecurityConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,36 +23,31 @@
import cz.cvut.kbss.termit.security.JwtAuthorizationFilter;
import cz.cvut.kbss.termit.security.JwtUtils;
import cz.cvut.kbss.termit.security.SecurityConstants;
import cz.cvut.kbss.termit.security.WebSocketJwtAuthorizationInterceptor;
import cz.cvut.kbss.termit.security.TermitJwtDecoder;
import cz.cvut.kbss.termit.service.security.TermItUserDetailsService;
import cz.cvut.kbss.termit.util.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.messaging.Message;
import org.springframework.messaging.simp.SimpMessageType;
import org.springframework.messaging.simp.annotation.support.SimpAnnotationMethodMessageHandler;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authorization.AuthorizationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.annotation.web.socket.EnableWebSocketSecurity;
import org.springframework.security.messaging.access.intercept.MessageMatcherDelegatingAuthorizationManager;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationProvider;
import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.HttpStatusEntryPoint;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
Expand Down Expand Up @@ -100,7 +95,7 @@ public SecurityConfig(AuthenticationProvider authenticationProvider,
}

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
public SecurityFilterChain filterChain(HttpSecurity http, TermitJwtDecoder jwtDecoder) throws Exception {
LOG.debug("Using internal security mechanisms.");
final AuthenticationManager authManager = buildAuthenticationManager(http);
http.authorizeHttpRequests((auth) -> auth.requestMatchers(antMatcher("/rest/query")).permitAll()
Expand All @@ -112,7 +107,7 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
.logoutSuccessHandler(authenticationSuccessHandler))
.authenticationManager(authManager)
.addFilter(authenticationFilter(authManager))
.addFilter(new JwtAuthorizationFilter(authManager, jwtUtils, userDetailsService, objectMapper));
.addFilter(new JwtAuthorizationFilter(authManager, jwtUtils, objectMapper, jwtDecoder));
return http.build();
}

Expand All @@ -131,6 +126,22 @@ private JwtAuthenticationFilter authenticationFilter(AuthenticationManager authe
return authenticationFilter;
}

/**
* @see cz.cvut.kbss.termit.security.WebSocketJwtAuthorizationInterceptor
*/
@Bean
public JwtAuthenticationProvider jwtAuthenticationProvider(JwtDecoder jwtDecoder) {
final JwtGrantedAuthoritiesConverter authoritiesConverter = new JwtGrantedAuthoritiesConverter();
authoritiesConverter.setAuthorityPrefix(""); // this removes default "SCOPE_" prefix
// otherwise, all granted authorities would have this prefix
// (like "SCOPE_ROLE_RESTRICTED_USER", we want just ROLE_...)
final JwtAuthenticationConverter converter = new JwtAuthenticationConverter();
converter.setJwtGrantedAuthoritiesConverter(authoritiesConverter);
final JwtAuthenticationProvider provider = new JwtAuthenticationProvider(jwtDecoder);
provider.setJwtAuthenticationConverter(converter);
return provider;
}

private CorsConfigurationSource corsConfigurationSource() {
return createCorsConfiguration(config.getCors());
}
Expand All @@ -154,32 +165,8 @@ protected static CorsConfigurationSource createCorsConfiguration(
return source;
}

/**
* Part of {@link EnableWebSocketSecurity @EnableWebSocketSecurity} replacement
* @see WebSocketConfig
*/
@Bean
@Scope("prototype")
public MessageMatcherDelegatingAuthorizationManager.Builder messageAuthorizationManagerBuilder(
ApplicationContext context) {
return MessageMatcherDelegatingAuthorizationManager.builder().simpDestPathMatcher(
() -> (context.getBeanNamesForType(SimpAnnotationMethodMessageHandler.class).length > 0)
? context.getBean(SimpAnnotationMethodMessageHandler.class).getPathMatcher()
: new AntPathMatcher());
}

/**
* WebSocket endpoint authorization
*/
@Bean
public AuthorizationManager<Message<?>> messageAuthorizationManager(
MessageMatcherDelegatingAuthorizationManager.Builder messages) {
return messages.simpTypeMatchers(SimpMessageType.DISCONNECT).permitAll()
.anyMessage().authenticated().build();
}

@Bean
public WebSocketJwtAuthorizationInterceptor webSocketJwtAuthorizationInterceptor() {
return new WebSocketJwtAuthorizationInterceptor(jwtUtils, userDetailsService);
public TermitJwtDecoder jwtDecoder() {
return new TermitJwtDecoder(jwtUtils, userDetailsService);
}
}
Loading