Search in sources :

Example 6 with Algorithm

use of com.auth0.jwt.Algorithm in project gravitee-api-management by gravitee-io.

the class AuthResource method login.

@POST
@Path("/login")
@Produces(MediaType.APPLICATION_JSON)
public Response login(@Context final javax.ws.rs.core.HttpHeaders headers, @Context final HttpServletResponse servletResponse) {
    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication != null && authentication.getPrincipal() instanceof UserDetails) {
        // JWT signer
        final UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        // Manage authorities, initialize it with dynamic permissions from the IDP
        List<Map<String, String>> authorities = userDetails.getAuthorities().stream().map(authority -> Maps.<String, String>builder().put("authority", authority.getAuthority()).build()).collect(Collectors.toList());
        // We must also load permissions from repository for configured environment role
        Set<RoleEntity> userRoles = membershipService.getRoles(MembershipReferenceType.ENVIRONMENT, GraviteeContext.getCurrentEnvironment(), MembershipMemberType.USER, userDetails.getId());
        if (!userRoles.isEmpty()) {
            userRoles.forEach(role -> authorities.add(Maps.<String, String>builder().put("authority", role.getScope().toString() + ':' + role.getName()).build()));
        }
        Algorithm algorithm = Algorithm.HMAC256(environment.getProperty("jwt.secret"));
        Date issueAt = new Date();
        Instant expireAt = issueAt.toInstant().plus(Duration.ofSeconds(environment.getProperty("jwt.expire-after", Integer.class, DEFAULT_JWT_EXPIRE_AFTER)));
        final String sign = JWT.create().withIssuer(environment.getProperty("jwt.issuer", DEFAULT_JWT_ISSUER)).withIssuedAt(issueAt).withExpiresAt(Date.from(expireAt)).withSubject(userDetails.getUsername()).withClaim(Claims.PERMISSIONS, authorities).withClaim(Claims.EMAIL, userDetails.getEmail()).withClaim(Claims.FIRSTNAME, userDetails.getFirstname()).withClaim(Claims.LASTNAME, userDetails.getLastname()).withJWTId(UUID.randomUUID().toString()).sign(algorithm);
        final Token tokenEntity = new Token();
        tokenEntity.setTokenType(TokenTypeEnum.BEARER);
        tokenEntity.setToken(sign);
        final Cookie bearerCookie = cookieGenerator.generate("Bearer%20" + sign);
        servletResponse.addCookie(bearerCookie);
        return ok(tokenEntity).build();
    }
    return ok().build();
}
Also used : JWT(com.auth0.jwt.JWT) java.util(java.util) Produces(javax.ws.rs.Produces) Path(javax.ws.rs.Path) Autowired(org.springframework.beans.factory.annotation.Autowired) GraviteeContext(io.gravitee.rest.api.service.common.GraviteeContext) Algorithm(com.auth0.jwt.algorithms.Algorithm) CookieGenerator(io.gravitee.rest.api.security.cookies.CookieGenerator) ConfigurableEnvironment(org.springframework.core.env.ConfigurableEnvironment) Claims(io.gravitee.rest.api.service.common.JWTHelper.Claims) Duration(java.time.Duration) Cookie(javax.servlet.http.Cookie) SecurityContextHolder(org.springframework.security.core.context.SecurityContextHolder) MembershipMemberType(io.gravitee.rest.api.model.MembershipMemberType) POST(javax.ws.rs.POST) Context(javax.ws.rs.core.Context) HttpServletResponse(javax.servlet.http.HttpServletResponse) OAuth2AuthenticationResource(io.gravitee.rest.api.portal.rest.resource.auth.OAuth2AuthenticationResource) Token(io.gravitee.rest.api.portal.rest.model.Token) TokenTypeEnum(io.gravitee.rest.api.portal.rest.model.Token.TokenTypeEnum) Instant(java.time.Instant) UserDetails(io.gravitee.rest.api.idp.api.authentication.UserDetails) Collectors(java.util.stream.Collectors) Maps(io.gravitee.common.util.Maps) RoleEntity(io.gravitee.rest.api.model.RoleEntity) DEFAULT_JWT_ISSUER(io.gravitee.rest.api.service.common.JWTHelper.DefaultValues.DEFAULT_JWT_ISSUER) MembershipReferenceType(io.gravitee.rest.api.model.MembershipReferenceType) MediaType(io.gravitee.common.http.MediaType) Response(javax.ws.rs.core.Response) ResourceContext(javax.ws.rs.container.ResourceContext) Response.ok(javax.ws.rs.core.Response.ok) DEFAULT_JWT_EXPIRE_AFTER(io.gravitee.rest.api.service.common.JWTHelper.DefaultValues.DEFAULT_JWT_EXPIRE_AFTER) Authentication(org.springframework.security.core.Authentication) Cookie(javax.servlet.http.Cookie) Instant(java.time.Instant) Token(io.gravitee.rest.api.portal.rest.model.Token) Algorithm(com.auth0.jwt.algorithms.Algorithm) RoleEntity(io.gravitee.rest.api.model.RoleEntity) UserDetails(io.gravitee.rest.api.idp.api.authentication.UserDetails) Authentication(org.springframework.security.core.Authentication) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces)

