密碼未編碼。它保存為與用戶在登錄時輸入的相同。我嘗試使用 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);
}
}
這是安全配置類。我懷疑錯誤可能只在這個類中
uj5u.com熱心網友回復:
你SecurityConfig的沒問題。
我想你誤解了這里的用法auth.userDetailsService(userDetailsService).passwordEncoder(this.passwordEncoder());
。
此代碼將BCryptPasswordEncoder在授權和身份驗證時應用于密碼,而不是在您將用戶存盤到資料庫時。
在將用戶密碼保存在資料庫中時,您應該手動對其進行編碼。
像這樣的東西:
@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);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/498094.html
