Search in sources :

Example 91 with Algorithm

use of com.auth0.jwt.Algorithm in project cryptography by norkator.

the class JWT method verifyECDSA256Jwt.

/**
 * Verify elliptic curve based JWT
 *
 * @param publicPem of key pair
 * @param issuer    party name
 * @param token     of created jwt
 * @return DecodedJWT including claims
 * @throws JWTVerificationException thrown if verification fails
 */
public static DecodedJWT verifyECDSA256Jwt(String publicPem, String issuer, final String token) throws JWTVerificationException, InvalidKeySpecException, NoSuchAlgorithmException {
    ECKey publicKey = (ECKey) PEMToKey.getPemPublicKey(publicPem, "ECDSA");
    Algorithm algorithm = Algorithm.ECDSA256(publicKey);
    JWTVerifier verifier = com.auth0.jwt.JWT.require(algorithm).withIssuer(issuer).build();
    return verifier.verify(token);
}
Also used : ECKey(java.security.interfaces.ECKey) Algorithm(com.auth0.jwt.algorithms.Algorithm) JWTVerifier(com.auth0.jwt.JWTVerifier)

Example 92 with Algorithm

use of com.auth0.jwt.Algorithm in project Minecraft-Server-WebStore by Ba1oretto.

the class JwtUtils method verity.

/**
 * 校验token
 * @return boolean
 */
public static boolean verity() {
    HttpServletRequest request = SpringContextUtils.getHttpServletRequest();
    // 从请求头部中获取token信息
    String token = request.getHeader(HEADER_KEY);
    if (StringUtils.isBlank(token)) {
        return false;
    }
    if (!token.startsWith(PREFIX)) {
        CommonUtils.throwRuntimeException(StatusEnum.WRONG_PREFIX);
    }
    token = token.replace(PREFIX, "");
    try {
        Algorithm algorithm = Algorithm.HMAC256(SECRET);
        JWTVerifier verifier = JWT.require(algorithm).build();
        DecodedJWT jwt = verifier.verify(token);
        if (null == jwt) {
            return false;
        }
        // 判断过期时间
        long time = (jwt.getExpiresAt().getTime() - System.currentTimeMillis());
        // 有效期只有不到60分钟,需要刷新token了
        if (REFRESH_TIME > time) {
            String newToken = createToken(jwt.getClaim(UUID).asString());
            // 将新的token放入响应请求头中
            SpringContextUtils.getHttpServletResponse().setHeader(HEADER_KEY, newToken);
        }
        return true;
    } catch (Exception e) {
        log.error("token verified error, {}", e.getMessage());
    }
    return false;
}
Also used : HttpServletRequest(jakarta.servlet.http.HttpServletRequest) Algorithm(com.auth0.jwt.algorithms.Algorithm) JWTVerifier(com.auth0.jwt.JWTVerifier) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT)

Example 93 with Algorithm

use of com.auth0.jwt.Algorithm in project actframework by actframework.

the class JWTTest method fromAuth0.

private String fromAuth0() throws Exception {
    JWTCreator.Builder builder = com.auth0.jwt.JWT.create();
    builder.withIssuer(ISSUER);
    builder.withExpiresAt(new Date(EXPIRE_AT * 1000l));
    builder.withJWTId(TOKEN_ID);
    builder.withClaim(KEY_USERNAME, USERNAME);
    Algorithm algorithm = Algorithm.HMAC256(SECRET);
    return builder.sign(algorithm);
}
Also used : JWTCreator(com.auth0.jwt.JWTCreator) Algorithm(com.auth0.jwt.algorithms.Algorithm) Date(java.util.Date)

Example 94 with Algorithm

use of com.auth0.jwt.Algorithm in project foundation-java by soffalabs.

the class DefaultJwtProcessor method decode.

@Override
public Optional<Authentication> decode(String token, ClaimsExtractor claimsExtractor) {
    try {
        Algorithm algorithm = Algorithm.HMAC256(config.getSecret());
        JWTVerifier verifier = JWT.require(algorithm).withIssuer(config.getIssuer()).build();
        DecodedJWT jwt = verifier.verify(token);
        Map<String, Claim> baseClaims = jwt.getClaims();
        Map<String, Object> claims = new HashMap<>();
        for (Map.Entry<String, Claim> entry : baseClaims.entrySet()) {
            claims.put(entry.getKey(), entry.getValue().asString());
        }
        return Optional.of(claimsExtractor.extractInfo(new Jwt(token, jwt.getSubject(), claims)));
    } catch (Exception e) {
        LOG.error(e);
        return Optional.empty();
    }
}
Also used : HashMap(java.util.HashMap) Algorithm(com.auth0.jwt.algorithms.Algorithm) JWTVerifier(com.auth0.jwt.JWTVerifier) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Map(java.util.Map) HashMap(java.util.HashMap) Claim(com.auth0.jwt.interfaces.Claim)