Example 7 with Algorithm

use of com.auth0.jwt.Algorithm in project cx-flow by checkmarx-ltd.

the class GitHubAppAuthService method getJwt.

private String getJwt(String appId) {
    // Check if current token is set and if it is verified
    LocalDateTime currentDateTime = LocalDateTime.now(ZoneOffset.UTC);
    if (this.jwt != null) {
        DecodedJWT decodedJwt = JWT.decode(this.jwt);
        Instant currentTime = currentDateTime.plusMinutes(1).toInstant(ZoneOffset.UTC);
        if (currentTime.isBefore(decodedJwt.getExpiresAt().toInstant())) {
            return this.jwt;
        }
    }
    // If the jwt was null or expired, we hit this block to create new
    // 10 minutes in future
    LocalDateTime exp = currentDateTime.plusMinutes(10);
    assert this.privateKey != null;
    Algorithm algorithm = Algorithm.RSA256(null, this.privateKey);
    // set the current token and return it
    this.jwt = JWT.create().withIssuer(appId).withIssuedAt(Date.from(currentDateTime.toInstant(ZoneOffset.UTC))).withExpiresAt(Date.from(exp.toInstant(ZoneOffset.UTC))).sign(algorithm);
    return this.jwt;
}
Also used : LocalDateTime(java.time.LocalDateTime) Instant(java.time.Instant) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Algorithm(com.auth0.jwt.algorithms.Algorithm)

Example 8 with Algorithm

use of com.auth0.jwt.Algorithm in project Team_Ahpuh_Surf_BE by prgrms-web-devcourse.

the class Jwt method sign.

public String sign(final Claims claims) {
    final Date now = new Date();
    final JWTCreator.Builder builder = com.auth0.jwt.JWT.create();
    builder.withIssuer(issuer);
    builder.withIssuedAt(now);
    if (expirySeconds > 0) {
        builder.withExpiresAt(new Date(now.getTime() + expirySeconds * 1_000L));
    }
    builder.withClaim("user_id", claims.userId);
    builder.withClaim("email", claims.email);
    builder.withArrayClaim("roles", claims.roles);
    return builder.sign(algorithm);
}
Also used : JWTCreator(com.auth0.jwt.JWTCreator) Date(java.util.Date)

Example 9 with Algorithm

use of com.auth0.jwt.Algorithm in project cyberduck by iterate-ch.

the class CryptoVault method create.

