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();
}
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;
}
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);
}
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;
}
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;
}
Aggregations