Spring Security + Cas Auth + Статический список пользователей разрешен - PullRequest
0 голосов
/ 05 октября 2018

У меня есть приложение с весенней конфигурацией безопасности, которое подключается к серверу cas (работает):

@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Value("${cas.service-url}")
    private String serviceUrl;

    @Value("${cas.cas-url}")
    private String casUrl;

    @Autowired
    private AuthenticationProvider authenticationProvider;

    @Autowired
    private AuthenticationEntryPoint authenticationEntryPoint;

    @Autowired
    private SingleSignOutFilter singleSignOutFilter;

    @Autowired
    private LogoutFilter logoutFilter;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf()
                .disable()
                .authorizeRequests()
                .regexMatchers("/secured.*")
                .authenticated()
                .and()
                .authorizeRequests()
                .regexMatchers("/")
                .permitAll()
                .and()
                .httpBasic()
                .authenticationEntryPoint(authenticationEntryPoint)
                .and()
                .addFilterBefore(singleSignOutFilter, CasAuthenticationFilter.class)
                .addFilterBefore(logoutFilter, LogoutFilter.class);
    }

    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return new ProviderManager(Arrays.asList(authenticationProvider));
    }

    @Bean
    public CasAuthenticationFilter casAuthenticationFilter(ServiceProperties sP) throws Exception {
        CasAuthenticationFilter filter = new CasAuthenticationFilter();
        filter.setServiceProperties(sP);
        filter.setAuthenticationManager(authenticationManager());
        return filter;
    }

    @Bean
    public ServiceProperties serviceProperties() {
        ServiceProperties serviceProperties = new ServiceProperties();
        serviceProperties.setService(serviceUrl);
        serviceProperties.setSendRenew(false);
        return serviceProperties;
    }

    @Bean
    @Primary
    public AuthenticationEntryPoint authenticationEntryPoint(ServiceProperties sP) {
        CasAuthenticationEntryPoint entryPoint = new CasAuthenticationEntryPoint();
        entryPoint.setLoginUrl(casUrl + "/login");
        entryPoint.setServiceProperties(sP);
        return entryPoint;
    }

    @Bean
    public TicketValidator ticketValidator() {
        return new Cas30ServiceTicketValidator(casUrl);
    }

    @Bean
    public CasAuthenticationProvider casAuthenticationProvider() {
        CasAuthenticationProvider provider = new CasAuthenticationProvider();
        provider.setServiceProperties(serviceProperties());
        provider.setTicketValidator(ticketValidator());
        provider.setUserDetailsService((s) -> {
            return new User(s, "fakepassword", true, true, true, true, AuthorityUtils.createAuthorityList("ROLE_ADMIN"));
        });
        provider.setKey("CAS_PROVIDER_IMPORT_PARCOURSUP_KEY");
        return provider;
    }

    @Bean
    public SecurityContextLogoutHandler securityContextLogoutHandler() {
        return new SecurityContextLogoutHandler();
    }

    @Bean
    public LogoutFilter logoutFilter() {
        LogoutFilter logoutFilter = new LogoutFilter(casUrl + "/logout", securityContextLogoutHandler());
        logoutFilter.setFilterProcessesUrl("/logout/cas");
        return logoutFilter;
    }

    @Bean
    public SingleSignOutFilter singleSignOutFilter() {
        SingleSignOutFilter singleSignOutFilter = new SingleSignOutFilter();
        singleSignOutFilter.setCasServerUrlPrefix(casUrl);
        singleSignOutFilter.setIgnoreInitConfiguration(true);
        return singleSignOutFilter;
    }

    @EventListener
    public SingleSignOutHttpSessionListener singleSignOutHttpSessionListener(HttpSessionEvent event) {
        return new SingleSignOutHttpSessionListener();
    }

}

Теперь я хотел бы добавить список авторизованного входа в систему, единственные, кто можетполучить доступ к приложению (то есть: для доступа они должны быть в cas AND в статическом списке).

String allowedLogin = List.of ("robert.bob", "john.jon");

Я нахожу эту ссылку: Spring Security - конкретные пользователи но я нене знаю, как реализовать StaticUserProvider и где его настроить в моей конфигурации.

Ответы [ 2 ]

0 голосов
/ 11 октября 2018

Я думаю, что самым простым способом было бы просто создать исключение UsernameNotFoundException в вашем UserDetailsService, если пользователя нет в списке.Вот так:

    provider.setUserDetailsService((s) -> {
        if(!allowedLogin.contains(s.getAssertion().getPrincipal().getName())) {
            throw new UsernameNotFoundException("user not authorized to use app");
        }
        return new User(s, "fakepassword", true, true, true, true, AuthorityUtils.createAuthorityList("ROLE_ADMIN"));
    });
0 голосов
/ 10 октября 2018

Вы можете сделать это с помощью Spring Security Roles .

Создайте пользовательскую роль для своего приложения:

public final class AuthoritiesConstants {

    public static final String APP = "ROLE_APP";

}

Затем добавьте всех пользователей, которым вы хотите предоставить доступна эту роль.

И, наконец, ограничьте доступ к вашему приложению с помощью Ant Matchers :

.antMatchers("/**").hasAuthority(AuthoritiesConstants.APP)
...