mraible commented on code in PR #300: URL: https://github.com/apache/roller/pull/300#discussion_r4594859580
########## app/src/main/java/org/apache/roller/weblogger/ui/core/security/SecurityConfig.java: ########## @@ -0,0 +1,252 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 org.apache.roller.weblogger.ui.core.security; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.Enumeration; +import java.util.List; + +import org.apache.commons.lang3.StringUtils; +import org.apache.roller.weblogger.config.AuthMethod; +import org.apache.roller.weblogger.config.WebloggerConfig; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpMethod; +import org.springframework.security.authentication.AuthenticationProvider; +import org.springframework.security.authentication.dao.DaoAuthenticationProvider; +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.configuration.WebSecurityCustomizer; +import org.springframework.security.core.userdetails.UserDetailsPasswordService; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.ldap.DefaultSpringSecurityContextSource; +import org.springframework.security.ldap.authentication.BindAuthenticator; +import org.springframework.security.ldap.authentication.LdapAuthenticationProvider; +import org.springframework.security.ldap.search.FilterBasedLdapUserSearch; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint; +import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler; +import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler; +import org.springframework.security.web.servlet.util.matcher.PathPatternRequestMatcher; +import org.springframework.security.web.util.matcher.RequestMatcher; +import org.springframework.web.util.pattern.PathPatternParser; + +/** + * Roller's Spring Security configuration, loaded by the web application + * context that web.xml sets up. + * + * <p>Logins use the Roller database, or the LDAP directory configured by the + * users.ldap.* properties when authentication.method is ldap. OpenID Connect + * login is available when oidc.* client registrations are configured. + */ +@Configuration +@EnableWebSecurity +public class SecurityConfig { + + static final String LOGIN_PAGE = "/roller-ui/login.rol"; + + static final String LOGIN_PROCESSING_URL = "/roller_j_security_check"; + + private static final String ACCESS_PREFIX = "security.access."; + + @Bean + public PasswordEncoder passwordEncoder() { + return RollerPasswordEncoders.create(); + } + + // Not a bean: a UserDetailsService bean would give Spring Security a + // second, database-backed login provider, including when LDAP is used. + UserDetailsService userDetailsService() { + return new RollerUserDetailsService(); + } + + @Bean + public RollerClientRegistrationRepository clientRegistrationRepository() { + return new RollerClientRegistrationRepository(); + } + + @Bean + public RollerOidcUserService rollerOidcUserService() { + return new RollerOidcUserService(); + } + + @Bean + public WebSecurityCustomizer staticResources() { + return web -> web.ignoring().requestMatchers("/images/**", "/scripts/**", "/styles/**"); + } + + @Bean + public SecurityFilterChain securityFilterChain(HttpSecurity http, PasswordEncoder passwordEncoder, + RollerClientRegistrationRepository clientRegistrationRepository, + RollerOidcUserService rollerOidcUserService) throws Exception { + + UserDetailsService userDetailsService = userDetailsService(); + + List<AccessRule> siteRules = siteAccessRules(); + http.authorizeHttpRequests(requests -> { + for (AccessRule rule : siteRules) { + requests.requestMatchers(rule.matcher()).hasAnyAuthority(rule.authorities()); + } + requests + .requestMatchers("/roller-ui/login-redirect**").hasAnyAuthority("admin", "editor") + .requestMatchers("/roller-ui/profile**").hasAnyAuthority("admin", "editor") + .requestMatchers("/roller-ui/createWeblog**").hasAnyAuthority("admin", "editor") + .requestMatchers("/roller-ui/menu**").hasAnyAuthority("admin", "editor") + .requestMatchers("/roller-ui/authoring/**").hasAnyAuthority("admin", "editor") + .requestMatchers("/roller-ui/admin/**").hasAuthority("admin") + .requestMatchers("/rewrite-status*").hasAuthority("admin") + .anyRequest().permitAll(); + }); + + http.authenticationProvider(loginProvider(userDetailsService, passwordEncoder)); + + http.formLogin(form -> form + .loginPage(LOGIN_PAGE) + .usernameParameter("j_username") + .passwordParameter("j_password") + .failureUrl(LOGIN_PAGE + "?error=true") + .loginProcessingUrl(LOGIN_PROCESSING_URL)); + + LoginUrlAuthenticationEntryPoint entryPoint = new LoginUrlAuthenticationEntryPoint(LOGIN_PAGE); + entryPoint.setForceHttps(WebloggerConfig.getBooleanProperty("securelogin.enabled")); + http.exceptionHandling(exceptions -> exceptions.authenticationEntryPoint(entryPoint)); + + if (WebloggerConfig.getBooleanProperty("rememberme.enabled")) { + http.rememberMe(rememberMe -> rememberMe + .rememberMeServices(new RollerRememberMeServices(userDetailsService))); + } + + // OAuth2/OIDC login (active only when oidc.*.client-id properties are configured) + SavedRequestAwareAuthenticationSuccessHandler oidcSuccess = + new SavedRequestAwareAuthenticationSuccessHandler(); + oidcSuccess.setDefaultTargetUrl("/roller-ui/menu.rol"); + http.oauth2Login(oauth2 -> oauth2 + .clientRegistrationRepository(clientRegistrationRepository) + .userInfoEndpoint(userInfo -> userInfo.oidcUserService(rollerOidcUserService)) + .successHandler(oidcSuccess) + // OIDC failures get their own marker so the login page does + // not diagnose them as a wrong password + .failureHandler(new SimpleUrlAuthenticationFailureHandler(LOGIN_PAGE + "?error=oidc")) + .loginPage(LOGIN_PAGE)); + + // Roller has its own logout action + http.logout(logout -> logout.disable()); + + // Roller protects its own forms with the salt that LoadSaltFilter and + // ValidateSaltFilter check on every POST under /roller-ui, so Spring's + // CSRF token is only required for the login form, which posts outside + // /roller-ui. The token is created only when the login page asks for + // it, so other pages don't start a session for it. + http.csrf(csrf -> csrf.requireCsrfProtectionMatcher( Review Comment: Good catch, fixed in bf535607f. A login post with a missing or stale token now redirects to `login.rol?error=expired`, and the login page shows "The login page expired. Please try again." The redirect comes with a new session and token, so the next try works. I didn't use `defaultAccessDeniedHandlerFor` as written: when it's the only one registered, Spring uses it for every refusal, so the parity table's editor-to-admin cases started redirecting to the login page instead of getting 403. The handler checks for `CsrfException` instead, and everything else still goes to the normal 403 page. `SecurityConfigTest` covers a login post without a token, one with a token from a session that has since expired (followed by a retry that logs in), and another refused POST that still gets 403. CHANGES mentions the new behaviour. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
