2015-07-12 125 views
2

我使用彈簧安全和mongodb。嘗試登錄但出現錯誤:無效的用戶名和密碼!登錄彈簧安全和mongodb不工作

不知道它取決於什麼。在2天內嘗試過沒有任何成功。

任何人如何能看到任何錯誤的地方?

SecurityConfiguration

@Configuration 
@EnableWebSecurity 
@EnableGlobalMethodSecurity(prePostEnabled=true,securedEnabled = true) 
@ComponentScan({ "com.test.*" }) 
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter 
{ 

@Autowired(required=false) 
private AuthFailureHandler authFailureHandler; 

@Autowired(required=false) 
private HttpLogoutSuccessHandler logoutSuccessHandler; 


@Bean 
public MySimpleUrlAuthenticationSuccessHandler myAuthenticationSuccessHandler() 
{ 
    return new MySimpleUrlAuthenticationSuccessHandler(); 

} 

@Bean 
public MongoUserDetailsService mongoUserDetailsService() 
{ 

    return new MongoUserDetailsService(); 
} 

@Autowired(required=true) 
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception 
{ 
    auth.userDetailsService(this.mongoUserDetailsService()).passwordEncoder(new BCryptPasswordEncoder()); 

} 


@Override 
protected void configure(AuthenticationManagerBuilder registry) throws Exception { 
    registry.userDetailsService(this.mongoUserDetailsService()); 
} 

@Override 
    public void configure(WebSecurity web) throws Exception { 
    web 
     .ignoring() 
     .antMatchers("/resources/**"); // #3 
    } 


@Bean 
public LoginUrlAuthenticationEntryPoint loginUrlAuthenticationEntryPoint() 
{ 
    LoginUrlAuthenticationEntryPoint loginUrlAuthenticationEntryPoint = new LoginUrlAuthenticationEntryPoint("/login"); 
    return loginUrlAuthenticationEntryPoint; 
} 

@Bean 
public SavedRequestAwareAuthenticationSuccessHandler savedRequestAwareAuthenticationSuccessHandler() 
{ 
    SavedRequestAwareAuthenticationSuccessHandler auth = new SavedRequestAwareAuthenticationSuccessHandler(); 
    auth.setTargetUrlParameter("targetUrl"); 
    return auth; 
} 


@Bean 
public SessionRegistry sessionRegistry() { 
    return new SessionRegistryImpl(); 
} 

    @Override 
protected void configure(HttpSecurity http) throws Exception { 
     http 
      .csrf().disable() 
      .and() 
      .authorizeRequests() 
      .antMatchers("/","/shared/**").permitAll() 
      .anyRequest().authenticated() 
      .and() 
     .formLogin() 
     .loginPage("/login") 
     .permitAll() 
     .usernameParameter("username") 
     .passwordParameter("password") 
     .successHandler(myAuthenticationSuccessHandler()) 
     .failureHandler(authFailureHandler) 
     .failureUrl("/login?error") 
    .and() 
     .portMapper() 
     .http(80).mapsTo(443) 
     .http(8080).mapsTo(8443) 
    .and() 
     .logout() 
     .logoutRequestMatcher(new AntPathRequestMatcher("/logout")) 
     .logoutSuccessUrl("/login?logout") 
     .logoutSuccessHandler(logoutSuccessHandler) 
     .deleteCookies("JSESSIONID") 
     .invalidateHttpSession(true)  
    .and() 
     .exceptionHandling() 
     .accessDeniedPage("/shared/accessDenied") 
     .and() 
     .sessionManagement() 
     .invalidSessionUrl("/login") 
     .maximumSessions(1); 


     } 
    private CsrfTokenRepository csrfTokenRepository() { 
     HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository(); 
     repository.setHeaderName("X-XSRF-TOKEN"); 
     return repository; 
    } 

} 

的控制器,用於登錄類

@RequestMapping(value = "/login", method = RequestMethod.GET) 
    public ModelAndView login(@RequestParam(value = "error", required = false) String error, 
     @RequestParam(value = "logout", required = false) String logout) { 

    ModelAndView model = new ModelAndView(); 
    if (error != null) { 
     model.addObject("error", "Invalid username and password!"); 
     } 

    if (logout != null) { 
     model.addObject("msg", "You've been logged out successfully."); 
    } 
    model.setViewName("login"); 

    return model; 

} 

MongoUserDetail服務

@Component 
@Service 
public class MongoUserDetailsService implements UserDetailsService 
{ 

    private MongoOperations mongoOperation; 


