Receive jwt in Java functions

Asked

Viewed 194 times

0

Good morning guys, I am with the following doubt, I created a java login function that validates user and password in a login request, if the login is successful it returns a jwt, I take this jwt and save in my front end and send to the back end each request, How do I now receive this jwt in my functions to be able to verify that users are actually validated? I’ve already created the function that validates jwt I’m just not getting it when it comes in the request header

1 answer

1


An authentication filter needs to be created. This filter will be called every time a request arrives in your backend.

@Protected
@Provider
@Priority(Priorities.AUTHENTICATION)
public class AuthenticationFilter implements ContainerRequestFilter {

private static final String AUTHORIZATION_PREFIX = "Bearer ";

@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
    String authorizationHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);

    if(authorizationHeader == null || !authorizationHeader.startsWith(AUTHORIZATION_PREFIX)) {
        throw new NotAuthorizedException("Usuário não logado"); //se não existe o header, lança uma exceção
    }

    String token = authorizationHeader.substring(AUTHORIZATION_PREFIX.length()).trim();

    try {
        //aqui você chamada o seu método de validação
        validateToken(token);
    } catch (Exception e) {
        //caso não consiga validar, aborte a conexão com um status correspondente ao erro
        requestContext.abortWith(Response.status(Response.Status.FORBIDDEN).build());
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.