sexta-feira, 3 de fevereiro de 2017

JSON Web Token, Security for applications


JSON Web Token called JWT, is an open standard RFC 7519 that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. 
Each information can be verified and trusted because it is digitally signed. 
JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA.

Some importants concepts:
  • Compact: JWTs can be sent through a URL, POST parameter, or inside an HTTP header. 
  • Self-contained: The payload contains all the required information about the user, avoiding the need to query the database more than once.

When should you use JSON Web Tokens:
  • Authentication: This is the most common scenario for using JWT. Once the user is logged in, each subsequent request will include the JWT, allowing the user to access routes, services, and resources that are permitted with that token. 
  • Information Exchange: JSON Web Tokens are a good way of securely transmitting information between parties, because as they can be signed, for example using public/private key pairs, you can be sure that the senders are who they say they are. 

JWT Structure:

A complete JWT is represented something like this:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjEzODY4OTkxMzEsImlzcyI6ImppcmE6MTU0ODk1OTUiLCJxc2giOiI4MDYzZmY0Y2ExZTQxZGY3YmM5MGM4YWI2ZDBmNjIwN2Q0OTFjZjZkYWQ3YzY2ZWE3OTdiNDYxNGI3MTkyMmU5IiwiaWF0IjoxMzg2ODk4OTUxfQ.uKqU9dTB6gKwG6jQCuXYAiMNdfNRw98Hw_IWuA5MaMo

This token could be sliced in 3 parts:

Header:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.

Payload:
eyJleHAiOjEzODY4OTkxMzEsImlzcyI6ImppcmE6MTU0ODk1OTUiLCJxc2giOiI4MDYzZmY0Y2ExZTQxZGY3YmM5MGM4YWI2ZDBmNjIwN2Q0OTFjZjZkYWQ3YzY2ZWE3OTdiNDYxNGI3MTkyMmU5IiwiaWF0IjoxMzg2ODk4OTUxfQ.

Signature:
uKqU9dTB6gKwG6jQCuXYAiMNdfNRw98Hw_IWuA5MaMo

Each part is separated by “.” 
<base64url-encoded header>.<base64url-encoded claims>.<base64url-encoded signature>

Here one simple sample of the flow to authentication of User to access a API Server.














I did two samples with JWT, first with main method call some others method to create token and another with Spring Boot call some rest operations.

First Example: 
This dependency below should be added in build.gradle 
dependencies {
    compile 'io.jsonwebtoken:jjwt:0.7.0'
}



public class PocAutorizationApplication {

private final String key"teste";

public static void main(String[] args) {
PocAutorizationApplication poc = new PocAutorizationApplication();
poc.desCompactJws(poc.compactJws(new User("user", "password").toString()));
}

public String compactJws(String user) {
String compactJws = Jwts.builder()
.setSubject(user)
.signWith(SignatureAlgorithm.HS512, key)
.compact();

System.out.println("compactJws = "+compactJws);

return compactJws;
}

public String desCompactJws(String compactJws) {
String desCompactJws = Jwts.parser()
.setSigningKey(key)
.parseClaimsJws(compactJws)
.getBody()
.getSubject();
System.out.println("desCompactJws = "+ desCompactJws);
return desCompactJws;
}

}


The second sample is a POC with JWT and Spring Boot, where I created some filters to check token on Header and I put some validations to Token.(I put just importants code parts)

dependencies {
compile('org.springframework.boot:spring-boot-starter-web')
compile group: 'org.apache.httpcomponents', name: 'httpclient', version: '4.5.2'
compile 'io.jsonwebtoken:jjwt:0.7.0'
testCompile('org.springframework.boot:spring-boot-starter-test')
}

Operations:
  • Login return Token and put Token in Header
  • User get use and pass by Header na decompact token
  • Validation is check if Token is valid
  • Users is to list users available

    @RestController
    public class UserService {
    @Autowired
    private Authentication authentication;
    @Autowired
    private UserBuilder userBuilder;
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(HttpServletResponse response,@RequestBody User user) throws IOException {
    System.out.println(user);
    String token = authentication.compactJws(new ObjectMapper().writeValueAsString(user));
    response.setHeader("X-Auth-Token", token);
    return token ;
    }

    @RequestMapping(value = "/user", method = RequestMethod.GET)
    public String user(HttpServletRequest request) throws IOException {
    System.out.println(request.getHeader("X-Auth-Token"));
    return authentication.desCompactJws(request.getHeader("X-Auth-Token"));
    }

    @RequestMapping(value = "/validation/token", method = RequestMethod.POST)
    public boolean validationToken(HttpServletRequest request) throws IOException {
    return true;
    }
    @RequestMapping(value = "/users", method = RequestMethod.POST)
    public List<User> listUsers(HttpServletRequest request,HttpServletResponse response) throws Exception {
    return userBuilder.users;
    }
    }

    Class to compact  and decompact.

    @Component
    public class Authentication {
    private final String key = "teste";
    private final int TEMPO_MAX_SESSAO=10;
    public String compactJws(String user) {
    String compactJws = Jwts.builder()
    .setSubject(user)
    .signWith(SignatureAlgorithm.HS512, key)
    .compact();

    System.out.println("compactJws = " + compactJws);
    return compactJws;
    }

    public String desCompactJws(String compactJws) {
    String desCompactJws = "";
    try{
    desCompactJws = Jwts.parser()
    .setSigningKey(key)
    .parseClaimsJws(compactJws)
    .getBody()
    .getSubject();
    System.out.println("desCompactJws = " + desCompactJws);
    }catch (MalformedJwtException e) {
    return "Invalid Token";
    }
    return desCompactJws;
    }
    }

    Filter class to check if operation is different from login, should check if contains token in header and user/password are valid.

    @Component
    public class AuthFilter implements Filter{

    @Autowired
    private Authentication authentication;

    @Autowired
    private UserBuilder userBuilder;

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    if(request.getRequestURI().contains("login")) {
    chain.doFilter(request, response);
    return;
    }
    try {
    if(getToken(request.getHeader("X-Auth-Token"))){
    response.setHeader("X-Auth-Token", request.getHeader("X-Auth-Token"));
    chain.doFilter(request, response);
    return;
    }
    response.sendError(HttpStatus.UNAUTHORIZED.value());
    } catch (Exception e) {
    e.printStackTrace();
    response.sendError(HttpStatus.UNAUTHORIZED.value());
    }
    }
    private boolean getToken(String token) throws Exception{
    if(token != null && !token.isEmpty() && validationToken(token))
    return true

    return false;
    }

    private boolean validationToken(String token) throws JsonParseException, JsonMappingException, IOException {
    String user = authentication.desCompactJws(token);

    if(user.equals("Invalid Token")) return false;

    User outnew ObjectMapper().readValue(user, User.class);

    Optional<User> userValid = userBuilder.users.stream().
    filter(x-> x.getUser().equals(out.getUser())&& x.getPass().equals(out.getPass()))
    .findFirst();

    return userValid.isPresent();
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }



    @Override
    public void destroy() {
    }

    }


    References:
  • https://auth0.com/blog/securing-spring-boot-with-jwts
  • https://jwt.io
  • https://github.com/salerno-rafael/spring-boot-jwt

Nenhum comentário:

Postar um comentário