Example 95 with Algorithm

use of com.auth0.jwt.Algorithm in project open-kilda by telstra.

the class PathVerificationService method generateVerificationPacket.

public OFPacketOut generateVerificationPacket(IOFSwitch srcSw, OFPort port, IOFSwitch dstSw, boolean sign) {
    try {
        OFPortDesc ofPortDesc = srcSw.getPort(port);
        byte[] chassisId = new byte[] { 4, 0, 0, 0, 0, 0, 0 };
        byte[] portId = new byte[] { 2, 0, 0 };
        byte[] ttlValue = new byte[] { 0, 0x78 };
        byte[] dpidTLVValue = new byte[] { 0x0, 0x26, (byte) 0xe1, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
        LLDPTLV dpidTLV = new LLDPTLV().setType((byte) 127).setLength((short) dpidTLVValue.length).setValue(dpidTLVValue);
        byte[] dpidArray = new byte[8];
        ByteBuffer dpidBB = ByteBuffer.wrap(dpidArray);
        ByteBuffer portBB = ByteBuffer.wrap(portId, 1, 2);
        DatapathId dpid = srcSw.getId();
        dpidBB.putLong(dpid.getLong());
        System.arraycopy(dpidArray, 2, chassisId, 1, 6);
        // Set the optionalTLV to the full SwitchID
        System.arraycopy(dpidArray, 0, dpidTLVValue, 4, 8);
        byte[] zeroMac = { 0, 0, 0, 0, 0, 0 };
        byte[] srcMac = ofPortDesc.getHwAddr().getBytes();
        if (Arrays.equals(srcMac, zeroMac)) {
            int portVal = ofPortDesc.getPortNo().getPortNumber();
            // this is a common scenario
            logger.debug("Port {}/{} has zero hardware address: overwrite with lower 6 bytes of dpid", dpid.toString(), portVal);
            System.arraycopy(dpidArray, 2, srcMac, 0, 6);
        }
        portBB.putShort(port.getShortPortNumber());
        VerificationPacket vp = new VerificationPacket();
        vp.setChassisId(new LLDPTLV().setType((byte) 1).setLength((short) chassisId.length).setValue(chassisId));
        vp.setPortId(new LLDPTLV().setType((byte) 2).setLength((short) portId.length).setValue(portId));
        vp.setTtl(new LLDPTLV().setType((byte) 3).setLength((short) ttlValue.length).setValue(ttlValue));
        vp.getOptionalTLVList().add(dpidTLV);
        // Add the controller identifier to the TLV value.
        // vp.getOptionalTLVList().add(controllerTLV);
        // Add T0 based on format from Floodlight LLDP
        long time = System.currentTimeMillis();
        long swLatency = srcSw.getLatency().getValue();
        byte[] timestampTLVValue = ByteBuffer.allocate(Long.SIZE / 8 + 4).put((byte) 0x00).put((byte) 0x26).put((byte) 0xe1).put(// 0x01 is what we'll use to differentiate DPID (0x00) from time (0x01)
        (byte) 0x01).putLong(time + swLatency).array();
        LLDPTLV timestampTLV = new LLDPTLV().setType((byte) 127).setLength((short) timestampTLVValue.length).setValue(timestampTLVValue);
        vp.getOptionalTLVList().add(timestampTLV);
        // Type
        byte[] typeTLVValue = ByteBuffer.allocate(Integer.SIZE / 8 + 4).put((byte) 0x00).put((byte) 0x26).put((byte) 0xe1).put((byte) 0x02).putInt(PathType.ISL.ordinal()).array();
        LLDPTLV typeTLV = new LLDPTLV().setType((byte) 127).setLength((short) typeTLVValue.length).setValue(typeTLVValue);
        vp.getOptionalTLVList().add(typeTLV);
        if (sign) {
            String token = JWT.create().withClaim("dpid", dpid.getLong()).withClaim("ts", time + swLatency).sign(algorithm);
            byte[] tokenBytes = token.getBytes(Charset.forName("UTF-8"));
            byte[] tokenTLVValue = ByteBuffer.allocate(4 + tokenBytes.length).put((byte) 0x00).put((byte) 0x26).put((byte) 0xe1).put((byte) 0x03).put(tokenBytes).array();
            LLDPTLV tokenTLV = new LLDPTLV().setType((byte) 127).setLength((short) tokenTLVValue.length).setValue(tokenTLVValue);
            vp.getOptionalTLVList().add(tokenTLV);
        }
        MacAddress dstMac = MacAddress.of(VERIFICATION_BCAST_PACKET_DST);
        if (dstSw != null) {
            OFPortDesc sw2OfPortDesc = dstSw.getPort(port);
            dstMac = sw2OfPortDesc.getHwAddr();
        }
        Ethernet l2 = new Ethernet().setSourceMACAddress(MacAddress.of(srcMac)).setDestinationMACAddress(dstMac).setEtherType(EthType.IPv4);
        IPv4Address dstIp = IPv4Address.of(VERIFICATION_PACKET_IP_DST);
        if (dstSw != null) {
            dstIp = IPv4Address.of(((InetSocketAddress) dstSw.getInetAddress()).getAddress().getAddress());
        }
        IPv4 l3 = new IPv4().setSourceAddress(IPv4Address.of(((InetSocketAddress) srcSw.getInetAddress()).getAddress().getAddress())).setDestinationAddress(dstIp).setTtl((byte) 64).setProtocol(IpProtocol.UDP);
        UDP l4 = new UDP();
        l4.setSourcePort(TransportPort.of(VERIFICATION_PACKET_UDP_PORT));
        l4.setDestinationPort(TransportPort.of(VERIFICATION_PACKET_UDP_PORT));
        l2.setPayload(l3);
        l3.setPayload(l4);
        l4.setPayload(vp);
        byte[] data = l2.serialize();
        OFPacketOut.Builder pob = srcSw.getOFFactory().buildPacketOut().setBufferId(OFBufferId.NO_BUFFER).setActions(getDiscoveryActions(srcSw, port)).setData(data);
        OFMessageUtils.setInPort(pob, OFPort.CONTROLLER);
        return pob.build();
    } catch (Exception exception) {
        logger.error("error generating verification packet: {}", exception);
    }
    return null;
}
Also used : UDP(net.floodlightcontroller.packet.UDP) InetSocketAddress(java.net.InetSocketAddress) IPv4(net.floodlightcontroller.packet.IPv4) DatapathId(org.projectfloodlight.openflow.types.DatapathId) MacAddress(org.projectfloodlight.openflow.types.MacAddress) ByteBuffer(java.nio.ByteBuffer) IPv4Address(org.projectfloodlight.openflow.types.IPv4Address) OFPacketOut(org.projectfloodlight.openflow.protocol.OFPacketOut) UnsupportedEncodingException(java.io.UnsupportedEncodingException) JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) FloodlightModuleException(net.floodlightcontroller.core.module.FloodlightModuleException) OFPortDesc(org.projectfloodlight.openflow.protocol.OFPortDesc) OFPortDescPropEthernet(org.projectfloodlight.openflow.protocol.OFPortDescPropEthernet) Ethernet(net.floodlightcontroller.packet.Ethernet) LLDPTLV(net.floodlightcontroller.packet.LLDPTLV)

Aggregations

Algorithm (com.auth0.jwt.algorithms.Algorithm)206 Test (org.junit.Test)160 DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)90 JWTVerifier (com.auth0.jwt.JWTVerifier)79 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)79 ECDSAAlgorithmTest (com.auth0.jwt.algorithms.ECDSAAlgorithmTest)61 Date (java.util.Date)57 ECDSAKeyProvider (com.auth0.jwt.interfaces.ECDSAKeyProvider)51 RSAPublicKey (java.security.interfaces.RSAPublicKey)36 ECPublicKey (java.security.interfaces.ECPublicKey)34 RSAKeyProvider (com.auth0.jwt.interfaces.RSAKeyProvider)31 IOException (java.io.IOException)30 JWTCreator (com.auth0.jwt.JWTCreator)28 JWTVerificationException (com.auth0.jwt.exceptions.JWTVerificationException)25 ECPrivateKey (java.security.interfaces.ECPrivateKey)23 RSAPrivateKey (java.security.interfaces.RSAPrivateKey)21 HashMap (java.util.HashMap)17 UnsupportedEncodingException (java.io.UnsupportedEncodingException)16 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)15 JsonObject (com.google.gson.JsonObject)15