简体   繁体   中英

Spring Security Custom Authentication Provider always redirect to login page

I have a serious problem... i'm trying to create login page with spring security integrated.

but, the problem is when i authenticate myself, spring security redirect me on the login page... and i really don't know why...

ApplicationConfig.java

@Configuration
@ComponentScan("id.mobiledashboard.*")
@EnableWebMvc
@EnableTransactionManagement
@PropertySource(value = "classpath:application.properties")
public class ApplicationConfig extends WebMvcConfigurerAdapter {

   private static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver";
   private static final String PROPERTY_NAME_DATABASE_USERNAME = "db.username";
   private static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";
   private static final String PROPERTY_NAME_DATABASE_URL = "db.url";

   private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
   private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
   private static final String PROPERTY_NAME_HIBERNATE_HBM2DLL_AUTO = "hibernate.hbm2ddl.auto";
   private static final String PROPERTY_NAME_HIBERNATE_LAZY_LOAD_NO_TRANS = "hibernate.enable_lazy_load_no_trans";
   private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN = "entitymanager.packages.to.scan";

   @Resource
   private Environment env;

   @Bean
   public DataSource dataSource() {
       DriverManagerDataSource dataSource = new DriverManagerDataSource();

       dataSource.setDriverClassName(env.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
       dataSource.setUsername(env.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
       dataSource.setPassword(env.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));
       dataSource.setUrl(env.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));

       return dataSource;
   }

   @Bean
   public LocalSessionFactoryBean sessionFactory() {
       LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();

       sessionFactoryBean.setDataSource(dataSource());
       sessionFactoryBean.setPackagesToScan(env.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN));
       sessionFactoryBean.setHibernateProperties(hibernateProperties());

       return sessionFactoryBean;
   }

   private Properties hibernateProperties() {
       Properties properties = new Properties();

       properties.put(PROPERTY_NAME_HIBERNATE_DIALECT, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
       properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
       properties.put(PROPERTY_NAME_HIBERNATE_LAZY_LOAD_NO_TRANS, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_LAZY_LOAD_NO_TRANS));
       //properties.put(PROPERTY_NAME_HIBERNATE_HBM2DLL_AUTO, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_HBM2DLL_AUTO));

       return properties;
   }

   @Bean
   public HibernateTransactionManager transactionManager() {
       HibernateTransactionManager transactionManager = new HibernateTransactionManager();

       transactionManager.setSessionFactory(sessionFactory().getObject());

       return transactionManager;
   }

   @Bean
   public InternalResourceViewResolver viewResolver() {
       InternalResourceViewResolver resolver = new InternalResourceViewResolver();
       resolver.setPrefix("/WEB-INF/views/");
       resolver.setSuffix(".jsp");

       return resolver;
   }

   @Bean
   public RequestMappingHandlerMapping requestMappingHandlerMapping() {
       RequestMappingHandlerMapping rmh = new RequestMappingHandlerMapping();
       rmh.setUseTrailingSlashMatch(true);
       return rmh;
   }

   @Override
   public void addResourceHandlers(ResourceHandlerRegistry registry) {
       registry.addResourceHandler("/assets/**").addResourceLocations("/WEB-INF/assets/");
   }

   @Override
   public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
       configurer.enable();
   }
}

SecurityConfig.java

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {  

    @Autowired
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(new CustomAuthenticationProvider());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http
        .authorizeRequests()
            .antMatchers("/assets/**").permitAll()
            .anyRequest().authenticated()
            .and()
        .formLogin()
            .loginPage("/login")
            .usernameParameter("username")
            .passwordParameter("password")
            .defaultSuccessUrl("/user/view")
            .permitAll()
            .and()
        .logout()
            .logoutUrl("/logout")
            .logoutSuccessUrl("/login")
            .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))             
            .permitAll()
            .and()
        .csrf()     
            .and()
        .exceptionHandling()
            .accessDeniedPage("/403");      
    }
}

CustomAuthenticationProvider.java

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        String name = authentication.getName();
        System.out.println("################# before name " + name);

        String password = authentication.getCredentials().toString(); 
        System.out.println("################# before password " + password);

        // Your custom authentication logic here
        WsBackendMobileDashboard wsOrganizations = new WsBackendMobileDashboard();
        WsBackendMobileDashboardPortType port = wsOrganizations.getSkkmigasMobileDashboardWsBackendMobileDashboardPort();
        BindingProvider bp = (BindingProvider) port;

        bp.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, Constants.USERNAME_PROPERTY);
        bp.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, Constants.PASSWORD_PROPERTY);

        ServiceReturn serviceReturn = port.loginBackEnd(name, password);

        if (serviceReturn.getCode().equals("0")) {
            System.out.println("################# success ");

            Collection<GrantedAuthority> authorities = new HashSet<>();
            GrantedAuthority authorityAdmin = new SimpleGrantedAuthority("ROLE_ADMIN");
            authorities.add(authorityAdmin);

            Authentication auth = new UsernamePasswordAuthenticationToken(name, password, authorities);

            System.out.println("################# after name " + auth.getPrincipal().toString());
            System.out.println("################# after password " + auth.getCredentials().toString());
            System.out.println("");

            return auth;
        } 
        return null;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
}

ApplicationInitializer.java

public class ApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

   @Override
   protected Class<?>[] getRootConfigClasses() {
           return new Class[] { ApplicationConfig.class };
   }

   @Override
   protected Class<?>[] getServletConfigClasses() {
           return null;
   }

   @Override
   protected String[] getServletMappings() {
           return new String[] { "/" };
   }    
}

the authentication seems no problem.

在此处输入图片说明

any ideas ? i'm almost despered...

Thank you in advance.

UPDATE

I must login twice before redirecting to defaultSuccessUrl.

Try adding this to your security configuration.

.antMatchers("/assets/**", "/login").permitAll()

Any changes?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM