使用spring security和mongodb登录无法正常工作

时间:2015-07-12 08:31:10

标签: spring mongodb security spring-security

我使用的是spring security和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;
    }

}

Controller类

  @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>

1 个答案:

答案 0 :(得分: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;
    }

}