public synchronized Path create(final Session<?> session, final VaultCredentials credentials, final PasswordStore keychain, final int version) throws BackgroundException {
    final Host bookmark = session.getHost();
    if (credentials.isSaved()) {
        try {
            keychain.addPassword(String.format("Cryptomator Passphrase (%s)", bookmark.getCredentials().getUsername()), new DefaultUrlProvider(bookmark).toUrl(masterkey).find(DescriptiveUrl.Type.provider).getUrl(), credentials.getPassword());
        } catch (LocalAccessDeniedException e) {
            log.error(String.format("Failure %s saving credentials for %s in password store", e, bookmark));
        }
    }
    final String passphrase = credentials.getPassword();
    final ByteArrayOutputStream mkArray = new ByteArrayOutputStream();
    final Masterkey mk = Masterkey.generate(FastSecureRandomProvider.get().provide());
    final MasterkeyFileAccess access = new MasterkeyFileAccess(pepper, FastSecureRandomProvider.get().provide());
    final MasterkeyFile masterkeyFile;
    try {
        access.persist(mk, mkArray, passphrase, version);
        masterkeyFile = MasterkeyFile.read(new StringReader(new String(mkArray.toByteArray(), StandardCharsets.UTF_8)));
    } catch (IOException e) {
        throw new VaultException("Failure creating master key", e);
    }
    if (log.isDebugEnabled()) {
        log.debug(String.format("Write master key to %s", masterkey));
    }
    // Obtain non encrypted directory writer
    final Directory directory = session._getFeature(Directory.class);
    final TransferStatus status = new TransferStatus();
    final Encryption encryption = session.getFeature(Encryption.class);
    if (encryption != null) {
        status.setEncryption(encryption.getDefault(home));
    }
    final Path vault = directory.mkdir(home, status);
    new ContentWriter(session).write(masterkey, mkArray.toByteArray());
    if (VAULT_VERSION == version) {
        // Create vaultconfig.cryptomator
        final Algorithm algorithm = Algorithm.HMAC256(mk.getEncoded());
        final String conf = JWT.create().withJWTId(new UUIDRandomStringService().random()).withKeyId(String.format("masterkeyfile:%s", masterkey.getName())).withClaim("format", version).withClaim("cipherCombo", CryptorProvider.Scheme.SIV_CTRMAC.toString()).withClaim("shorteningThreshold", CryptoFilenameV7Provider.NAME_SHORTENING_THRESHOLD).sign(algorithm);
        new ContentWriter(session).write(config, conf.getBytes(StandardCharsets.US_ASCII));
    }
    this.open(masterkeyFile, passphrase);
    final Path secondLevel = directoryProvider.toEncrypted(session, home.attributes().getDirectoryId(), home);
    final Path firstLevel = secondLevel.getParent();
    final Path dataDir = firstLevel.getParent();
    if (log.isDebugEnabled()) {
        log.debug(String.format("Create vault root directory at %s", secondLevel));
    }
    directory.mkdir(dataDir, status);
    directory.mkdir(firstLevel, status);
    directory.mkdir(secondLevel, status);
    return vault;
}
Also used : VaultException(ch.cyberduck.core.vault.VaultException) MasterkeyFileAccess(org.cryptomator.cryptolib.common.MasterkeyFileAccess) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) Algorithm(com.auth0.jwt.algorithms.Algorithm) DefaultUrlProvider(ch.cyberduck.core.shared.DefaultUrlProvider) Masterkey(org.cryptomator.cryptolib.api.Masterkey) StringReader(java.io.StringReader) TransferStatus(ch.cyberduck.core.transfer.TransferStatus) MasterkeyFile(org.cryptomator.cryptolib.common.MasterkeyFile) LocalAccessDeniedException(ch.cyberduck.core.exception.LocalAccessDeniedException)

Example 10 with Algorithm

use of com.auth0.jwt.Algorithm in project JustLive-Android by guyijie1211.

the class DanmuUtils method getWebSocketJwtParamsMap.

/**
 * 生成开放API Websocket连接参数
 * @param appId  开发者ID(https://ext.huya.com成为开发者后自动生成)
 * @param secret 开发者密钥(https://ext.huya.com成为开发者后自动生成)
 * @param roomId 要监听主播的房间号
 * @return
 */
public static Map<String, Object> getWebSocketJwtParamsMap(String appId, String secret, long roomId) {
    // 获取时间戳(毫秒)
    long currentTimeMillis = System.currentTimeMillis();
    // 超时时间:通常设置10分钟有效,即exp=iat+600,注意不少于当前时间且不超过当前时间60分钟
    long expireTimeMillis = System.currentTimeMillis() + 10 * 60 * 1000;
    Date iat = new Date(currentTimeMillis);
    Date exp = new Date(expireTimeMillis);
    try {
        Map<String, Object> header = new HashMap<String, Object>();
        header.put("alg", "HS256");
        header.put("typ", "JWT");
        // 生成JWT凭证
        // 开发者密钥
        Algorithm algorithm = Algorithm.HMAC256(secret);
        String sToken = JWT.create().withHeader(// JWT声明
        header).withIssuedAt(// jwt凭证生成时间
        iat).withExpiresAt(// jwt凭证超时时间
        exp).withClaim("appId", // 开发者ID
        appId).sign(algorithm);
        Map<String, Object> authMap = new HashMap<String, Object>();
        // jwt凭证生成时间戳(秒)
        authMap.put("iat", currentTimeMillis / 1000);
        // jwt凭证超时时间戳(秒)
        authMap.put("exp", expireTimeMillis / 1000);
        // jwt签名串
        authMap.put("sToken", sToken);
        // 开发者ID
        authMap.put("appId", appId);
        // 接口默认参数
        authMap.put("do", "comm");
        // 需要监听主播的房间号
        authMap.put("roomId", roomId);
        return authMap;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
Also used : HashMap(java.util.HashMap) JSONObject(com.alibaba.fastjson.JSONObject) ByteString(okio.ByteString) Algorithm(com.auth0.jwt.algorithms.Algorithm) Date(java.util.Date) DataFormatException(java.util.zip.DataFormatException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

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