spring-security 密码未在Spring Security中编码

gdx19jrr  于 2022-11-11  发布在  Spring
关注(0)|答案(1)|浏览(166)

密码没有被编码。它被保存为与用户登录时输入的密码相同。我已经尝试使用BCryptPasswordEncoder,但它不起作用。似乎我在某处犯了错误。请帮助!

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    @Autowired
    private JwtAuthenticationEntryPoint unauthorizedHandler;

    /**
     * Password Encoder Bean
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * Authentication Manager Bean.
     * It is required for login process
     */
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Autowired
    private JwtAuthenticationFilter jwtAuthenticationFilter;

    /**
     * Method for configuring the authentication service based on user details
     * provided
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(this.passwordEncoder());
    }

    /**
     * Method for configuring HTTP requests for the application
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                .antMatchers("/generate-token").permitAll()
                .antMatchers(HttpMethod.POST).permitAll()
                .antMatchers(HttpMethod.OPTIONS).permitAll()
                .anyRequest().authenticated().and().exceptionHandling().authenticationEntryPoint(unauthorizedHandler)
                .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        // Check JWT authentication token before any request
        http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }
}

这是安全配置类。我怀疑错误可能只在这个类中出现

mfpqipee

mfpqipee1#

你的SecurityConfig没问题。
我想你误解了这里auth.userDetailsService(userDetailsService).passwordEncoder(this.passwordEncoder());的用法。
此代码将在授权和身份验证时对密码应用BCryptPasswordEncoder,而不是在将用户存储到DB中时。
在数据库上保存用户密码时,您应该手动对用户密码进行编码。
大概是这样的:

@Autowired
private BCryptPasswordEncoder passwordEncoder;

public User registerNewUserAccount(UserDto accountDto) throws EmailExistsException {
    if (emailExist(accountDto.getEmail())) {
        throw new EmailExistsException(
          "There is an account with that email adress:" + accountDto.getEmail());
    }
    User user = new User();
    user.setFirstName(accountDto.getFirstName());
    user.setLastName(accountDto.getLastName());

    // Encoding user's password:
    user.setPassword(passwordEncoder.encode(accountDto.getPassword()));

    user.setEmail(accountDto.getEmail());
    user.setRole(new Role(Integer.valueOf(1), user));
    return repository.save(user);
}

相关问题