Spring security-Bad Credentials Exception

时间:2015-08-23 03:47:10

标签: spring spring-mvc spring-security

用户

@Entity
@Table(name="users")
public class User{

    @Id
    @NotNull
    @Column(name="username", unique=true)
    private String username;

    @NotBlank
    private String first_name;
    @NotBlank
    private String last_name;
    @NotNull
    private String password;
    @NotBlank
    private String email;
    @NotBlank
    private String phone;

    @OneToMany(mappedBy="user")
    private Collection<Role> roles;
    private boolean enabled;

    public User(){

    }

    public User(User user) {
        this.username=user.username;
        this.first_name=user.first_name;
        this.last_name=user.last_name;
        this.password=user.password;
        this.email=user.email;
        this.phone=user.phone;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getFirst_name() {
        return first_name;
    }

    public void setFirst_name(String first_name) {
        this.first_name = first_name;
    }

    public String getLast_name() {
        return last_name;
    }

    public void setLast_name(String last_name) {
        this.last_name = last_name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }   

    public Collection<Role> getRoles() {
        return roles;
    }

    public void setRoles(Collection<Role> roles) {
        this.roles = roles;
    }

    public boolean isEnabled() {
        return enabled;
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }
}

UserService

public interface UserService extends UserDetailsService {

}

UserServiceImpl

@Service
public class UserServiceImpl implements UserService {

    private UserRepo userRepo;

    @Autowired
    public void setUserRepo(UserRepo userRepo) {
        this.userRepo = userRepo;
    }

    @Override
    public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException {
        User user=userRepo.findUserByUsername(username);
        if(user == null) {
            throw new UsernameNotFoundException("Could not find user " + username);
        }
        return new CustomUser(user);
    }

    public final static class CustomUser extends User implements UserDetails
    {
        public CustomUser(User user) {
            super(user);
        }

        @Override
        public Collection<? extends GrantedAuthority> getAuthorities() {
            List<GrantedAuthority> authorities=new ArrayList<GrantedAuthority>();
            List<Role> roles=new ArrayList<Role>(getRoles());

            for(Role role:roles)
                authorities.add(new SimpleGrantedAuthority(role.getRole()));

            return authorities;
        }

        @Override
        public boolean isAccountNonExpired() {
            return true;
        }

        @Override
        public boolean isAccountNonLocked() {
            return true;
        }

        @Override
        public boolean isCredentialsNonExpired() {
            return true;
        }       
    }
}

SecurityConfig

@Configuration
@EnableWebSecurity
@ComponentScan(basePackageClasses=UserServiceImpl.class)
public class SecurityConfig extends WebSecurityConfigurerAdapter{

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth)
            throws Exception {

        auth
            .userDetailsService(userDetailsService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers(HttpMethod.GET, "/","/index","/register","/public/**").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .permitAll()
                .logoutUrl("/logout")
                .logoutSuccessUrl("/");

    }
}

登录失败,出现错误凭据异常。当我使用 jdbcAuthentication()而不是自定义用户服务时,登录工作正常。实际上,我不知道为什么我应该编写实现 UserDetailsS​​ervice 的自定义用户服务。我只是遵循以这种方式编写的教程,而不是jdbcAuthentication()。

有什么建议吗?

的login.jsp

<sf:form role="form" action="login" method="post">
        <c:if test="${param.error != null}">
            <p class="text-danger text-center">Invalid username and password</p>
        </c:if>
        <c:if test="${param.logout != null}">
            <p>You have been logged out</p>
        </c:if>
        <div class="row">
            <div class="col-lg-8 col-lg-offset-2 col-md-8 col-md-offset-2 col-sm-12 col-xs-12">
                <div class="form-group">
                    <label>Username</label>
                    <input type="text" name="username" id="username" class="form-control" placeholder="Enter Username">
                </div>
                <div class="form-group">
                    <label>Password</label>
                    <input type="password" name="password" id="password" class="form-control" placeholder="Enter Password">
                </div>
                <div class="checkbox">
                    <label>
                        <input type="checkbox"> Remember me
                    </label>
                </div>
                <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
            </div>
        </div>
        <div class="row">
            <div class="col-lg-4 col-lg-offset-4 col-md-4 col-md-offset-4 col-sm-4 col-sm-offset-4 col-xs-8 col-xs-offset-2">
                <button type="submit" class="btn btn-primary btn-block"><i class="fa fa-lock"></i> Sign in to Tracker</button>
            </div>
            <div class="text-center col-lg-12 col-md-12 col-sm-12 col-xs-12">
                <a href="#">Forgot Password?</a>
            </div>
        </div>
    </sf:form>

0 个答案:

没有答案