use of com.auth0.android.jwt.JWT in project Taier by DTStack.
the class TokenService method decryption.
public DTToken decryption(String tokenText) {
Assert.notNull(tokenText, "JWT Token Text can't blank.");
try {
/**
* 验证
*/
DecodedJWT jwt = JWT.require(Algorithm.HMAC256(JWT_TOKEN)).build().verify(tokenText);
DTToken token = new DTToken();
token.setUserName(jwt.getClaim(DTToken.USER_NAME).asString());
token.setUserId(Long.parseLong(jwt.getClaim(DTToken.USER_ID).asString()));
if (!jwt.getClaim(DTToken.TENANT_ID).isNull()) {
token.setTenantId(Long.parseLong(jwt.getClaim(DTToken.TENANT_ID).asString()));
}
token.setExpireAt(jwt.getExpiresAt());
return token;
} catch (UnsupportedEncodingException e) {
if (log.isErrorEnabled()) {
log.error("JWT Token decode Error.", e);
}
throw new RdosDefineException("DT Token解码异常.");
} catch (TokenExpiredException e) {
if (log.isErrorEnabled()) {
log.error("JWT Token expire.", e);
}
throw new RdosDefineException("DT Token已过期");
}
}
use of com.auth0.android.jwt.JWT in project Taier by DTStack.
the class TokenService method decryptionWithOutExpire.
public DTToken decryptionWithOutExpire(String tokenText) {
Assert.notNull(tokenText, "JWT Token Text can't blank.");
try {
DecodedJWT jwt = JWT.require(Algorithm.HMAC256(JWT_TOKEN)).build().verify(tokenText);
DTToken token = new DTToken();
token.setUserName(jwt.getClaim(DTToken.USER_NAME).asString());
token.setUserId(Long.parseLong(jwt.getClaim(DTToken.USER_ID).asString()));
if (!jwt.getClaim(DTToken.TENANT_ID).isNull()) {
token.setTenantId(Long.parseLong(jwt.getClaim(DTToken.TENANT_ID).asString()));
}
return token;
} catch (UnsupportedEncodingException e) {
throw new RdosDefineException("DT Token解码异常.");
}
}
use of com.auth0.android.jwt.JWT in project sda-dropwizard-commons by SDA-SE.
the class AuthBuilderTest method shouldOverwriteClaimOnMultipleAddCalls.
@Test
public void shouldOverwriteClaimOnMultipleAddCalls() {
String token = authBuilder.addClaim("test", 1L).addClaim("test", 2).addClaim("test", "foo").buildToken();
DecodedJWT jwt = JWT.decode(token);
assertThat(jwt.getClaim("test").asLong()).isNull();
assertThat(jwt.getClaim("test").asInt()).isNull();
assertThat(jwt.getClaim("test").asString()).isEqualTo("foo");
}
use of com.auth0.android.jwt.JWT in project sda-dropwizard-commons by SDA-SE.
the class OpaAuthFilter method filter.
@Override
public void filter(ContainerRequestContext requestContext) {
Span span = tracer.buildSpan("authorizeUsingOpa").withTag("opa.allow", false).withTag(COMPONENT, "OpaAuthFilter").start();
try (Scope ignored = tracer.scopeManager().activate(span)) {
// collect input parameters for Opa request
UriInfo uriInfo = requestContext.getUriInfo();
String method = requestContext.getMethod();
String trace = requestContext.getHeaderString(RequestTracing.TOKEN_HEADER);
String jwt = null;
// if security context already exist and if it is a jwt security context,
// we include the jwt in the request
SecurityContext securityContext = requestContext.getSecurityContext();
Map<String, Claim> claims = null;
if (null != securityContext) {
JwtPrincipal jwtPrincipal = getJwtPrincipal(requestContext.getSecurityContext());
if (jwtPrincipal != null) {
// JWT principal found, this means that JWT has been validated by
// auth bundle
// and can be used within this bundle
jwt = jwtPrincipal.getJwt();
claims = jwtPrincipal.getClaims();
}
}
JsonNode constraints = null;
if (!isDisabled && !isExcluded(uriInfo)) {
// process the actual request to the open policy agent server
String[] path = uriInfo.getPathSegments().stream().map(PathSegment::getPath).toArray(String[]::new);
OpaInput opaInput = new OpaInput(jwt, path, method, trace);
ObjectNode objectNode = om.convertValue(opaInput, ObjectNode.class);
// append the input extensions to the input object
inputExtensions.forEach((namespace, extension) -> objectNode.set(namespace, om.valueToTree(extension.createAdditionalInputContent(requestContext))));
OpaRequest request = OpaRequest.request(objectNode);
constraints = authorizeWithOpa(request, span);
}
OpaJwtPrincipal principal = OpaJwtPrincipal.create(jwt, claims, constraints, om);
replaceSecurityContext(requestContext, securityContext, principal);
} finally {
span.finish();
}
}
use of com.auth0.android.jwt.JWT 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();
}
Aggregations