Search in sources :

Example 1 with ExpressionUrlAuthorizationConfigurer

use of org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer in project molgenis by molgenis.

the class MolgenisWebAppSecurityConfig method configure.

@Override
protected void configure(HttpSecurity http) throws Exception {
    // do not write cache control headers for static resources
    RequestMatcher matcher = new NegatedRequestMatcher(new OrRequestMatcher(new AntPathRequestMatcher(PATTERN_CSS), new AntPathRequestMatcher(PATTERN_JS), new AntPathRequestMatcher(PATTERN_IMG), new AntPathRequestMatcher(PATTERN_FONTS)));
    DelegatingRequestMatcherHeaderWriter cacheControlHeaderWriter = new DelegatingRequestMatcherHeaderWriter(matcher, new CacheControlHeadersWriter());
    http.sessionManagement().invalidSessionStrategy(invalidSessionStrategy());
    // add default header options but use custom cache control header writer
    http.headers().contentTypeOptions().and().xssProtection().and().httpStrictTransportSecurity().and().frameOptions().and().addHeaderWriter(cacheControlHeaderWriter);
    http.addFilterBefore(anonymousAuthFilter(), AnonymousAuthenticationFilter.class);
    http.authenticationProvider(anonymousAuthenticationProvider());
    http.authenticationProvider(tokenAuthenticationProvider());
    http.authenticationProvider(runAsAuthenticationProvider());
    http.addFilterBefore(tokenAuthenticationFilter(), AnonymousAuthenticationFilter.class);
    http.addFilterBefore(googleAuthenticationProcessingFilter(), TokenAuthenticationFilter.class);
    http.addFilterAfter(changePasswordFilter(), SwitchUserFilter.class);
    http.addFilterAfter(twoFactorAuthenticationFilter(), MolgenisChangePasswordFilter.class);
    http.authenticationProvider(twoFactorAuthenticationProvider());
    http.authenticationProvider(recoveryAuthenticationProvider());
    ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry expressionInterceptUrlRegistry = http.authorizeRequests();
    configureUrlAuthorization(expressionInterceptUrlRegistry);
    expressionInterceptUrlRegistry.antMatchers(MolgenisLoginController.URI).permitAll().antMatchers(TwoFactorAuthenticationController.URI + "/**").permitAll().antMatchers(GOOGLE_AUTHENTICATION_URL).permitAll().antMatchers("/beacon/**").permitAll().antMatchers("/logo/**").permitAll().antMatchers("/molgenis.py").permitAll().antMatchers("/molgenis.R").permitAll().antMatchers(AccountController.CHANGE_PASSWORD_URI).authenticated().antMatchers("/account/**").permitAll().antMatchers(PATTERN_SWAGGER).permitAll().antMatchers(PATTERN_CSS).permitAll().antMatchers(PATTERN_IMG).permitAll().antMatchers(PATTERN_JS).permitAll().antMatchers(PATTERN_FONTS).permitAll().antMatchers("/html/**").permitAll().antMatchers("/plugin/void/**").permitAll().antMatchers("/api/**").permitAll().antMatchers("/webjars/**").permitAll().antMatchers("/search").permitAll().antMatchers("/captcha").permitAll().antMatchers("/dataindexerstatus").authenticated().antMatchers("/permission/**/read/**").permitAll().antMatchers("/permission/**/write/**").permitAll().antMatchers("/scripts/**/run").authenticated().antMatchers("/scripts/**/start").authenticated().antMatchers("/files/**").permitAll().antMatchers('/' + PATH_SEGMENT_APPS + "/**").permitAll().anyRequest().denyAll().and().httpBasic().authenticationEntryPoint(authenticationEntryPoint()).and().formLogin().loginPage(MolgenisLoginController.URI).failureUrl(MolgenisLoginController.URI + "?error").and().logout().deleteCookies("JSESSIONID").addLogoutHandler((req, res, auth) -> {
        if (req.getSession(false) != null && req.getSession().getAttribute("continueWithUnsupportedBrowser") != null) {
            req.setAttribute("continueWithUnsupportedBrowser", true);
        }
    }).logoutSuccessHandler((req, res, auth) -> {
        StringBuilder logoutSuccessUrl = new StringBuilder("/");
        if (req.getAttribute("continueWithUnsupportedBrowser") != null) {
            logoutSuccessUrl.append("?continueWithUnsupportedBrowser=true");
        }
        SimpleUrlLogoutSuccessHandler logoutSuccessHandler = new SimpleUrlLogoutSuccessHandler();
        logoutSuccessHandler.setDefaultTargetUrl(logoutSuccessUrl.toString());
        logoutSuccessHandler.onLogoutSuccess(req, res, auth);
    }).and().csrf().disable();
}
Also used : NegatedRequestMatcher(org.springframework.security.web.util.matcher.NegatedRequestMatcher) BCryptPasswordEncoder(org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder) Autowired(org.springframework.beans.factory.annotation.Autowired) AuthenticationProvider(org.springframework.security.authentication.AuthenticationProvider) HttpSecurity(org.springframework.security.config.annotation.web.builders.HttpSecurity) UserDetailsChecker(org.springframework.security.core.userdetails.UserDetailsChecker) AuthenticationSettings(org.molgenis.security.settings.AuthenticationSettings) GooglePublicKeysManager(com.google.api.client.googleapis.auth.oauth2.GooglePublicKeysManager) org.molgenis.security.twofactor.auth(org.molgenis.security.twofactor.auth) WebSecurityConfigurerAdapter(org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter) DataServiceTokenService(org.molgenis.security.token.DataServiceTokenService) RunAsImplAuthenticationProvider(org.springframework.security.access.intercept.RunAsImplAuthenticationProvider) TwoFactorAuthenticationService(org.molgenis.security.twofactor.service.TwoFactorAuthenticationService) OtpService(org.molgenis.security.twofactor.service.OtpService) Filter(javax.servlet.Filter) MolgenisLoginController(org.molgenis.security.login.MolgenisLoginController) MolgenisUserDetailsChecker(org.molgenis.security.user.MolgenisUserDetailsChecker) GoogleAuthenticationProcessingFilter(org.molgenis.security.google.GoogleAuthenticationProcessingFilter) DelegatingRequestMatcherHeaderWriter(org.springframework.security.web.header.writers.DelegatingRequestMatcherHeaderWriter) UserFactory(org.molgenis.data.security.auth.UserFactory) HttpSessionEventPublisher(org.springframework.security.web.session.HttpSessionEventPublisher) UserDetailsService(org.molgenis.security.user.UserDetailsService) ExpressionUrlAuthorizationConfigurer(org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer) JacksonFactory(com.google.api.client.json.jackson2.JacksonFactory) TokenAuthenticationProvider(org.molgenis.security.token.TokenAuthenticationProvider) HttpTransport(com.google.api.client.http.HttpTransport) UserAccountService(org.molgenis.security.user.UserAccountService) RequestMatcher(org.springframework.security.web.util.matcher.RequestMatcher) OrRequestMatcher(org.springframework.security.web.util.matcher.OrRequestMatcher) PATH_SEGMENT_APPS(org.molgenis.security.UriConstants.PATH_SEGMENT_APPS) TokenFactory(org.molgenis.data.security.auth.TokenFactory) RoleHierarchyVoter(org.springframework.security.access.vote.RoleHierarchyVoter) GroupMemberFactory(org.molgenis.data.security.auth.GroupMemberFactory) TokenGenerator(org.molgenis.security.token.TokenGenerator) RoleHierarchyAuthoritiesMapper(org.springframework.security.access.hierarchicalroles.RoleHierarchyAuthoritiesMapper) LoginUrlAuthenticationEntryPoint(org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint) RoleVoter(org.springframework.security.access.vote.RoleVoter) DefaultRedirectStrategy(org.springframework.security.web.DefaultRedirectStrategy) NegatedRequestMatcher(org.springframework.security.web.util.matcher.NegatedRequestMatcher) UserService(org.molgenis.data.security.user.UserService) TwoFactorAuthenticationController(org.molgenis.security.twofactor.TwoFactorAuthenticationController) RedirectStrategy(org.springframework.security.web.RedirectStrategy) AuthenticationManagerBuilder(org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder) ResourcePathPatterns(org.molgenis.core.framework.ui.ResourcePathPatterns) AccountController(org.molgenis.security.account.AccountController) TokenAuthenticationFilter(org.molgenis.security.token.TokenAuthenticationFilter) CacheControlHeadersWriter(org.springframework.security.web.header.writers.CacheControlHeadersWriter) SwitchUserFilter(org.springframework.security.web.authentication.switchuser.SwitchUserFilter) NetHttpTransport(com.google.api.client.http.javanet.NetHttpTransport) AnonymousAuthenticationFilter(org.springframework.security.web.authentication.AnonymousAuthenticationFilter) AuthenticationManager(org.springframework.security.authentication.AuthenticationManager) InvalidSessionStrategy(org.springframework.security.web.session.InvalidSessionStrategy) WebSecurity(org.springframework.security.config.annotation.web.builders.WebSecurity) SimpleUrlLogoutSuccessHandler(org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler) RecoveryService(org.molgenis.security.twofactor.service.RecoveryService) SecurityUtils(org.molgenis.security.core.utils.SecurityUtils) DaoAuthenticationProvider(org.springframework.security.authentication.dao.DaoAuthenticationProvider) GrantedAuthoritiesMapper(org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper) PasswordEncoder(org.springframework.security.crypto.password.PasswordEncoder) MolgenisPasswordEncoder(org.molgenis.security.core.MolgenisPasswordEncoder) JsonFactory(com.google.api.client.json.JsonFactory) AnonymousAuthenticationProvider(org.springframework.security.authentication.AnonymousAuthenticationProvider) TokenService(org.molgenis.security.core.token.TokenService) DataService(org.molgenis.data.DataService) Bean(org.springframework.context.annotation.Bean) RoleHierarchy(org.springframework.security.access.hierarchicalroles.RoleHierarchy) AuthorityUtils(org.springframework.security.core.authority.AuthorityUtils) GOOGLE_AUTHENTICATION_URL(org.molgenis.security.google.GoogleAuthenticationProcessingFilter.GOOGLE_AUTHENTICATION_URL) AntPathRequestMatcher(org.springframework.security.web.util.matcher.AntPathRequestMatcher) RequestMatcher(org.springframework.security.web.util.matcher.RequestMatcher) OrRequestMatcher(org.springframework.security.web.util.matcher.OrRequestMatcher) NegatedRequestMatcher(org.springframework.security.web.util.matcher.NegatedRequestMatcher) AntPathRequestMatcher(org.springframework.security.web.util.matcher.AntPathRequestMatcher) DelegatingRequestMatcherHeaderWriter(org.springframework.security.web.header.writers.DelegatingRequestMatcherHeaderWriter) ExpressionUrlAuthorizationConfigurer(org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer) CacheControlHeadersWriter(org.springframework.security.web.header.writers.CacheControlHeadersWriter) AntPathRequestMatcher(org.springframework.security.web.util.matcher.AntPathRequestMatcher) SimpleUrlLogoutSuccessHandler(org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler) OrRequestMatcher(org.springframework.security.web.util.matcher.OrRequestMatcher)

