2
respostas

Pedindo Autorização em URLS permitidas | Em Kotlin

Boa tarde,

O Endpoint /auth está pedindo autorização, nesse caso não deveria ser permitido?

Segue abaixo minhas classes de autenticação.

-- Classe AutenticacaoViaToken

class AutenticacaoViaTokenFilter: OncePerRequestFilter() {

    override fun doFilterInternal(request: HttpServletRequest, response: HttpServletResponse, filter: FilterChain) {
        val token: String? = recuperarToken(request)
        filter.doFilter(request,response)
    }

    private fun recuperarToken(request: HttpServletRequest): String? {
        val token: String = request.getHeader("Authorization")
        if(ObjectUtils.isEmpty(token) || !token.startsWith("Bearer ")){
            return null
        }
        return token.substring(7, token.length)
    }
}

--SecurityConfiguration

@EnableWebSecurity
@Configuration
class SecurityConfiguration: WebSecurityConfigurerAdapter() {

    @Autowired
    lateinit var autenticacaoService: AutenticacaoService

    @Override
    @Bean
    override fun authenticationManager(): AuthenticationManager {
        return super.authenticationManager()
    }
   //Configurações de Autenticação
    override fun configure(auth: AuthenticationManagerBuilder?) {
        auth!!.userDetailsService(this.autenticacaoService).passwordEncoder(BCryptPasswordEncoder())
    }
    //Configuração de Autorização, URLS, diferenciar se é Stateless
    override fun configure(http: HttpSecurity?) {
        http!!.authorizeRequests()
                .antMatchers(HttpMethod.POST, "/auth").permitAll()
                .anyRequest().authenticated()
                .and()
                .csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .addFilterBefore(AutenticacaoViaTokenFilter()
                        ,UsernamePasswordAuthenticationFilter::class.java)
    }

    //Configuração de Recursos Estáticos css,imagens
    override fun configure(web: WebSecurity?) {
    }
}
2 respostas

Oi Nilton,

Como você fez o teste?

O código está correto, sendo que talvez tenha pedido autenticação se você disparou a requisição via método GET ao invés de POST.

Dessa maneira está dando 403

curl --location --request POST 'http://localhost:8080/auth' \
--header 'Content-Type: application/json' \
--data-raw '{
    "email":"nilton@gmail.com",
    "senha":"123456"
}'

Contudo ao inserir o Header, com qualquer valor após o Bearer ele me retorna o token.

curl --location --request POST 'http://localhost:8080/auth' \
--header 'Authorization: Bearer  asas' \
--header 'Content-Type: application/json' \
--data-raw '{
    "email":"nilton@gmail.com",
    "senha":"123456"
}'
{
    "token": "eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJBUEkgbmdCb29rIiwic3ViIjoiMSIsImlhdCI6MTU5NjI5OTU1OCwiZXhwIjoxNTk2Mjk5NTU4fQ.ybw158LQBbBn7KY2dFP6ePa5-4OEi3WeI1c5_VnlJig",
    "tipo": "Bearer"
}

Segue tmb o link no github https://github.com/njguilhem2/ecommerce-ngbook/tree/develop/src/main

está no package authorization

Quer mergulhar em tecnologia e aprendizagem?

Receba a newsletter que o nosso CEO escreve pessoalmente, com insights do mercado de trabalho, ciência e desenvolvimento de software