@Override protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception { HttpServletRequest httpRequest = WebUtils.toHttp(request); String jwt = getJSONWebToken(httpRequest); if(jwt == null) { logger.debug("JWT not found, proceeding with the request"); return true; } Subject subject = SecurityUtils.getSubject(); if(subject.isAuthenticated()) { subject.logout(); } try { subject.login(new JSONWebToken(jwt)); return true; } catch (AuthenticationException e) { logger.warn("Failed JWT authentication to " + httpRequest.getRequestURL(), e); HttpServletResponse httpResponse = WebUtils.toHttp(response); httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return false; } }
public AuthenticationInfo loadAuthenticationInfo(JSONWebToken token) { Key key = getJWTKey(); Jwt jwt; try { jwt = Jwts.parser().setSigningKey(key).parse(token.getPrincipal()); } catch (JwtException e) { throw new AuthenticationException(e); } Map body = (Map) jwt.getBody(); String credentials = legacyHashing ? token.getCredentials() : encryptPassword(token.getCredentials()); String base64Principal = (String) body.get("serialized-principal"); byte[] serializedPrincipal = Base64.decode(base64Principal); Object principal; try { ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(serializedPrincipal)); principal = objectInputStream.readObject(); objectInputStream.close(); } catch (Exception e) { throw new AuthenticationException(e); } return new SimpleAuthenticationInfo(principal, credentials, getName()); }
@Override @POST @Produces("application/json") public String login(@FormParam("username") String username, @FormParam("password") String password) throws AuthenticationException { Subject subject = SecurityUtils.getSubject(); if(!subject.isAuthenticated()) try { UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password); usernamePasswordToken.setRememberMe(false); subject.login(usernamePasswordToken); logger.info("User {} login", ShiroUtils.getUserId(subject)); Object principal = subject.getPrincipal(); subject.logout(); PortofinoRealm portofinoRealm = ShiroUtils.getPortofinoRealm(); String jwt = portofinoRealm.generateWebToken(principal); subject.login(new JSONWebToken(jwt)); return userInfo(subject, portofinoRealm, jwt); } catch (AuthenticationException e) { logger.warn("Login failed for '" + username + "': " + e.getMessage(), e); throw new WebApplicationException(Response.Status.UNAUTHORIZED); } return checkJWT(); }