Search in sources :

Example 1 with JWTSigner

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);
}
Also used : Cookie(javax.servlet.http.Cookie) JWTCookieGenerator(io.gravitee.management.security.cookies.JWTCookieGenerator) UserDetails(io.gravitee.management.idp.api.authentication.UserDetails) RoleScope(io.gravitee.repository.management.model.RoleScope) FilterChain(javax.servlet.FilterChain) ServletRequest(javax.servlet.ServletRequest) java.util(java.util) HttpHeaders(io.gravitee.common.http.HttpHeaders) RoleEntity(io.gravitee.management.model.RoleEntity) ServletException(javax.servlet.ServletException) MembershipDefaultReferenceId(io.gravitee.repository.management.model.MembershipDefaultReferenceId) HttpServletResponse(javax.servlet.http.HttpServletResponse) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) IOException(java.io.IOException) GrantedAuthority(org.springframework.security.core.GrantedAuthority) HttpServletRequest(javax.servlet.http.HttpServletRequest) MembershipService(io.gravitee.management.service.MembershipService) ServletResponse(javax.servlet.ServletResponse) GenericFilterBean(org.springframework.web.filter.GenericFilterBean) JWTSigner(com.auth0.jwt.JWTSigner) Claims(io.gravitee.management.service.common.JWTHelper.Claims) MembershipReferenceType(io.gravitee.repository.management.model.MembershipReferenceType) Authentication(org.springframework.security.core.Authentication) SecurityContextHolder(org.springframework.security.core.context.SecurityContextHolder) Cookie(javax.servlet.http.Cookie) JWTSigner(com.auth0.jwt.JWTSigner) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) HttpServletResponse(javax.servlet.http.HttpServletResponse) HttpServletRequest(javax.servlet.http.HttpServletRequest) RoleEntity(io.gravitee.management.model.RoleEntity) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) UserDetails(io.gravitee.management.idp.api.authentication.UserDetails) Authentication(org.springframework.security.core.Authentication)

Example 2 with JWTSigner

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;
}
Also used : JWTSigner(com.auth0.jwt.JWTSigner) EmailNotificationBuilder(io.gravitee.management.service.builder.EmailNotificationBuilder) NotificationParamsBuilder(io.gravitee.management.service.notification.NotificationParamsBuilder)

Example 3 with JWTSigner

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);
    }
}
Also used : User(org.survey.model.user.User) JWTSigner(com.auth0.jwt.JWTSigner) HashMap(java.util.HashMap) JWTVerifyException(com.auth0.jwt.JWTVerifyException) JWTExpiredException(com.auth0.jwt.JWTExpiredException) JWTVerifyException(com.auth0.jwt.JWTVerifyException) Test(org.junit.Test)

Example 4 with JWTSigner

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;
}
Also used : JwtSigner(com.auth0.jwt.JwtSigner) ClaimSet(com.auth0.jwt.ClaimSet) NextprotSecurityException(org.nextprot.api.security.service.exception.NextprotSecurityException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) SignatureException(java.security.SignatureException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) NextprotSecurityException(org.nextprot.api.security.service.exception.NextprotSecurityException) InvalidKeyException(java.security.InvalidKeyException)

Example 5 with JWTSigner

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();
}
Also used : HashMap(java.util.HashMap) JWTSigner(com.auth0.jwt.JWTSigner) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) UserEntity(io.gravitee.management.model.UserEntity) RoleEntity(io.gravitee.management.model.RoleEntity) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) UserDetails(io.gravitee.management.idp.api.authentication.UserDetails) Authentication(org.springframework.security.core.Authentication) HashSet(java.util.HashSet) NewCookie(javax.ws.rs.core.NewCookie)

Aggregations

JWTSigner (com.auth0.jwt.JWTSigner)4 UserDetails (io.gravitee.management.idp.api.authentication.UserDetails)2 RoleEntity (io.gravitee.management.model.RoleEntity)2 IOException (java.io.IOException)2 HashMap (java.util.HashMap)2 Authentication (org.springframework.security.core.Authentication)2 GrantedAuthority (org.springframework.security.core.GrantedAuthority)2 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)2 ClaimSet (com.auth0.jwt.ClaimSet)1 JWTExpiredException (com.auth0.jwt.JWTExpiredException)1 JWTVerifyException (com.auth0.jwt.JWTVerifyException)1 JwtSigner (com.auth0.jwt.JwtSigner)1 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 HttpHeaders (io.gravitee.common.http.HttpHeaders)1 UserEntity (io.gravitee.management.model.UserEntity)1 JWTCookieGenerator (io.gravitee.management.security.cookies.JWTCookieGenerator)1 MembershipService (io.gravitee.management.service.MembershipService)1 EmailNotificationBuilder (io.gravitee.management.service.builder.EmailNotificationBuilder)1 Claims (io.gravitee.management.service.common.JWTHelper.Claims)1