Solucionado (ver solução)
Solucionado
(ver solução)
1
resposta

Resposta quando usuário ou senha são inválidos

Bom dia, ao consumir a API, quando insiro usuário e senha válidos recebo na api os dados esperados, porém, quando insiro dados inválidos, geram duas mensagem de resposta, conforme abaixo, o que dificulta tratar para enviar uma mensagem de retorno ao usuário.

zone-evergreen.js:2952 POST http://localhost:8080/auth 400
scheduleTask @ zone-evergreen.js:2952
scheduleTask @ zone-evergreen.js:378
onScheduleTask @ zone-evergreen.js:272
scheduleTask @ zone-evergreen.js:372
scheduleTask @ zone-evergreen.js:211
scheduleMacroTask @ zone-evergreen.js:234
scheduleMacroTaskWithCurrentZone @ zone-evergreen.js:1107
(anonymous) @ zone-evergreen.js:2985
proto.<computed> @ zone-evergreen.js:1428
(anonymous) @ http.js:2078
_trySubscribe @ Observable.js:42
subscribe @ Observable.js:28
subscribeToResult @ subscribeToResult.js:9
_innerSub @ mergeMap.js:59
_tryNext @ mergeMap.js:53
_next @ mergeMap.js:36
next @ Subscriber.js:49
(anonymous) @ subscribeToArray.js:3
_trySubscribe @ Observable.js:42
subscribe @ Observable.js:28
call @ mergeMap.js:21
subscribe @ Observable.js:23
call @ filter.js:13
subscribe @ Observable.js:23
call @ map.js:16
subscribe @ Observable.js:23
(anonymous) @ login.service.ts:20
ZoneAwarePromise @ zone-evergreen.js:876
login @ login.service.ts:18
(anonymous) @ login.page.ts:34
(anonymous) @ tslib.es6.js:73
ZoneAwarePromise @ zone-evergreen.js:876
__awaiter @ tslib.es6.js:69
login @ login.page.ts:24
eval @ LoginPage.html:15
handleEvent @ core.js:38098
callWithDebugContext @ core.js:39716
debugHandleEvent @ core.js:39352
dispatchEvent @ core.js:25818
(anonymous) @ core.js:27715
schedulerFn @ core.js:31094
__tryOrUnsub @ Subscriber.js:183
next @ Subscriber.js:122
_next @ Subscriber.js:72
next @ Subscriber.js:49
next @ Subject.js:39
emit @ core.js:31013
onSubmit @ forms.js:5324
eval @ LoginPage.html:15
handleEvent @ core.js:38098
callWithDebugContext @ core.js:39716
debugHandleEvent @ core.js:39352
dispatchEvent @ core.js:25818
(anonymous) @ core.js:37030
(anonymous) @ platform-browser.js:1789
invokeTask @ zone-evergreen.js:391
onInvokeTask @ core.js:34182
invokeTask @ zone-evergreen.js:390
runTask @ zone-evergreen.js:168
invokeTask @ zone-evergreen.js:465
invokeTask @ zone-evergreen.js:1603
globalZoneAwareCallback @ zone-evergreen.js:1629
Button.handleClick @ ion-button_2-ios.entry.js:47
Show 33 more frames
core.js:9110 ERROR HttpErrorResponse {headers: HttpHeaders, status: 400, statusText: "OK", url: "http://localhost:8080/auth", ok: false, …}

Como retornar uma mensagem amigável em json?

1 resposta
solução!

Oi Alcimar,

Você vai precisar criar uma classe para tratamento do erro e personalização da resposta, e depois precisa configurar o Spring Security para utilizar essa classe:

public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException { 
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Acesso negado!");
    }
}
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
        .antMatchers(HttpMethod.GET, "/topicos").permitAll()
        .antMatchers(HttpMethod.GET, "/topicos/*").permitAll()
        .antMatchers(HttpMethod.POST, "/auth").permitAll()
        .antMatchers(HttpMethod.GET, "/actuator/**").permitAll()
        .anyRequest().authenticated()
        .and().csrf().disable()
        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and().addFilterBefore(new AutenticacaoViaTokenFilter(tokenService, usuarioRepository), UsernamePasswordAuthenticationFilter.class)
        .exceptionHandling().authenticationEntryPoint(new JwtAuthenticationEntryPoint());
    }