Receiving jwt in Java functions

0

Hi, I have a java login function that validates username and password in a login request. If the login is successful it returns a jwt, I get this jwt and I keep it my front end and sending it to the back end of each request, how do I now to receive this jwt in my functions to be able to verify if the users are really validated? I have already created the function that validates the jwt only I am not able to get it when it comes in the request header

    
asked by anonymous 30.05.2017 / 14:11

1 answer

1

An authentication filter needs to be created. This filter will be called every time a request arrives on 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());
    }
}
    
30.05.2017 / 14:48