【问题标题】:SpringWebSecurity: Bad Credentials for missing reasonSpringWebSecurity:由于缺少原因而导致凭证错误
【发布时间】:2016-07-25 18:11:00
【问题描述】:

我有一个基于 SpringSecurity 的非常简单的身份验证系统,与 here 的发现非常相似(有点复杂)。

尽管如此,当我执行登录过程时,SpringSecurity 根据其配置抛出一个 Bad Credentials 错误。

查看代码,我找不到原因,因为在运行时用户名、密码、启用和角色是根据数据库中存储的内容。因此,我认为它可能源于错误的配置或逻辑问题。

根据日志,唯一可能失败的是:WARNING: Encoded password does not look like BCrypt,但我读到每次身份验证都可以正常。

有人可以帮我检查配置吗?谢谢!!

package com.company.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class AppSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    @Qualifier("userDetailsService")
    UserDetailsService userDetailsService;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}

@Bean
public PasswordEncoder passwordEncoder() {
    PasswordEncoder encoder = new BCryptPasswordEncoder();
    return encoder;
}


@Override
protected void configure(HttpSecurity http) throws Exception {

    http.authorizeRequests()
            .antMatchers("**/admin/**").access("hasAnyRole('ROLE_ADMIN','ROLE_SUPERADMIN')")
            .antMatchers("/superadmin/**").access("hasRole('ROLE_SUPERADMIN')")
            .antMatchers("**/user/**").access("hasAnyRole('ROLE_USER','ROLE_ADMIN','ROLE_SUPERADMIN')")
            .antMatchers("/resources/**").permitAll()
            .antMatchers("/messages/**").permitAll() 
            .and()
            .formLogin()
                .loginPage("/login")
                .usernameParameter("username")
                .passwordParameter("password")
                .defaultSuccessUrl("/user/home")
                .failureUrl("/403")
                .permitAll()
            .and()
                .exceptionHandling().accessDeniedPage("/403")
            .and()
                .logout().logoutUrl("/logout")
            .and()
                .csrf().disable();
    }
}

package com.company.service.impl;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.company.dao.UsuarioDao;
import com.company.model.UserRole;
import com.company.model.Usuario;

@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService{

    @Autowired
    private UsuarioDao usuarioDao;


    @Transactional(readOnly=true)
    public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException {

        Usuario usuario = usuarioDao.findByChave(username);
        List<GrantedAuthority> authorities = buildUserAuthority(usuario.getUserRole());

        return buildUserForAuthentication(usuario, authorities);

    }

    private User buildUserForAuthentication(Usuario user, 
        List<GrantedAuthority> authorities) {

        User usr= new User(user.getUsername(), user.getPassword(), 
            user.isEnabled(), true, true, true, authorities);

        System.out.println(usr.toString());
/*
* Prints: org.springframework.security.core.userdetails.User@ae6e27ef: 
* Username: SMITH; Password: [PROTECTED]; Enabled: true; 
* AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: 
* true; Not granted any authorities
*/

        return usr;

    }

    private List<GrantedAuthority> buildUserAuthority(Set<UserRole> userRoles){

        Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>();

        // Build user's authorities
        for (UserRole userRole : userRoles) {
            setAuths.add(new SimpleGrantedAuthority(userRole.getRole()));
        }

        List<GrantedAuthority> Result = new ArrayList<GrantedAuthority>(setAuths);

        return Result;  
    }

}

【问题讨论】:

  • 如果您收到该消息,则表示您从数据库收到的信息不是预期的,因为密码不是预期的。检查编码,字段长度...检查实际值...显然您没有存储正确的哈希,这就是该消息告诉您的内容。
  • @M.Deinum,发现问题。如果您想查看答案,我认为它很有价值。感谢您的关注。

标签: spring spring-security


【解决方案1】:

经过一番研究,我发现了这个问题。我正在处理第三方提供的已经加密的密码。因此,我将它直接存储在 DB 中,而 SpringSecurity 使用它自己的加密 (BCrypt)。因此,SpringSecurity 比较了两个不同的加密字符串,从而产生了问题(问题中提到的 WARNING 消息中给出了一个很好的提示)。

这样,我在 AppSecurityConfig 中禁用了@Bean PasswordEncoder,因为没有必要保留它(记住我已经在处理预先加密的密码了)。之后,一切正常。

有关更多信息,请查看以下问题和答案:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-04
    • 2020-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-23
    相关资源
    最近更新 更多