    @SuppressWarnings("unused") 
    private static final Logger logger = Logger.getLogger(MongoUserDetailsService.class); 
    private User userdetails; 

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException 
    { 

     try 
     { 
      mongoOperation = new MongoTemplate(new MongoClient(), "test"); 
     } 
     catch (UnknownHostException e) 
     { 
      e.printStackTrace(); 
     } 
     catch (MongoException e) 
     { 
      e.printStackTrace(); 
     } 
     try{ 
     boolean enabled = true; 
     boolean accountNonExpired = true; 
     boolean credentialsNonExpired = true; 
     boolean accountNonLocked = true; 
     Customer user = getUserDetail(username); 

     if(user !=null){ 
      System.out.println("username: "+user.getUsername()); 
      System.out.println("password: "+user.getPassword()); 
      System.out.println("roles: "+getAuthorities(user.getRoleAsInt())); 
     } 
     if (user == null) 
     { 
      throw new AuthenticationServiceException("Authentication failed for user " + username); 

     } 
     userdetails = new User(user.getUsername(), user.getPassword(), enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, 
       getAuthorities(user.getRoleAsInt())); 
     return userdetails; 
    } 
     catch (Exception e) 
     { 
      System.out.println("query failed"); 
      throw new RuntimeException(e); 
     } 
    } 

    public List<GrantedAuthority> getAuthorities(Integer role) 
    { 
     List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>(); 
     if (role.intValue() == 2) 
     { 
      authList.add(new SimpleGrantedAuthority("ROLE_USER")); 
      authList.add(new SimpleGrantedAuthority("ROLE_ADMIN")); 
     } 
     else if (role.intValue() == 1) 
     { 
      authList.add(new SimpleGrantedAuthority("ROLE_USER")); 
     } 
     return authList; 
    } 



    public List<String> getRoles(Integer role) 
    { 
     List<String> roles = new ArrayList<String>(); 

     if (role.intValue() == 1) 
     { 
      roles.add("ROLE_USER"); 
      roles.add("ROLE_ADMIN"); 

     } 
     else if (role.intValue() == 2) 
     { 
      roles.add("ROLE_USER"); 
     } 

     return roles; 
    } 

    public Customer getUserDetail(String username) 
    { 
     Customer user = mongoOperation.findOne(new Query(Criteria.where("username").is(username)), Customer.class); 
     return user; 
    } 
} 

的login.jsp

<div id="login-box"> 

      <h3>Login with Username and Password</h3> 

      <c:if test="${not empty error}"> 
       <div class="error">${error}</div> 
      </c:if> 
      <c:if test="${not empty msg}"> 
       <div class="msg">${msg}</div> 
      </c:if> 

    <form name='loginForm' action="<c:url value='/login' />" method='POST'> 
     <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/> 
     <div> 
      <label for="username">Username</label> 
      <input type="text" name="username" id="username" required > 
     </div> 
     <div> 
      <label for="password">Password</label> 
      <input type="password" name="password" id="password" required> 
     </div> 
     <button type="submit">Sign in</button> 
    </form> 
     </div> 
+0

你能解釋的情況下發生了什麼?也請嘗試在登錄方法中打印錯誤值並檢查。 –

+0

嗨 我只得到:無效的用戶名或密碼! – user1067665

回答

0

已解決

這是我的MongoUserDetailsS​​ervice中的一個衝突。

這裏是新的,其工作良好!(OBS!新的日誌與電子郵件)

 
@Component 
public class MongoUserDetailsService implements UserDetailsService 
{ 
    public MongoOperations mongoOperations; 

    private User userDetails; 

    @Override 
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException 
    { 

     boolean enabled = true; 
     boolean accountNonLocked = true; 
     boolean accountNonExpired = true; 
     boolean credentialsNonExpired = true; 
     try 
     { 
      mongoOperations = new MongoTemplate(new MongoClient(), "booking"); 
      Customer user = getUserByEmail(email); 

      userDetails = new User(user.getEmail(), user.getPassword(), enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, 
        getAuthorities(user.getRoleAsInt())); 
     } 
     catch (UnknownHostException e) 
     { 
      e.printStackTrace(); 
     } 


     return userDetails; 
    } 

    public List getAuthorities(Integer role) 
    { 

     List authList = new ArrayList(); 
     if (role.intValue() == 2) 
     { 
      authList.add(new SimpleGrantedAuthority("ROLE_ADMIN")); 
      authList.add(new SimpleGrantedAuthority("ROLE_USER")); 
     } 
     if (role.intValue() == 1) 
     { 
      authList.add(new SimpleGrantedAuthority("ROLE_USER")); 
     } 

     return authList; 

    } 

    public Customer getUserByEmail(String email) 
    { 
     Query query = new Query(); 
     query.addCriteria(Criteria.where("email").is(email)); 
     Customer customer = mongoOperations.findOne(query, Customer.class); 

     return customer; 
    } 

}