Solucionado (ver solução)
Solucionado
(ver solução)
8
respostas

Bad Credentials ao enviar póst no /auth

Estou tomando erro 400 de bad credentials ao tentar autenticar o form de autenticaco passando pelo metodo authenticate da classe AuthenticationManager. Alguma ideia do motivo, professor? obrigado

8 respostas

Oi Bruno,

Posta aqui o código das suas classes AutenticacaoController, SecurityConfigurations e AutenticacaoViaTokenFilter para a gente entender melhor qual pode ser o problema.

Não consegui encontrar o problema, mas olha só , eu baixei o projeto da aula 6 e tentei testar no postman uma chamada post no /auth passando o mesmo usuario e senha no body e tbm retornou erro 400. Acha que pode ser alguma configuração minha? qual poderia ser? Obrigado

abaixo o codigo das classes:

import java.io.IOException;

import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;

import org.springframework.web.filter.OncePerRequestFilter;

public class AutenticacaoViaTokenFilter extends OncePerRequestFilter {

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
        throws ServletException, IOException {

    String token = recuperarToken(request);


    filterChain.doFilter(request, response);

}

private String recuperarToken(HttpServletRequest request) {
    String token = request.getHeader("Authorization");
    if (token == null || token.isEmpty() || !token.startsWith("Bearer ")) {

        return null;
    }

    return token.substring(7,token.length());
}

}

package com.casamassa.alura.forum.config.security;

import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@EnableWebSecurity @Configuration public class SecurityConfigurations extends WebSecurityConfigurerAdapter {

@Autowired
private AuthService autenticacaoService;

@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
}

//Configuracoes de autenticacao
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(autenticacaoService).passwordEncoder(new BCryptPasswordEncoder());
}


// config de autorização
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
    .antMatchers(HttpMethod.GET,"/topics").permitAll()
    .antMatchers(HttpMethod.GET,"/topics/*").permitAll()
    .antMatchers(HttpMethod.POST,"/auth*").permitAll()
    .anyRequest().authenticated() //autenticação para todos os nao configurados a cima
    .and().csrf().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);


    //cross site request forgery ataque hacker quando cria sessao (auth será stateless entao nao precisa desse step)
}

// config de recursos estaticos(js,css, imagens)
@Override
public void configure(WebSecurity web) throws Exception {
    // TODO Auto-generated method stub
    super.configure(web);
}

}

package com.casamassa.alura.forum.controller;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.web.bind.annotation.*;

import com.casamassa.alura.forum.config.security.TokenService; import com.casamassa.alura.forum.controller.dto.TokenDto; import com.casamassa.alura.forum.controller.form.LoginForm;

@RestController @RequestMapping("/auth") public class AuthController {

@Autowired
private TokenService tokenService;

@Autowired
private AuthenticationManager authManager;

@PostMapping
public ResponseEntity<TokenDto> autenticar(@RequestBody @Valid LoginForm form) {
    System.out.println(form.getEmail());
    System.out.println(form.getSenha());

    UsernamePasswordAuthenticationToken dadosLogin = form.converter();

    System.out.println(dadosLogin.getName());
    System.out.println(dadosLogin.getCredentials());
    try {

        Authentication auth = authManager.authenticate(dadosLogin);

        String token = tokenService.generateToken(auth);
        System.out.println(token);

        return ResponseEntity.ok().build();
    } catch (BadCredentialsException be) {

        System.out.println(be.getLocalizedMessage() + "\n------");
        System.out.println(be.getStackTrace() + "\n------");
        System.out.println(be.getMessage() + "\n------");
        System.out.println(be.getCause() + "\n------");
        return ResponseEntity.badRequest().build();

    }

    catch (Exception e) {
        System.out.println(e.getMessage());

        return ResponseEntity.badRequest().build();
    }

}

}

Não consegui encontrar o problema, mas olha só , eu baixei o projeto da aula 6 e tentei testar no postman uma chamada post no /auth passando o mesmo usuario e senha no body e tbm retornou erro 400. Acha que pode ser alguma configuração minha? qual poderia ser?

Oi Bruno,

A princípio o único problema que vi foi o mapeamento da url:

.antMatchers(HttpMethod.POST, "/auth*").permitAll()

Remova esse asterisco, deixando assim:

.antMatchers(HttpMethod.POST, "/auth").permitAll()

Veja se é esse o problema. Se não for, posta aqui o que está saindo no console do eclipse.

Esta é a exception que caio , é quando tento instanciar o Authentication pelo metodo authenticate do authManager

org.springframework.security.authentication.BadCredentialsException: Bad credentials at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:141) at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:182) at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:201) at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter$AuthenticationManagerDelegator.authenticate(WebSecurityConfigurerAdapter.java:518) at com.casamassa.alura.forum.controller.AuthController.autenticar(AuthController.java:38) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:567) at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:197) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:141) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:893) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:807) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1061) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:961) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909) at javax.servlet.http.HttpServlet.service(HttpServlet.java:652) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) at javax.servlet.http.HttpServlet.service(HttpServlet.java:733) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:327) at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:115) at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:81) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:119) at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:126) at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:81) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:105) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:149) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFi

Oi Bruno,

Pela exception aconteceu Bad Credentials, ou seja, usuario/senha inválidos.

Verifique os dados que você enviou se estão corretos e se estão chegando certinhos no controller.

solução!

Opa professor, consegui reoslver, o problema era a database que nao havia atualizado, obrigado :)