Я пытаюсь настроить приложение SpringBoot на JWT, и каждый раз, когда я пытаюсь выполнить аутентификацию, используя мой JWTAuthenticationFilter.class, я получаю исключение для неверных учетных данных. Я чувствую, что вся проблема в результате Bycrpt, потому что переходя по этой ссылке , пользователь жаловался на ту же проблему. но когда я реализовал его код, он не работал для меня.
ниже - мой класс настройки безопасности Spring:
@EnableGlobalMethodSecurity(prePostEnabled = true)
// @ Configuration
@EnableWebSecurity
открытый класс JwtSecurityConfiguration расширяет WebSecurityConfigurerAdapter {
private final CustomerDetailsService customerDetailsService;
@Autowired
private JwtAuthenticationEntryPoint unauthorizedHandler;
@Autowired
public JwtSecurityConfiguration(CustomerDetailsService customerDetailsService) {
this.customerDetailsService = customerDetailsService;
}
@Autowired
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/resources/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/welcome/login").permitAll()
.antMatchers("**/rest/**").authenticated()
.and()
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler)
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(new JWTAuthenticationFilter(authenticationManager(),
(BCryptPasswordEncoder) passwordEncoder()), UsernamePasswordAuthenticationFilter.class);
http.addFilter(new JWTAuthorizationFilter(authenticationManager(),customerDetailsService));
http
.headers()
.frameOptions().sameOrigin()
.cacheControl();
}
}
а это класс JWTAuthenticationFiler:
public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
private AuthenticationManager authenticationManager;
@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
public JWTAuthenticationFilter(AuthenticationManager authenticationManager, BCryptPasswordEncoder bCryptPasswordEncoder) {
this.authenticationManager = authenticationManager;
this.bCryptPasswordEncoder = bCryptPasswordEncoder;
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
try {
User user = new ObjectMapper().readValue(request.getInputStream(), User.class);
user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword()));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
ZonedDateTime expirationTimeUTC = ZonedDateTime.now(ZoneOffset.UTC).plus(EXPIRATION_TIME, ChronoUnit.MILLIS);
String token = Jwts.builder().setSubject(((User)authResult.getPrincipal()).getUserName())
.setExpiration(Date.from(expirationTimeUTC.toInstant()))
.signWith(SignatureAlgorithm.ES256, SECRET)
.compact();
response.getWriter().write(token);
response.addHeader(HEADER, TOKEN_PREFIX + token);
}
@Override
protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
super.unsuccessfulAuthentication(request, response, failed);
response.getWriter().write(failed.getMessage());
}
}
и, наконец, это мой класс обслуживания клиентов:
@Component
public class CustomerDetailsService implements UserDetailsService {
@Autowired
DefaultUserDAOService defaultUserDAOService;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = defaultUserDAOService.getByUsername(username);
if (user == null) {
throw new UsernameNotFoundException(String.format("No user found with username '%s'.", username));
} else {
return new org.springframework.security.core.userdetails.User(user.getUserName(), user.getPassword(),
AuthorityUtils.createAuthorityList("ROLE_USER"));
}
}
} * * тысяча двадцать-один