I\'m working on a java spring boot project which I\'m trying to get spring security set up for user authentication with JWT, the tutorial I\'m following(and also many tutori
public class MyUserDetails implements UserDetails {
/**
*
*/
private static final long serialVersionUID = 1L;
private User user;
public MyUserDetails(User user) {
this.user = user;
}
@Override
public String getUsername() {
return user.getLogin();
}
@Override
public String getPassword() {
return user.getPassword();
}
@Override
public Collection extends GrantedAuthority> getAuthorities() {
return user.getGrantedAuthorities();
}
@Override
public boolean isAccountNonExpired() {
return user.getActivated();
}
@Override
public boolean isAccountNonLocked() {
return user.getActivated();
}
@Override
public boolean isCredentialsNonExpired() {
return user.getActivated();
}
@Override
public boolean isEnabled() {
return user.getActivated();
}
}
public class JWTFilter extends GenericFilterBean {
private TokenProvider tokenProvider;
public JWTFilter(TokenProvider tokenProvider) {
this.tokenProvider = tokenProvider;
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
String jwt = resolveToken(httpServletRequest);
if (StringUtils.hasText(jwt) && this.tokenProvider.validateToken(jwt)) {
Authentication authentication = this.tokenProvider.getAuthentication(jwt);
SecurityContextHolder.getContext().setAuthentication(authentication);
}
filterChain.doFilter(servletRequest, servletResponse);
}
private String resolveToken(HttpServletRequest request){
String bearerToken1 = RequestUtil.getTokenFromHeader(request);
if (bearerToken1 != null) return bearerToken1;
String jwt = request.getParameter(JWTConfigurer.AUTHORIZATION_TOKEN);
if (StringUtils.hasText(jwt)) {
return jwt;
}
return null;
}
}
@Component("userDetailsService")
public class DomainUserDetailsService implements UserDetailsService {
private final Logger log = LoggerFactory.getLogger(DomainUserDetailsService.class);
private final UserRepository userRepository;
public DomainUserDetailsService(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Override
@Transactional
public UserDetails loadUserByUsername(final String login) {
log.debug("Authenticating {}", login);
String lowercaseLogin = login.toLowerCase(Locale.ENGLISH);
Optional userByLoginFromDatabase = userRepository.findOneWithRolesByLogin(lowercaseLogin);
return userByLoginFromDatabase.map(user -> new MyUserDetails(user))
.orElseThrow(() -> new UsernameNotFoundException("User " + lowercaseLogin + " was not found in the database"));
}
}