use of com.auth0.jwt.JWTSigner in project gravitee-management-rest-api by gravitee-io.
the class AuthenticationSuccessFilter method doFilter.
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
final HttpServletRequest req = (HttpServletRequest) servletRequest;
final Optional<Cookie> optionalStringToken;
if (req.getCookies() == null) {
optionalStringToken = Optional.empty();
} else {
optionalStringToken = Arrays.stream(req.getCookies()).filter(cookie -> HttpHeaders.AUTHORIZATION.equals(cookie.getName())).filter(cookie -> cookie.getValue() != null && !cookie.getValue().isEmpty()).findAny();
}
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && !optionalStringToken.isPresent()) {
// JWT signer
final Map<String, Object> claims = new HashMap<>();
claims.put(Claims.ISSUER, jwtIssuer);
final UserDetails userDetails = (UserDetails) authentication.getPrincipal();
// Manage authorities, initialize it with dynamic permissions from the IDP
Set<GrantedAuthority> authorities = new HashSet<>(userDetails.getAuthorities());
// We must also load permissions from repository for configured management or portal role
RoleEntity role = membershipService.getRole(MembershipReferenceType.MANAGEMENT, MembershipDefaultReferenceId.DEFAULT.toString(), userDetails.getUsername(), RoleScope.MANAGEMENT);
if (role != null) {
authorities.add(new SimpleGrantedAuthority(role.getScope().toString() + ':' + role.getName()));
}
role = membershipService.getRole(MembershipReferenceType.PORTAL, MembershipDefaultReferenceId.DEFAULT.toString(), userDetails.getUsername(), RoleScope.PORTAL);
if (role != null) {
authorities.add(new SimpleGrantedAuthority(role.getScope().toString() + ':' + role.getName()));
}
claims.put(Claims.PERMISSIONS, authorities);
claims.put(Claims.SUBJECT, userDetails.getUsername());
claims.put(Claims.EMAIL, userDetails.getEmail());
claims.put(Claims.FIRSTNAME, userDetails.getFirstname());
claims.put(Claims.LASTNAME, userDetails.getLastname());
final JWTSigner.Options options = new JWTSigner.Options();
options.setExpirySeconds(jwtExpireAfter);
options.setIssuedAt(true);
options.setJwtId(true);
final Cookie bearerCookie = jwtCookieGenerator.generate("Bearer " + new JWTSigner(jwtSecret).sign(claims, options));
((HttpServletResponse) servletResponse).addCookie(bearerCookie);
}
filterChain.doFilter(servletRequest, servletResponse);
}
use of com.auth0.jwt.JWTSigner in project gravitee-management-rest-api by gravitee-io.
the class UserServiceImpl method register.
/**
* Allows to pre-create a user and send an email notification to finalize its creation.
*/
@Override
public UserEntity register(final NewExternalUserEntity newExternalUserEntity) {
checkUserRegistrationEnabled();
newExternalUserEntity.setUsername(newExternalUserEntity.getEmail());
newExternalUserEntity.setSource("gravitee");
newExternalUserEntity.setSourceId(newExternalUserEntity.getUsername());
final UserEntity userEntity = create(newExternalUserEntity, true);
// generate a JWT to store user's information and for security purpose
final Map<String, Object> claims = new HashMap<>();
claims.put(Claims.ISSUER, environment.getProperty("jwt.issuer", DEFAULT_JWT_ISSUER));
claims.put(Claims.SUBJECT, userEntity.getUsername());
claims.put(Claims.EMAIL, userEntity.getEmail());
claims.put(Claims.FIRSTNAME, userEntity.getFirstname());
claims.put(Claims.LASTNAME, userEntity.getLastname());
final JWTSigner.Options options = new JWTSigner.Options();
options.setExpirySeconds(environment.getProperty("user.creation.token.expire-after", Integer.class, DEFAULT_JWT_EMAIL_REGISTRATION_EXPIRE_AFTER));
options.setIssuedAt(true);
options.setJwtId(true);
// send a confirm email with the token
final String jwtSecret = environment.getProperty("jwt.secret");
if (jwtSecret == null || jwtSecret.isEmpty()) {
throw new IllegalStateException("JWT secret is mandatory");
}
final String token = new JWTSigner(jwtSecret).sign(claims, options);
String portalUrl = environment.getProperty("portalURL");
if (portalUrl.endsWith("/")) {
portalUrl = portalUrl.substring(0, portalUrl.length() - 1);
}
String registrationUrl = portalUrl + "/#!/registration/confirm/" + token;
final Map<String, Object> params = new NotificationParamsBuilder().user(userEntity).token(token).registrationUrl(registrationUrl).build();
notifierService.trigger(PortalHook.USER_REGISTERED, params);
emailService.sendAsyncEmailNotification(new EmailNotificationBuilder().to(userEntity.getEmail()).subject("User registration - " + userEntity.getUsername()).template(EmailNotificationBuilder.EmailTemplate.USER_REGISTRATION).params(params).build());
return userEntity;
}
use of com.auth0.jwt.JWTSigner in project survey by markoniemi.
the class JwtTokenTest method verifyTokenWithInvalidSignature.
@Test()
public void verifyTokenWithInvalidSignature() {
try {
User user = new User("username", "password", "email", Role.ROLE_USER);
JWTSigner jwtSigner = new JWTSigner("wrong_secret");
Map<String, Object> payload = new HashMap<String, Object>();
payload.put("username", user.getUsername());
String tokenString = jwtSigner.sign(payload);
JwtToken token = new JwtToken(tokenString);
token.verifyToken();
Assert.fail();
} catch (Exception e) {
Assert.assertTrue(e instanceof JWTVerifyException);
}
}
use of com.auth0.jwt.JWTSigner in project nextprot-api by calipho-sib.
the class JWTCodecImpl method encodeJWT.
@Override
public String encodeJWT(Map<String, Object> properties, int expiration) {
String payload, token;
try {
JwtSigner jwtSigner = new JwtSigner();
payload = new ObjectMapper().writeValueAsString(properties);
ClaimSet claimSet = new ClaimSet();
claimSet.setExp(expiration);
token = jwtSigner.encode(Algorithm.HS256, payload, "payload", new String(Base64.decodeBase64(clientSecret)), claimSet);
} catch (JsonProcessingException e) {
throw new SecurityException(e);
} catch (Exception e) {
throw new SecurityException(e);
}
return token;
}
use of com.auth0.jwt.JWTSigner in project gravitee-management-rest-api by gravitee-io.
the class AbstractAuthenticationResource method connectUser.
protected Response connectUser(String userId) {
UserEntity user = userService.connect(userId);
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
final UserDetails userDetails = (UserDetails) authentication.getPrincipal();
// Manage authorities, initialize it with dynamic permissions from the IDP
Set<GrantedAuthority> authorities = new HashSet<>(userDetails.getAuthorities());
// We must also load permissions from repository for configured management or portal role
RoleEntity role = membershipService.getRole(MembershipReferenceType.MANAGEMENT, MembershipDefaultReferenceId.DEFAULT.toString(), userDetails.getUsername(), RoleScope.MANAGEMENT);
if (role != null) {
authorities.add(new SimpleGrantedAuthority(role.getScope().toString() + ':' + role.getName()));
}
role = membershipService.getRole(MembershipReferenceType.PORTAL, MembershipDefaultReferenceId.DEFAULT.toString(), userDetails.getUsername(), RoleScope.PORTAL);
if (role != null) {
authorities.add(new SimpleGrantedAuthority(role.getScope().toString() + ':' + role.getName()));
}
// JWT signer
final Map<String, Object> claims = new HashMap<>();
claims.put(JWTHelper.Claims.ISSUER, environment.getProperty("jwt.issuer", JWTHelper.DefaultValues.DEFAULT_JWT_ISSUER));
claims.put(JWTHelper.Claims.SUBJECT, user.getId());
claims.put(JWTHelper.Claims.PERMISSIONS, authorities);
claims.put(JWTHelper.Claims.EMAIL, user.getEmail());
claims.put(JWTHelper.Claims.FIRSTNAME, user.getFirstname());
claims.put(JWTHelper.Claims.LASTNAME, user.getLastname());
final JWTSigner.Options options = new JWTSigner.Options();
options.setExpirySeconds(environment.getProperty("jwt.expire-after", Integer.class, DEFAULT_JWT_EXPIRE_AFTER));
options.setIssuedAt(true);
options.setJwtId(true);
return Response.ok().entity(user).cookie(new NewCookie(HttpHeaders.AUTHORIZATION, "Bearer " + new JWTSigner(environment.getProperty("jwt.secret")).sign(claims, options), environment.getProperty("jwt.cookie-path", "/"), environment.getProperty("jwt.cookie-domain"), "", environment.getProperty("jwt.expire-after", Integer.class, DEFAULT_JWT_EXPIRE_AFTER), environment.getProperty("jwt.cookie-secure", Boolean.class, false), true)).build();
}
Aggregations