Java Code Examples for io.jsonwebtoken.SignatureAlgorithm

source:http://www.programcreek.com/java-api-examples/index.php?api=io.jsonwebtoken.SignatureAlgorithm


The following are top voted examples for showing how to use io.jsonwebtoken.SignatureAlgorithm. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples. 

Example 1
Project: azure-sdk-for-java   File: TokenRestrictionTemplateSerializer.java View source code 6 votes
public static String generateTestTokenJWT(TokenRestrictionTemplate tokenTemplate, TokenVerificationKey signingKeyToUse,
    UUID keyIdForContentKeyIdentifierClaim, Date tokenExpiration, Date notBefore) {

    SymmetricVerificationKey signingKey = (SymmetricVerificationKey) signingKeyToUse;
    SecretKeySpec secretKey = new SecretKeySpec(signingKey.getKeyValue(), "HmacSHA256");
    
    // Mapping Claims.
    Map<String, Object> claims = new HashMap<String, Object>();
    for (TokenClaim claim : tokenTemplate.getRequiredClaims()) {
        String claimValue = claim.getClaimValue();
        if (claimValue == null && claim.getClaimType().equals(TokenClaim.getContentKeyIdentifierClaimType())) {
            if (keyIdForContentKeyIdentifierClaim == null) {
                throw new IllegalArgumentException(String.format("The 'keyIdForContentKeyIdentifierClaim' parameter cannot be null when the token template contains a required '%s' claim type.", TokenClaim.getContentKeyIdentifierClaimType()));
            }
            claimValue = keyIdForContentKeyIdentifierClaim.toString();
        }
        claims.put(claim.getClaimType(), claimValue);    
    }

    return Jwts.builder()
            .setHeaderParam("typ", "JWT")
            .setClaims(claims)
            .setIssuer(tokenTemplate.getIssuer().toString())
            .setAudience(tokenTemplate.getAudience().toString())
            .setIssuedAt(notBefore)
            .setExpiration(tokenExpiration)
            .signWith(SignatureAlgorithm.HS256, secretKey)
            .compact();
}
 
Example 2
Project: jwt-angular-spring   File: UserController.java View source code 6 votes
@RequestMapping(value = "login", method = RequestMethod.POST)
public LoginResponse login(@RequestBody final UserLogin login)
    throws ServletException {
    if (login.name == null || !userDb.containsKey(login.name)) {
        throw new ServletException("Invalid login");
    }
    return new LoginResponse(Jwts.builder().setSubject(login.name)
        .claim("roles", userDb.get(login.name)).setIssuedAt(new Date())
        .signWith(SignatureAlgorithm.HS256, "secretkey").compact());
}
 
Example 3
Project: stormpath-sdk-java   File: DefaultIdSiteUrlBuilder.java View source code 6 votes
@Override
public String build() {
    Assert.state(Strings.hasText(this.callbackUri), "callbackUri cannot be null or empty.");

    String jti = UUID.randomUUID().toString();

    Date now = new Date();

    final ApiKey apiKey = this.internalDataStore.getApiKey();

    JwtBuilder jwtBuilder = Jwts.builder().setId(jti).setIssuedAt(now).setIssuer(apiKey.getId())
            .setSubject(this.applicationHref).claim(REDIRECT_URI, this.callbackUri);

    if (Strings.hasText(this.path)) {
        jwtBuilder.claim(PATH, this.path);
    }

    if (Strings.hasText(this.state)) {
        jwtBuilder.claim(STATE, this.state);
    }

    if (Strings.hasText(this.organizationNameKey)) {
        jwtBuilder.claim(ORGANIZATION_NAME_KEY, organizationNameKey);
    }

    if (useSubdomain != null) {
        jwtBuilder.claim(USE_SUBDOMAIN, useSubdomain);
    }

    if (showOrganizationField != null) {
        jwtBuilder.claim(SHOW_ORGANIZATION_FIELD, showOrganizationField);
    }

    byte[] secret = apiKey.getSecret().getBytes(Strings.UTF_8);

    String jwt = jwtBuilder.setHeaderParam(JwsHeader.TYPE, JwsHeader.JWT_TYPE).signWith(SignatureAlgorithm.HS256, secret).compact();

    QueryString queryString = new QueryString();
    queryString.put(JWT_REQUEST, jwt);

    StringBuilder urlBuilder = new StringBuilder(ssoEndpoint);

    if (logout) {
        urlBuilder.append(SSO_LOGOUT_SUFFIX);
    }

    return urlBuilder.append('?').append(queryString.toString()).toString();
}
 
