Определить пользователя CAS автоматически на общедоступной странице (allowAll())
Я использую Spring Security с Spring Boot и аутентифицирую своих пользователей через JASIG CAS. Некоторые страницы требуют явной аутентификации (.authenticated()), а некоторые из них предназначены для всех пользователей.
Теперь в меню есть определенная область, в которой указан текущий пользователь и возможные действия, такие как вход / выход из системы.
Моя главная проблема заключается в том, что главная страница является общедоступной (allowAll()) и что, если у пользователя уже есть сеанс CAS через какое-либо другое приложение, он отображается как "anonymousUser" до тех пор, пока не будет выполнен вход в систему вручную или не будет открыта защищенная страница.,
Есть ли кто-нибудь, у кого есть идеи, как заставить это работать?
Моя конфигурация безопасности:
import org.jasig.cas.client.validation.Cas20ServiceTicketValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.security.cas.ServiceProperties;
import org.springframework.security.cas.authentication.CasAuthenticationProvider;
import org.springframework.security.cas.web.CasAuthenticationEntryPoint;
import org.springframework.security.cas.web.CasAuthenticationFilter;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.AuthenticationUserDetailsService;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private Environment env;
@Autowired
private CasAuthenticationProvider authProvider;
@Bean
public ServiceProperties serviceProperties() {
ServiceProperties sp = new ServiceProperties();
sp.setSendRenew(false);
sp.setService(env.getProperty("app.url") + "/j_spring_cas_security_check");
return sp;
}
@SuppressWarnings("rawtypes")
@Autowired
private AuthenticationUserDetailsService customUserDetailsService() {
return new CASUserDetailsService();
}
@Bean
public CasAuthenticationProvider casAuthenticationProvider() {
CasAuthenticationProvider casAuthenticationProvider = new CasAuthenticationProvider();
casAuthenticationProvider.setAuthenticationUserDetailsService(customUserDetailsService());
casAuthenticationProvider.setServiceProperties(serviceProperties());
casAuthenticationProvider.setTicketValidator(cas20ServiceTicketValidator());
casAuthenticationProvider.setKey("an_id_for_this_auth_provider_only");
return casAuthenticationProvider;
}
@Bean
public Cas20ServiceTicketValidator cas20ServiceTicketValidator() {
return new Cas20ServiceTicketValidator(env.getProperty("cas.service.url"));
}
@Bean
public CasAuthenticationFilter casAuthenticationFilter() throws Exception {
CasAuthenticationFilter casAuthenticationFilter = new CasAuthenticationFilter();
casAuthenticationFilter.setAuthenticationManager(authenticationManager());
casAuthenticationFilter.setAuthenticationSuccessHandler(savedRequestAwareAuthenticationSuccessHandler());
return casAuthenticationFilter;
}
@Bean
public CasAuthenticationEntryPoint casAuthenticationEntryPoint() {
CasAuthenticationEntryPoint ep = new CasAuthenticationEntryPoint();
ep.setLoginUrl(env.getProperty("cas.service.url") + "/login");
ep.setServiceProperties(serviceProperties());
return ep;
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authProvider);
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/js/**").antMatchers("/fonts/**").antMatchers("/images/**").antMatchers("/css/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.exceptionHandling().
authenticationEntryPoint(casAuthenticationEntryPoint()).and().addFilter(casAuthenticationFilter()).
logout().logoutUrl("/caslogout").addLogoutHandler(logoutHandler()).logoutSuccessUrl("/").deleteCookies("JSESSIONID").permitAll().and().
csrf().disable().headers().frameOptions().disable().authorizeRequests().antMatchers("/rest/**").permitAll().
antMatchers("/login/**").authenticated().antMatchers("/settings/**").authenticated().
antMatchers("/projects/*/settings").authenticated().antMatchers("/projects/*/role").authenticated().
antMatchers("/projects/*/*/admin").authenticated().antMatchers("/**").permitAll();
}
@Bean
public SavedRequestAwareAuthenticationSuccessHandler savedRequestAwareAuthenticationSuccessHandler() {
CASAuthSuccessHandler auth = new CASAuthSuccessHandler();
return auth;
}
@Bean
public CASLogoutHandler logoutHandler() {
CASLogoutHandler logout = new CASLogoutHandler();
return logout;
}
@EnableGlobalMethodSecurity(prePostEnabled = true, jsr250Enabled = true)
private static class GlobalSecurityConfiguration extends GlobalMethodSecurityConfiguration {
}
}
1 ответ
То, что вы ищете, - это функция CAS Gateway. В настоящее время это не поддерживается в Spring Security. Существует протокол JIRA, поддерживающий его, и запрос на извлечение, который ожидает дополнительных изменений на основе моего отзыва отправителю.
Я бы посмотрел на запрос на извлечение, поскольку он демонстрирует несколько вариантов того, как это реализовать. Пожалуйста, прочитайте все это полностью, так как вам потребуется внести некоторые изменения в запрос на извлечение, чтобы убедиться, что ваше приложение работает.