У меня простая проблема для вас, ребята.Я сталкиваюсь с проблемой, что всегда получаю ответ 404, если я реализую Spring Security в своем приложении Spring Boot.
Я отлаживал весь код и просто обнаружил, что путь перенаправления всегда "/", а невызываемый URL.
Например,
call localhost:8080/user/login/
-> Spring Security check given credentials
-> they are correct
-> resolve given path
-> SOMETHING STANGES HAPPENS HERE (Refer to figure (1))
-> resolve path to "/" and not "/user/login/"
-> Therefore I get the response 404 NOT FOUND because it returns the wrong path
Режим отладки - defineTargetUrl -> this.targetUrlParameter не установлен, и поэтому targetUrl будет равен «/» ине real targetUrl "/ user / login /".Код показан на рисунке (1).
рисунок (1) Класс Spring Secutiry - AbstractAuthenticationTargetUrlRequestHandler
MyКод с Spring Security
WebSecurityConfig
@EnableWebSecurity
открытый класс WebSecurityConfig расширяет WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors()
.disable()
.csrf()
.disable()
.authorizeRequests()
.antMatchers(HttpMethod.POST, "/user/login/").permitAll()
.antMatchers(HttpMethod.GET, "/user/secret/**").permitAll()
.and()
.addFilterBefore(new JWTLoginFilter("/user/login/", authenticationManager()), UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(new JWTAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
}
}
JWTLoginFilter
public class JWTLoginFilter extends AbstractAuthenticationProcessingFilter {
public JWTLoginFilter(String url, AuthenticationManager authManager) {
super(new AntPathRequestMatcher(url));
setAuthenticationManager(authManager);
}
@Override
public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res) throws AuthenticationException, IOException, ServletException {
User user = new ObjectMapper().readValue(req.getInputStream(), User.class);
Optional<User> dbUser = SpringContextBridge.services().getUserRepository().findUserByEmail(user.getEmail());
dbUser.ifPresent(us -> user.setPassword(SecretGenerator.generateSha256(user.getPassword(), us.getSecret())));
return getAuthenticationManager()
.authenticate(new UsernamePasswordAuthenticationToken(user.getEmail(), user.getPassword(), Collections.emptyList())
);
}
}
JWTAuthenticationFilter
public class JWTAuthenticationFilter extends GenericFilterBean {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
Authentication authentication = TokenAuthenticationService.getAuthentication((HttpServletRequest) request);
SecurityContextHolder.getContext().setAuthentication(authentication);
filterChain.doFilter(request, response);
}
}
UserDetailsServiceImpl
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
private UserRepository userRepository;
@Autowired
public void setUserRepository(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
Optional<User> user = userRepository.findUserByEmail(email);
if (!user.isPresent()) {
throw new UserNotFoundException("User with email: " + email + " not found");
}
return new org.springframework.security.core.userdetails.User(user.get().getEmail(), user.get().getPassword(), Collections.emptyList());
}
}
Может быть, кто-то может помочьменя!