Example 4
Project: stormpath-sdk-java   File: JwtSigningKeyResolver.java View source code 6 votes
/**
 * Inspects the request and authentication result and returns a cryptographic signature key that will be used to
 * digitally sign a JWT using the specified {@code alg}orithm.  The JWT will represent the authenticated account.
 *
 * 

This method implementation MUST return the exact same signing key as what is returned by {@link * #getSigningKey(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, * io.jsonwebtoken.JwsHeader, io.jsonwebtoken.Claims)}.

* * @param request the inbound request * @param response the outbound response * @param result the result for which an account JWT will be created * @param alg the JWT signature algorithm that will be used to generate the JWT * @return a cryptographic signature key that will be used to digitally sign a JWT using the specified {@code * alg}orithm. */
Key getSigningKey(HttpServletRequest request, HttpServletResponse response, AuthenticationResult result, SignatureAlgorithm alg);
Example 5
Project: stormpath-sdk-java   File: DefaultJwtSigningKeyResolver.java View source code 6 votes
@Override
public Key getSigningKey(HttpServletRequest request, HttpServletResponse response, AuthenticationResult result,
                         SignatureAlgorithm alg) {
    Assert.isTrue(!alg.isRsa(), RSA_ERR_MSG);
    Assert.isTrue(!alg.isEllipticCurve(), EC_ERR_MSG);
    return getSigningKey(request, alg);
}
 
Example 6
Project: stormpath-sdk-java   File: DefaultJwtSigningKeyResolver.java View source code 6 votes
protected Key getSigningKey(HttpServletRequest request, SignatureAlgorithm alg) {

        Client client = (Client) request.getAttribute(Client.class.getName());
        Assert.notNull(client, "Client must be accessible as a request attribute.");

        String apiKeySecret = client.getApiKey().getSecret();

        //Stormpath API Keys are base-64-encoded secure random byte arrays:
        byte[] apiKeySecretBytes = Base64.decodeBase64(apiKeySecret);

        return new SecretKeySpec(apiKeySecretBytes, alg.getJcaName());

    }
 
Example 7
Project: spark-jwt-auth   File: JwtTokenServiceImpl.java View source code 6 votes
public String tokenGenerator(String username, String password) {


        SignatureAlgorithm hs512 = SignatureAlgorithm.HS512;


        String token = Jwts.builder()
                .claim("username", username)
                .claim("password", password)
                        //Todo:Config
                .claim("expireTime", currentTime.getCurrentTime() + Constant.TOKEN_TIMEOUT_INMILISECOND)
                .signWith(hs512, Constant.JWT_SECRET)
                .compact();

        return token;
    }
 
Example 8
Project: jjwt   File: DefaultJwtBuilder.java View source code 6 votes
@Override
public JwtBuilder signWith(SignatureAlgorithm alg, byte[] secretKey) {
    Assert.notNull(alg, "SignatureAlgorithm cannot be null.");
    Assert.notEmpty(secretKey, "secret key byte array cannot be null or empty.");
    Assert.isTrue(alg.isHmac(), "Key bytes may only be specified for HMAC signatures.  If using RSA or Elliptic Curve, use the signWith(SignatureAlgorithm, Key) method instead.");
    this.algorithm = alg;
    this.keyBytes = secretKey;
    return this;
}
 
Example 9
Project: jjwt   File: DefaultJwtBuilder.java View source code 6 votes
@Override
public JwtBuilder signWith(SignatureAlgorithm alg, String base64EncodedSecretKey) {
    Assert.hasText(base64EncodedSecretKey, "base64-encoded secret key cannot be null or empty.");
    Assert.isTrue(alg.isHmac(), "Base64-encoded key bytes may only be specified for HMAC signatures.  If using RSA or Elliptic Curve, use the signWith(SignatureAlgorithm, Key) method instead.");
    byte[] bytes = TextCodec.BASE64.decode(base64EncodedSecretKey);
    return signWith(alg, bytes);
}
 
Example 10
Project: jjwt   File: DefaultJwtBuilder.java View source code 6 votes
@Override
public JwtBuilder signWith(SignatureAlgorithm alg, Key key) {
    Assert.notNull(alg, "SignatureAlgorithm cannot be null.");
    Assert.notNull(key, "Key argument cannot be null.");
    this.algorithm = alg;
    this.key = key;
    return this;
}
 
Example 11
Project: jjwt   File: DefaultSignatureValidatorFactory.java View source code 6 votes
@Override
public SignatureValidator createSignatureValidator(SignatureAlgorithm alg, Key key) {
    Assert.notNull(alg, "SignatureAlgorithm cannot be null.");
    Assert.notNull(key, "Signing Key cannot be null.");

    switch (alg) {
        case HS256:
        case HS384:
        case HS512:
            return new MacValidator(alg, key);
        case RS256:
        case RS384:
        case RS512:
        case PS256:
        case PS384:
        case PS512:
            return new RsaSignatureValidator(alg, key);
        case ES256:
        case ES384:
        case ES512:
            return new EllipticCurveSignatureValidator(alg, key);
        default:
            throw new IllegalArgumentException("The '" + alg.name() + "' algorithm cannot be used for signing.");
    }
}

你可能感兴趣的:(笔记)