2015-04-10 21 views
14

Tôi hỏi một câu hỏi về mới nhất mùa xuân khuôn khổ, mã dựa cấu hình heremùa xuân an ninh 4 tùy chỉnh đăng nhập j_spring_security_check trở 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 cấu hình

@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/"); 
    } 
    } 

confi bảo mật 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(); 
    } 
} 

an ninh initializer

public class SecurityInitializer extends 
     AbstractSecurityWebApplicationInitializer { 

} 

tùy chỉnh đăng nhập

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); 
    } 
} 

Tuy nhiên, bây giờ tôi có vấn đề mới về đăng nhập tùy chỉnh.

khi đường bưu điện đến j_spring_security_check, tôi sẽ nhận được http 302.

Tôi đang yêu cầu /, nhưng sau khi đăng nhập, nó sẽ nằm trên trang đăng nhập.

Vì tôi đang sử dụng phiên bản 4.x bảo mật mùa xuân và cấu hình dựa trên mã hoàn toàn nên tôi không thể tìm thêm tài liệu tham khảo trên internet. Bất cứ ai có thể giúp đỡ để tìm ra lý do tại sao.

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)} 

tôi đã thay đổi 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); 
    } 
} 

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; 
    } 
} 
+0

302 là đúng, kể từ khi j_spring_security_check sẽ chuyển hướng bạn đến trang wellcome bạn. Bạn mong đợi điều gì để trở lại? – Nitek

+0

@Nitek vì tôi đang yêu cầu /, nhưng sau khi đăng nhập, nó vẫn nằm trên trang đăng nhập. – Timeless

+0

tôi có cùng vấn đề tương tự, bạn đã thử 'org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler' chưa? Ở đó bạn có một phương thức gọi là 'onAuthenticationSuccess() 'ở đó bạn có thể gọi từ' HttpServletResponse 'phương thức sendRedirect với trang chuyển hướng của bạn. –

Trả lời

1

nó là defaultSuccessUrl("/")

formLogin() 
     ... 
     .defaultSuccessUrl("/") 
    ... 
+0

Tôi đã thử ngay bây giờ, vẫn không hoạt động. khi tôi cố gắng đăng nhập, nó vẫn ở trên trang đăng nhập. Vì vậy, tôi đã cố gắng để yêu cầu /, nó sẽ được reditect để đăng nhập trang. Vì vậy, có nghĩa là xác thực thất bại ở đâu đó. – Timeless

0

Hãy thử cũng chính xác định "loginProcessingUrl":

formLogin() 
    ... 
    .loginProcessingUrl("/j_spring_security_check") 
... 
2

Trong Xuân An URL 4.x đăng nhập đã thay đổi để login thay vì j_spring_security_check, xem Migrating from Spring Security 3.x to 4.x (XML Configuration).

<form name='f'action="login" method='POST'> 
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" /> 
    <table> 
     <tbody> 
      <tr> 
       <td>User Name</td> 
       <td><input type="text" name="username" size="30" /></td> 
      </tr> 
      <tr> 
       <td>Password</td> 
       <td><input type="password" name="password" size="30" /></td> 
      </tr> 
      <tr> 
       <td></td> 
       <td><input type="submit" value="login" /></td> 
      </tr> 
     </tbody> 
    </table> 
</form> 
1

Có thể đó là vấn đề về CORS? bất kể nó là gì, bạn có thể kiểm tra yêu cầu và phản hồi bằng cách thêm:

authentication-success-handler-ref="appLoginSuccessHandler" 
authentication-failure-handler-ref="appLoginFailureHandler" 

để bảo mật mùa xuân của bạn. nó sẽ giống như thế này:

<http use-expressions="true" disable-url-rewriting="true" > 
    <logout invalidate-session="true" delete-cookies="true"/> 
    <form-login login-page="/YOUR_login_PAGE" 
     username-parameter="j_username" 
     password-parameter="j_password" 
     login-processing-url="/j_spring_security_check" 
     authentication-failure-url="/YOUR_login_PAGE" 
     default-target-url="/YOUR_login_PAGE" 
     authentication-success-handler-ref="appLoginSuccessHandler" 
     authentication-failure-handler-ref="appLoginFailureHandler"/> 

Nó sẽ gọi các phương pháp chính xác về các dịch vụ appLoginSuccessHandler và appLoginFailureHandler.

Ví dụ về khai dịch vụ:

@Service("appLoginSuccessHandler") 
public class LoginSuccessHandler extends 
SimpleUrlAuthenticationSuccessHandler{ 

@Override 
public void onAuthenticationSuccess(
HttpServletRequest request, HttpServletResponse response, Authentication 
auth) throws IOException, ServletException{ ...... 
..... 
..... 
..... Here you can handle also CORS ... and more ... 
Các vấn đề liên quan