Example 2 with ExpressionUrlAuthorizationConfigurer

use of org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer in project cas by apereo.

the class CasWebSecurityConfigurerAdapter method configureEndpointAccessToDenyUndefined.

/**
 * Configure endpoint access to deny undefined.
 *
 * @param http     the http
 * @param requests the requests
 */
protected void configureEndpointAccessToDenyUndefined(final HttpSecurity http, final ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry requests) {
    val endpoints = casProperties.getMonitor().getEndpoints().getEndpoint().keySet();
    val endpointDefaults = casProperties.getMonitor().getEndpoints().getDefaultEndpointProperties();
    pathMappedEndpoints.getObject().forEach(endpoint -> {
        val rootPath = endpoint.getRootPath();
        if (endpoints.contains(rootPath)) {
            LOGGER.trace("Endpoint security is defined for endpoint [{}]", rootPath);
        } else {
            val defaultAccessRules = endpointDefaults.getAccess();
            LOGGER.trace("Endpoint security is NOT defined for endpoint [{}]. Using default security rules [{}]", rootPath, endpointDefaults);
            val endpointRequest = EndpointRequest.to(rootPath).excludingLinks();
            defaultAccessRules.forEach(Unchecked.consumer(access -> configureEndpointAccess(http, requests, access, endpointDefaults, endpointRequest)));
        }
    });
}
Also used : lombok.val(lombok.val) CasConfigurationProperties(org.apereo.cas.configuration.CasConfigurationProperties) JaasSecurityActuatorEndpointsMonitorProperties(org.apereo.cas.configuration.model.core.monitor.JaasSecurityActuatorEndpointsMonitorProperties) EndpointLdapAuthenticationProvider(org.apereo.cas.web.security.authentication.EndpointLdapAuthenticationProvider) SneakyThrows(lombok.SneakyThrows) RequiredArgsConstructor(lombok.RequiredArgsConstructor) ArrayUtils(org.apache.commons.lang3.ArrayUtils) HttpSecurity(org.springframework.security.config.annotation.web.builders.HttpSecurity) StringUtils(org.apache.commons.lang3.StringUtils) BeanSupplier(org.apereo.cas.util.spring.beans.BeanSupplier) WebSecurityConfigurerAdapter(org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter) ObjectProvider(org.springframework.beans.factory.ObjectProvider) AuthenticationManagerBuilder(org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder) ProtocolEndpointWebSecurityConfigurer(org.apereo.cas.web.ProtocolEndpointWebSecurityConfigurer) JaasAuthenticationProvider(org.springframework.security.authentication.jaas.JaasAuthenticationProvider) SecurityExpressionHandler(org.springframework.security.access.expression.SecurityExpressionHandler) SecurityProperties(org.springframework.boot.autoconfigure.security.SecurityProperties) Order(org.springframework.core.annotation.Order) PathRequest(org.springframework.boot.autoconfigure.security.servlet.PathRequest) Unchecked(org.jooq.lambda.Unchecked) ExpressionUrlAuthorizationConfigurer(org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer) lombok.val(lombok.val) EndpointRequest(org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest) Collectors(java.util.stream.Collectors) LdapSecurityActuatorEndpointsMonitorProperties(org.apereo.cas.configuration.model.core.monitor.LdapSecurityActuatorEndpointsMonitorProperties) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) CasWebSecurityConstants(org.apereo.cas.web.CasWebSecurityConstants) ActuatorEndpointProperties(org.apereo.cas.configuration.model.core.monitor.ActuatorEndpointProperties) DisposableBean(org.springframework.beans.factory.DisposableBean) FilterInvocation(org.springframework.security.web.FilterInvocation) PathMappedEndpoints(org.springframework.boot.actuate.endpoint.web.PathMappedEndpoints) LdapUtils(org.apereo.cas.util.LdapUtils)

