Использование проверки подлинности в памяти и базы данных в одном проекте - PullRequest
0 голосов
/ 20 декабря 2018

У меня есть существующий проект, который использует аутентификацию InMemory со Spring Security, и теперь есть новое требование.Теперь нам также необходимо использовать аутентификацию на основе базы данных вместе с аутентификацией InMemory, так как будет два типа пользователей: один статический, а другой динамически добавленный;для динамически добавленных нам нужно использовать аутентификацию на основе базы данных.Я использовал аутентификацию на основе InMemory и базы данных в разных проектах, но не в одном и том же.Пожалуйста, предложите несколько решений, использующих оба в одном проекте.Я использую Spring Boot 2.0.2 Release, и решение на основе Java приветствуется.

@Configuration
@EnableWebSecurity
@Order(Ordered.HIGHEST_PRECEDENCE)
public class SecurityConfig extends WebSecurityConfigurerAdapter{

    @Value("${admin.username}")
    String user;

    @Value("${admin.password}")
    String password;

    @Value("${superadmin.username}")
    String admin;

    @Value("${superadmin.password}")
    String adminPassword;

    /* (non-Javadoc)
     * @see org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter#configure(org.springframework.security.config.annotation.web.builders.HttpSecurity)
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
        .antMatchers("/","/blogs","/support","/index","/pricing","/step-guide","/sales-info","/sales-info/**","/step-guide/**","/blogs/**","/productdetail","/25-point-checklist-for-networking","/thanks-for-downloading-checklist","/events-&-conference",,"/share_profile","/share","/share/**").permitAll()
        .antMatchers("/swagger-ui.html").hasAnyAuthority("ROLE_SUPER_ADMIN")
        .antMatchers("/admin").hasAnyAuthority("ROLE_SUPER_ADMIN","ROLE_ADMIN")
        .antMatchers("/api/**").permitAll()
        .anyRequest().authenticated()       
        .and()
        .formLogin()
        .loginPage("/login").permitAll()
        .successHandler(new AuthenticationSuccessHandler() {

            @Override
            public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                    Authentication authentication) throws IOException, ServletException {
                String currentUsername = authentication.getName();
                if(currentUsername.equals(admin)) {
                    response.sendRedirect(request.getContextPath()+"/admin");
                }
                else if(currentUsername.equals(user))
                {
                    response.sendRedirect(request.getContextPath()+"/swagger-ui.html");
                }
            }

        })
        .and()
        .logout()
        .permitAll()
        .and().csrf().disable();


    }

    /* (non-Javadoc)
     * @see org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter#configure(org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder)
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.inMemoryAuthentication()       
        .withUser(user)
        .password(PasswordUtil.encryptPassword(password))
        .credentialsExpired(false)
        .accountExpired(false)
        .accountLocked(false)       
        .roles("SUPER_ADMIN");

        auth.inMemoryAuthentication()
        .withUser(admin)
        .password(PasswordUtil.encryptPassword(adminPassword))
        .credentialsExpired(false)
        .accountExpired(false)
        .accountLocked(false)
        .roles("ADMIN");
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/resources/**","/webjars/**","/static/**","/css/**","/js/**","/fonts/**","/images/**","/favicon.ico","/swagger-resources/**","/bucket/**");
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }   

}

И код с обработчиком аутентификации базы данных и пользовательской аутентификации:

@Configuration
@EnableWebSecurity
@Order(Ordered.HIGHEST_PRECEDENCE)
public class SecurityConfig extends WebSecurityConfigurerAdapter{

    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    AppUserDetailsService appUserDetailsService;

    @Autowired
    CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler;

    /* (non-Javadoc)
     * @see org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter#configure(org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder)
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(appUserDetailsService).passwordEncoder(passwordEncoder);
    }

    /* (non-Javadoc)
     * @see org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter#configure(org.springframework.security.config.annotation.web.builders.WebSecurity)
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/resources/**","/webjars/**","/static/**","/css/**","/js/**","/fonts/**","/images/**","/favicon.ico");
    }

    /* (non-Javadoc)
     * @see org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter#configure(org.springframework.security.config.annotation.web.builders.HttpSecurity)
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
        .antMatchers("/").permitAll()
        .antMatchers("/swagger-ui.html").hasAnyAuthority("ROLE_SUPER_ADMIN")
        .antMatchers("/api/user/sign_up").permitAll()
        .antMatchers("/api/user/forgot_password").permitAll()
        .antMatchers("/api/**").authenticated()
        .anyRequest().authenticated()
        .and()
        .formLogin()
        .loginPage("/login").successHandler(customAuthenticationSuccessHandler).permitAll()     
        .and()
        .logout()
        .permitAll()
        .and().csrf().disable().exceptionHandling().accessDeniedPage("/403");
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

}

Поэтому я хочу объединитьэти два, и он может иметь одну страницу входа или несколько страниц входа в зависимости от случая.

Ответы [ 2 ]

0 голосов
/ 20 декабря 2018

Если вы реализуете WebSecurityConfigurerAdapter, вы получите следующее:

 @Override
 protected void configure(AuthenticationManagerBuilder auth) {

         //   auth.ldapAuthentication()...
        auth.apply(new LdapAuthenticationProviderConfigurer());
        auth.apply(new JdbcUserDetailsManagerConfigurer<>());
        auth.apply(new InMemoryUserDetailsManagerConfigurer<>());
 }

Метод ldapAuthentication () не делает ничего, кроме добавления LdapAuthenticationProvider в список конфигурации AbstractConfiguredSecurityBuilder.Просто попробуйте добавить другой Configurer в AuthenticationManagerBuilder.

Пример:

InMemoryUserDetailsManagerConfigurer memprovider = 
    new InMemoryUserDetailsManagerConfigurer();

    memprovider.withUser("admin")
            .credentialsExpired(false)
            .accountExpired(false)
            .accountLocked(false)
            .roles("SUPER_ADMIN");
    auth.apply(memprovider);

Это относится к новому провайдеру.Чем просто применить второй:

JdbcUserDetailsManagerConfigurer jdpbProvider = 
    new JdbcUserDetailsManagerConfigurer();
    jdpbProvider.withUser("user").password() ...
    auth.apply(jdpbProvider);

С UserDetailService:

 @Autowired
 UserDetailsService appUserDetailsService;

и

 DaoAuthenticationConfigurer daoAC = 
     new DaoAuthenticationConfigurer(appUserDetailsService);
 daoAC.passwordEncoder(passwordEncoder);
 auth.apply(daoAC);
0 голосов
/ 20 декабря 2018

Вы можете использовать org.springframework.security.authentication.ProviderManager в безопасности Spring и использовать Database и InMemory как providers.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...