ho fatto una domanda sulle ultime Spring Framework, basato codice di configurazione herePrimavera login di sicurezza 4 personalizzato j_spring_security_check tornare http 302
initializer
public class AppInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { SecurityConfig.class };
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { MvcConfig.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
MVC config
@EnableWebMvc
@ComponentScan({ "com.appname.controller" })
public class MvcConfig extends WebMvcConfigurerAdapter {
@Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/jsp/");
resolver.setSuffix(".jsp");
return resolver;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/res/**").addResourceLocations("/res/");
}
}
sicurezza confi g
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, jsr250Enabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private CustomUserDetailsService customUserDetailsService;
public SecurityConfig() {
customUserDetailsService = new CustomUserDetailsService();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)
throws Exception {
auth.inMemoryAuthentication().withUser("user").password("password")
.roles("USER");
auth.userDetailsService(customUserDetailsService);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/res/**").permitAll()
.and().authorizeRequests()
.anyRequest().hasRole("USER")
.and().formLogin().loginPage("/account/signin").permitAll()
.and().logout().permitAll();
}
}
initializer sicurezza
public class SecurityInitializer extends
AbstractSecurityWebApplicationInitializer {
}
login personalizzato
public class CustomUserDetailsService implements UserDetailsService {
private AccountRepository accountRepository;
public CustomUserDetailsService() {
this.accountRepository = new AccountRepository();
}
@Override
public UserDetails loadUserByUsername(String email)
throws UsernameNotFoundException {
Account account = accountRepository.getAccountByEmail(email);
if (account == null) {
throw new UsernameNotFoundException("Invalid email/password.");
}
Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
authorities.add(new SimpleGrantedAuthority("USER"));
return new User(account.getEmail(), account.getPassword(), authorities);
}
}
Tuttavia, ora ho nuovo numero su login personalizzato.
quando posta a j_spring_security_check, riceverò http 302.
sto chiedendo /, ma dopo Entra, rimane sulla pagina di accesso.
Perché sto utilizzando la versione 4.x di sicurezza primaverile e la configurazione basata esclusivamente su codice, quindi non riesco a trovare più riferimenti su Internet. Qualcuno può aiutare a capire perché.
EDIT
org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'securityConfig':
Injection of autowired dependencies failed;
nested exception is org.springframework.beans.factory.BeanCreationException:
Could not autowire field:
private org.springframework.security.core.userdetails.UserDetailsService sg.mathschool.infra.SecurityConfig.userDetailsService;
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type [org.springframework.security.core.userdetails.UserDetailsService] found for dependency:
expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations:
{@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=userDetailsService)}
ho cambiato CustomUserDetailsService
@Service("userDetailsService")
public class CustomUserDetailsService implements UserDetailsService {
private AccountRepository accountRepository;
public CustomUserDetailsService() {
this.accountRepository = new AccountRepository();
}
@Override
@Transactional(readOnly = true)
public UserDetails loadUserByUsername(String email)
throws UsernameNotFoundException {
Account account = accountRepository.getAccountByEmail(email);
if (account == null) {
throw new UsernameNotFoundException("Invalid email/password.");
}
Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
authorities.add(new SimpleGrantedAuthority("USER"));
return new User(account.getEmail(), account.getPassword(), authorities);
}
}
e security config
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, jsr250Enabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
@Qualifier("userDetailsService")
private UserDetailsService userDetailsService;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)
throws Exception {
auth.inMemoryAuthentication().withUser("user").password("password")
.roles("USER");
auth.userDetailsService(userDetailsService).passwordEncoder(
passwordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/res/**").permitAll()
.antMatchers("/account/**").permitAll().anyRequest()
.hasRole("USER").and().formLogin().loginPage("/account/signin")
.failureUrl("/account/signin?error").usernameParameter("email")
.passwordParameter("password").and().logout()
.logoutSuccessUrl("/account/signin?logout").and().csrf();
}
@Bean
public PasswordEncoder passwordEncoder() {
PasswordEncoder encoder = new BCryptPasswordEncoder();
return encoder;
}
}
302 è corretto, dal momento che la j_spring_security_check vi reindirizzerà alla pagina di benvenuto. Cosa ti aspetti che ritorni? – Nitek
@Nitek perché sto richiedendo /, ma dopo l'accesso rimane nella pagina di accesso. – Timeless
Ho avuto lo stesso problema, hai provato il file 'org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler'? Esiste un metodo chiamato 'onAuthenticationSuccess()' lì puoi chiamare dal 'HttpServletResponse' il metodo sendRedirect con la tua pagina di reindirizzamento. –