Example 3 with ExpressionUrlAuthorizationConfigurer

use of org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer in project cas by apereo.

the class CasWebSecurityConfigurerAdapter method configureEndpointAccessByIpAddress.

private void configureEndpointAccessByIpAddress(final ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry requests, final ActuatorEndpointProperties properties, final EndpointRequest.EndpointRequestMatcher endpoint) {
    val addresses = properties.getRequiredIpAddresses().stream().map(address -> "hasIpAddress('" + address + "')").collect(Collectors.joining(" or "));
    requests.requestMatchers(endpoint).access(addresses);
}
Also used : lombok.val(lombok.val) CasConfigurationProperties(org.apereo.cas.configuration.CasConfigurationProperties) JaasSecurityActuatorEndpointsMonitorProperties(org.apereo.cas.configuration.model.core.monitor.JaasSecurityActuatorEndpointsMonitorProperties) EndpointLdapAuthenticationProvider(org.apereo.cas.web.security.authentication.EndpointLdapAuthenticationProvider) SneakyThrows(lombok.SneakyThrows) RequiredArgsConstructor(lombok.RequiredArgsConstructor) ArrayUtils(org.apache.commons.lang3.ArrayUtils) HttpSecurity(org.springframework.security.config.annotation.web.builders.HttpSecurity) StringUtils(org.apache.commons.lang3.StringUtils) BeanSupplier(org.apereo.cas.util.spring.beans.BeanSupplier) WebSecurityConfigurerAdapter(org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter) ObjectProvider(org.springframework.beans.factory.ObjectProvider) AuthenticationManagerBuilder(org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder) ProtocolEndpointWebSecurityConfigurer(org.apereo.cas.web.ProtocolEndpointWebSecurityConfigurer) JaasAuthenticationProvider(org.springframework.security.authentication.jaas.JaasAuthenticationProvider) SecurityExpressionHandler(org.springframework.security.access.expression.SecurityExpressionHandler) SecurityProperties(org.springframework.boot.autoconfigure.security.SecurityProperties) Order(org.springframework.core.annotation.Order) PathRequest(org.springframework.boot.autoconfigure.security.servlet.PathRequest) Unchecked(org.jooq.lambda.Unchecked) ExpressionUrlAuthorizationConfigurer(org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer) lombok.val(lombok.val) EndpointRequest(org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest) Collectors(java.util.stream.Collectors) LdapSecurityActuatorEndpointsMonitorProperties(org.apereo.cas.configuration.model.core.monitor.LdapSecurityActuatorEndpointsMonitorProperties) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) CasWebSecurityConstants(org.apereo.cas.web.CasWebSecurityConstants) ActuatorEndpointProperties(org.apereo.cas.configuration.model.core.monitor.ActuatorEndpointProperties) DisposableBean(org.springframework.beans.factory.DisposableBean) FilterInvocation(org.springframework.security.web.FilterInvocation) PathMappedEndpoints(org.springframework.boot.actuate.endpoint.web.PathMappedEndpoints) LdapUtils(org.apereo.cas.util.LdapUtils)

Aggregations

List (java.util.List)2 Collectors (java.util.stream.Collectors)2 RequiredArgsConstructor (lombok.RequiredArgsConstructor)2 SneakyThrows (lombok.SneakyThrows)2 Slf4j (lombok.extern.slf4j.Slf4j)2 lombok.val (lombok.val)2 ArrayUtils (org.apache.commons.lang3.ArrayUtils)2 StringUtils (org.apache.commons.lang3.StringUtils)2 CasConfigurationProperties (org.apereo.cas.configuration.CasConfigurationProperties)2 ActuatorEndpointProperties (org.apereo.cas.configuration.model.core.monitor.ActuatorEndpointProperties)2 JaasSecurityActuatorEndpointsMonitorProperties (org.apereo.cas.configuration.model.core.monitor.JaasSecurityActuatorEndpointsMonitorProperties)2 LdapSecurityActuatorEndpointsMonitorProperties (org.apereo.cas.configuration.model.core.monitor.LdapSecurityActuatorEndpointsMonitorProperties)2 LdapUtils (org.apereo.cas.util.LdapUtils)2 BeanSupplier (org.apereo.cas.util.spring.beans.BeanSupplier)2 CasWebSecurityConstants (org.apereo.cas.web.CasWebSecurityConstants)2 ProtocolEndpointWebSecurityConfigurer (org.apereo.cas.web.ProtocolEndpointWebSecurityConfigurer)2 EndpointLdapAuthenticationProvider (org.apereo.cas.web.security.authentication.EndpointLdapAuthenticationProvider)2 Unchecked (org.jooq.lambda.Unchecked)2 DisposableBean (org.springframework.beans.factory.DisposableBean)2 ObjectProvider (org.springframework.beans.factory.ObjectProvider)2