use of com.auth0.jwt.Algorithm in project Taier by DTStack.
the class TokenService method encryptionWithOutExpire.
public String encryptionWithOutExpire(Long userId, String username, Long tenantId) {
Objects.requireNonNull(userId);
Objects.requireNonNull(username);
try {
Algorithm algorithm = Algorithm.HMAC256(JWT_TOKEN);
JWTCreator.Builder builder = JWT.create();
builder.withClaim(DTToken.USER_ID, String.valueOf(userId)).withClaim(DTToken.USER_NAME, username);
// 若存在租户id,则增加租户id信息
if (Objects.nonNull(tenantId)) {
builder.withClaim(DTToken.TENANT_ID, String.valueOf(tenantId));
}
return builder.sign(algorithm);
} catch (UnsupportedEncodingException e) {
throw new RdosDefineException("dtToken生成异常.", e);
}
}
use of com.auth0.jwt.Algorithm in project sda-dropwizard-commons by SDA-SE.
the class AuthBuilder method buildToken.
/**
* @return the signed and encoded token, e.g. {@code eyXXX.eyYYY.ZZZ}
*/
public String buildToken() {
Algorithm algorithm = Algorithm.RSA256(null, privateKey);
JWTCreator.Builder builder = JWT.create().withKeyId(keyId).withIssuer(issuer).withSubject(subject);
claims.keySet().forEach(key -> {
Object value = claims.get(key);
if (value instanceof String) {
builder.withClaim(key, (String) value);
} else if (value instanceof Long) {
builder.withClaim(key, (Long) value);
} else if (value instanceof Integer) {
builder.withClaim(key, (Integer) value);
} else if (value instanceof Double) {
builder.withClaim(key, (Double) value);
} else if (value instanceof Date) {
builder.withClaim(key, (Date) value);
} else if (value instanceof Boolean) {
builder.withClaim(key, (Boolean) value);
} else if (value instanceof String[]) {
builder.withArrayClaim(key, (String[]) value);
} else if (value instanceof Long[]) {
builder.withArrayClaim(key, (Long[]) value);
} else if (value instanceof Integer[]) {
builder.withArrayClaim(key, (Integer[]) value);
}
});
return builder.sign(algorithm);
}
use of com.auth0.jwt.Algorithm in project gravitee-api-management by gravitee-io.
the class AbstractAuthenticationResource method connectUserInternal.
protected Response connectUserInternal(UserEntity user, final String state, final HttpServletResponse servletResponse, final String accessToken, final String idToken) {
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
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 management or portal role
Set<RoleEntity> userRoles = membershipService.getRoles(MembershipReferenceType.ORGANIZATION, GraviteeContext.getCurrentOrganization(), MembershipMemberType.USER, userDetails.getId());
if (!userRoles.isEmpty()) {
userRoles.forEach(role -> authorities.add(Maps.<String, String>builder().put("authority", role.getScope().toString() + ':' + role.getName()).build()));
}
// JWT signer
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 token = JWT.create().withIssuer(environment.getProperty("jwt.issuer", DEFAULT_JWT_ISSUER)).withIssuedAt(issueAt).withExpiresAt(Date.from(expireAt)).withSubject(user.getId()).withClaim(JWTHelper.Claims.PERMISSIONS, authorities).withClaim(JWTHelper.Claims.EMAIL, user.getEmail()).withClaim(JWTHelper.Claims.FIRSTNAME, user.getFirstname()).withClaim(JWTHelper.Claims.LASTNAME, user.getLastname()).withJWTId(UUID.randomUUID().toString()).sign(algorithm);
final TokenEntity tokenEntity = new TokenEntity();
tokenEntity.setType(BEARER);
tokenEntity.setToken(token);
if (idToken != null) {
tokenEntity.setAccessToken(accessToken);
tokenEntity.setIdToken(idToken);
}
if (state != null && !state.isEmpty()) {
tokenEntity.setState(state);
}
final Cookie bearerCookie = cookieGenerator.generate(TokenAuthenticationFilter.AUTH_COOKIE_NAME, "Bearer%20" + token);
servletResponse.addCookie(bearerCookie);
return Response.ok(tokenEntity).build();
}
use of com.auth0.jwt.Algorithm in project gravitee-api-management by gravitee-io.
the class CurrentUserResource method login.
@POST
@Path("/login")
@ApiOperation(value = "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 Map<String, Object> claims = new HashMap<>();
claims.put(Claims.ISSUER, environment.getProperty("jwt.issuer", DEFAULT_JWT_ISSUER));
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 management or portal role
Set<RoleEntity> roles = membershipService.getRoles(MembershipReferenceType.ORGANIZATION, GraviteeContext.getCurrentOrganization(), MembershipMemberType.USER, userDetails.getUsername());
if (!roles.isEmpty()) {
roles.forEach(role -> authorities.add(Maps.<String, String>builder().put("authority", role.getScope().toString() + ':' + role.getName()).build()));
}
this.environmentService.findByOrganization(GraviteeContext.getCurrentOrganization()).stream().flatMap(env -> membershipService.getRoles(MembershipReferenceType.ENVIRONMENT, env.getId(), MembershipMemberType.USER, userDetails.getUsername()).stream()).filter(Objects::nonNull).forEach(role -> authorities.add(Maps.<String, String>builder().put("authority", role.getScope().toString() + ':' + role.getName()).build()));
// JWT signer
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 token = JWT.create().withIssuer(environment.getProperty("jwt.issuer", DEFAULT_JWT_ISSUER)).withIssuedAt(issueAt).withExpiresAt(Date.from(expireAt)).withSubject(userDetails.getUsername()).withClaim(JWTHelper.Claims.PERMISSIONS, authorities).withClaim(JWTHelper.Claims.EMAIL, userDetails.getEmail()).withClaim(JWTHelper.Claims.FIRSTNAME, userDetails.getFirstname()).withClaim(JWTHelper.Claims.LASTNAME, userDetails.getLastname()).withJWTId(UUID.randomUUID().toString()).sign(algorithm);
final TokenEntity tokenEntity = new TokenEntity();
tokenEntity.setType(BEARER);
tokenEntity.setToken(token);
final Cookie bearerCookie = cookieGenerator.generate(TokenAuthenticationFilter.AUTH_COOKIE_NAME, "Bearer%20" + token);
servletResponse.addCookie(bearerCookie);
return ok(tokenEntity).build();
}
return ok().build();
}
use of com.auth0.jwt.Algorithm in project gravitee-api-management by gravitee-io.
the class OAuth2AuthenticationResourceTest method verifyJwtToken.
private void verifyJwtToken(Response response) throws NoSuchAlgorithmException, InvalidKeyException, IOException, SignatureException, JWTVerificationException {
TokenEntity responseToken = response.readEntity(TokenEntity.class);
assertEquals("BEARER", responseToken.getType().name());
String token = responseToken.getToken();
Algorithm algorithm = Algorithm.HMAC256("myJWT4Gr4v1t33_S3cr3t");
JWTVerifier jwtVerifier = JWT.require(algorithm).build();
DecodedJWT jwt = jwtVerifier.verify(token);
assertEquals(jwt.getSubject(), "janedoe@example.com");
assertEquals(jwt.getClaim("firstname").asString(), "Jane");
assertEquals(jwt.getClaim("iss").asString(), "gravitee-management-auth");
assertEquals(jwt.getClaim("sub").asString(), "janedoe@example.com");
assertEquals(jwt.getClaim("email").asString(), "janedoe@example.com");
assertEquals(jwt.getClaim("lastname").asString(), "Doe");
}
Aggregations