Search in sources :

Example 81 with User

use of com.auth0.flickr2.domain.User in project ddf by codice.

the class TestOidc method processCredentialFlow.

/**
 * Processes a credential flow request/response
 *
 * <ul>
 *   <li>Sets up a userinfo endpoint that responds with the given {@param userInfoResponse} when
 *       given {@param accessToken}
 *   <li>Sends a request to Intrigue with the {@param accessToken} as a parameter
 *   <li>Asserts that the response is teh expected response
 *   <li>Verifies if the userinfo endpoint is hit or not
 * </ul>
 *
 * @return the response for additional verification
 */
private Response processCredentialFlow(String accessToken, String userInfoResponse, boolean isSigned, int expectedStatusCode, boolean userInfoShouldBeHit) {
    // Host the user info endpoint with the access token in the auth header
    String basicAuthHeader = "Bearer " + accessToken;
    String contentType = isSigned ? "application/jwt" : APPLICATION_JSON;
    whenHttp(server).match(get(USER_INFO_ENDPOINT_PATH), withHeader(AUTHORIZATION, basicAuthHeader)).then(ok(), contentType(contentType), bytesContent(userInfoResponse.getBytes()));
    // Send a request to DDF with the access token
    Response response = given().redirects().follow(false).expect().statusCode(expectedStatusCode).when().get(ROOT_URL.getUrl() + "?access_token=" + accessToken);
    List<Call> endpointCalls = server.getCalls().stream().filter(call -> call.getMethod().getMethodString().equals(GET)).filter(call -> call.getUrl().equals(URL_START + USER_INFO_ENDPOINT_PATH)).collect(Collectors.toList());
    if (userInfoShouldBeHit) {
        assertThat(endpointCalls.size(), is(greaterThanOrEqualTo(1)));
    } else {
        assertThat(endpointCalls.size(), is(0));
    }
    return response;
}
Also used : Response(io.restassured.response.Response) KeyPair(java.security.KeyPair) Arrays(java.util.Arrays) StubServer(com.xebialabs.restito.server.StubServer) GET(javax.ws.rs.HttpMethod.GET) Enumeration(java.util.Enumeration) Date(java.util.Date) PREFERRED_USERNAME(org.pac4j.oidc.profile.OidcProfileDefinition.PREFERRED_USERNAME) HttpStatus(org.apache.http.HttpStatus) GsonBuilder(com.google.gson.GsonBuilder) Algorithm(com.auth0.jwt.algorithms.Algorithm) NONCE(org.pac4j.oidc.profile.OidcProfileDefinition.NONCE) RSAPublicKey(java.security.interfaces.RSAPublicKey) Gson(com.google.gson.Gson) Duration(java.time.Duration) Map(java.util.Map) Base64URL(com.nimbusds.jose.util.Base64URL) AbstractIntegrationTest(org.codice.ddf.itests.common.AbstractIntegrationTest) URI(java.net.URI) APPLICATION_JSON(javax.ws.rs.core.MediaType.APPLICATION_JSON) KeyPairGenerator(java.security.KeyPairGenerator) Awaitility.await(org.awaitility.Awaitility.await) ImmutableMap(com.google.common.collect.ImmutableMap) JWTCreator(com.auth0.jwt.JWTCreator) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) Condition.parameter(com.xebialabs.restito.semantics.Condition.parameter) UUID(java.util.UUID) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) JWK(com.nimbusds.jose.jwk.JWK) StandardCharsets(java.nio.charset.StandardCharsets) HOST(javax.ws.rs.core.HttpHeaders.HOST) PerSuite(org.ops4j.pax.exam.spi.reactors.PerSuite) List(java.util.List) JSONObject(org.json.simple.JSONObject) Action.bytesContent(com.xebialabs.restito.semantics.Action.bytesContent) KeyUse(com.nimbusds.jose.jwk.KeyUse) URLEncodedUtils(org.apache.http.client.utils.URLEncodedUtils) SECURE_ROOT(org.codice.ddf.itests.common.AbstractIntegrationTest.DynamicUrl.SECURE_ROOT) Action.ok(com.xebialabs.restito.semantics.Action.ok) RestAssured.given(io.restassured.RestAssured.given) Matchers.is(org.hamcrest.Matchers.is) Condition.withHeader(com.xebialabs.restito.semantics.Condition.withHeader) AfterExam(org.codice.ddf.test.common.annotations.AfterExam) NameValuePair(org.apache.http.NameValuePair) Dictionary(java.util.Dictionary) StubHttp.whenHttp(com.xebialabs.restito.builder.stub.StubHttp.whenHttp) PaxExam(org.ops4j.pax.exam.junit.PaxExam) JWT(com.auth0.jwt.JWT) Call(com.xebialabs.restito.semantics.Call) MessageDigest(java.security.MessageDigest) RunWith(org.junit.runner.RunWith) BeforeExam(org.codice.ddf.test.common.annotations.BeforeExam) AZP(org.pac4j.oidc.profile.OidcProfileDefinition.AZP) REFRESH_TOKEN(org.pac4j.oidc.profile.OidcProfileDefinition.REFRESH_TOKEN) LOCATION(javax.ws.rs.core.HttpHeaders.LOCATION) Condition.post(com.xebialabs.restito.semantics.Condition.post) ImmutableList(com.google.common.collect.ImmutableList) Configuration(org.osgi.service.cm.Configuration) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Condition.get(com.xebialabs.restito.semantics.Condition.get) AUTHORIZATION(javax.ws.rs.core.HttpHeaders.AUTHORIZATION) GsonTypeAdapters(org.codice.gsonsupport.GsonTypeAdapters) Hashtable(java.util.Hashtable) Before(org.junit.Before) Matchers.greaterThanOrEqualTo(org.hamcrest.Matchers.greaterThanOrEqualTo) PublicClaims(com.auth0.jwt.impl.PublicClaims) Assert.assertTrue(org.junit.Assert.assertTrue) AUTH_TIME(org.pac4j.oidc.profile.OidcProfileDefinition.AUTH_TIME) Test(org.junit.Test) USER_AGENT(javax.ws.rs.core.HttpHeaders.USER_AGENT) EMAIL_VERIFIED(org.pac4j.oidc.profile.OidcProfileDefinition.EMAIL_VERIFIED) TimeUnit(java.util.concurrent.TimeUnit) ExamReactorStrategy(org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy) RSAKey(com.nimbusds.jose.jwk.RSAKey) Response(io.restassured.response.Response) Action.contentType(com.xebialabs.restito.semantics.Action.contentType) ACCESS_TOKEN(org.pac4j.oidc.profile.OidcProfileDefinition.ACCESS_TOKEN) LoggingUtils(org.codice.ddf.test.common.LoggingUtils) Call(com.xebialabs.restito.semantics.Call)

Example 82 with User

use of com.auth0.flickr2.domain.User in project ddf by codice.

the class TestOidc method testCodeFlowLogin.

// --------------------------Code Flow Tests--------------------------//
@Test
public void testCodeFlowLogin() throws Exception {
    Map<String, String> initialResponseParams = sendInitialRequest(CODE);
    assertThat(initialResponseParams.get(SCOPE), is(DDF_SCOPE));
    assertThat(initialResponseParams.get(RESPONSE_TYPE), is(CODE));
    assertThat(initialResponseParams.get(CLIENT_ID), is(DDF_CLIENT_ID));
    assertTrue(initialResponseParams.containsKey(REDIRECT_URI));
    // recommended by spec
    assertTrue(initialResponseParams.containsKey(STATE));
    // optional but sent in DDF
    assertTrue(initialResponseParams.containsKey(RESPONSE_MODE));
    // optional but sent in DDF
    assertTrue(initialResponseParams.containsKey(NONCE));
    // Add token endpoint information to stub server
    String basicAuthHeader = "Basic " + java.util.Base64.getEncoder().encodeToString((DDF_CLIENT_ID + ":" + DDF_CLIENT_SECRET).getBytes(StandardCharsets.UTF_8));
    String validIdToken = getBaseIdTokenBuilder().withClaim(NONCE, initialResponseParams.get(NONCE)).sign(validAlgorithm);
    String validAccessToken = createAccessToken(true);
    String tokenEndpointResponse = createTokenEndpointResponse(validIdToken, validAccessToken);
    whenHttp(server).match(post(TOKEN_ENDPOINT_PATH), parameter(CODE, TEMPORARY_CODE), parameter("grant_type", "authorization_code"), withHeader(AUTHORIZATION, basicAuthHeader)).then(ok(), contentType(APPLICATION_JSON), bytesContent(tokenEndpointResponse.getBytes()));
    // Respond to request after user logged in with the temporary code
    Response searchResponse = given().cookie(JSESSIONID, initialResponseParams.get(JSESSIONID)).header(USER_AGENT, BROWSER_USER_AGENT).header(HOST, "localhost:" + HTTPS_PORT.getPort()).header("Origin", URL_START.toString()).param(CODE, TEMPORARY_CODE).param(STATE, initialResponseParams.get(STATE)).redirects().follow(false).expect().statusCode(200).when().post(initialResponseParams.get(REDIRECT_URI));
    // Verify that the stub server was hit
    List<Call> tokenEndpointCalls = server.getCalls().stream().filter(call -> call.getUrl().equals(URL_START + TOKEN_ENDPOINT_PATH)).collect(Collectors.toList());
    assertThat(tokenEndpointCalls.size(), is(1));
    // Verify that we're logged in as admin
    Map<String, Object> userInfoList = getUserInfo(initialResponseParams.get(JSESSIONID));
    assertThat(userInfoList.get("name"), is(ADMIN));
    logout(initialResponseParams.get(JSESSIONID));
}
Also used : Response(io.restassured.response.Response) KeyPair(java.security.KeyPair) Arrays(java.util.Arrays) StubServer(com.xebialabs.restito.server.StubServer) GET(javax.ws.rs.HttpMethod.GET) Enumeration(java.util.Enumeration) Date(java.util.Date) PREFERRED_USERNAME(org.pac4j.oidc.profile.OidcProfileDefinition.PREFERRED_USERNAME) HttpStatus(org.apache.http.HttpStatus) GsonBuilder(com.google.gson.GsonBuilder) Algorithm(com.auth0.jwt.algorithms.Algorithm) NONCE(org.pac4j.oidc.profile.OidcProfileDefinition.NONCE) RSAPublicKey(java.security.interfaces.RSAPublicKey) Gson(com.google.gson.Gson) Duration(java.time.Duration) Map(java.util.Map) Base64URL(com.nimbusds.jose.util.Base64URL) AbstractIntegrationTest(org.codice.ddf.itests.common.AbstractIntegrationTest) URI(java.net.URI) APPLICATION_JSON(javax.ws.rs.core.MediaType.APPLICATION_JSON) KeyPairGenerator(java.security.KeyPairGenerator) Awaitility.await(org.awaitility.Awaitility.await) ImmutableMap(com.google.common.collect.ImmutableMap) JWTCreator(com.auth0.jwt.JWTCreator) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) Condition.parameter(com.xebialabs.restito.semantics.Condition.parameter) UUID(java.util.UUID) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) JWK(com.nimbusds.jose.jwk.JWK) StandardCharsets(java.nio.charset.StandardCharsets) HOST(javax.ws.rs.core.HttpHeaders.HOST) PerSuite(org.ops4j.pax.exam.spi.reactors.PerSuite) List(java.util.List) JSONObject(org.json.simple.JSONObject) Action.bytesContent(com.xebialabs.restito.semantics.Action.bytesContent) KeyUse(com.nimbusds.jose.jwk.KeyUse) URLEncodedUtils(org.apache.http.client.utils.URLEncodedUtils) SECURE_ROOT(org.codice.ddf.itests.common.AbstractIntegrationTest.DynamicUrl.SECURE_ROOT) Action.ok(com.xebialabs.restito.semantics.Action.ok) RestAssured.given(io.restassured.RestAssured.given) Matchers.is(org.hamcrest.Matchers.is) Condition.withHeader(com.xebialabs.restito.semantics.Condition.withHeader) AfterExam(org.codice.ddf.test.common.annotations.AfterExam) NameValuePair(org.apache.http.NameValuePair) Dictionary(java.util.Dictionary) StubHttp.whenHttp(com.xebialabs.restito.builder.stub.StubHttp.whenHttp) PaxExam(org.ops4j.pax.exam.junit.PaxExam) JWT(com.auth0.jwt.JWT) Call(com.xebialabs.restito.semantics.Call) MessageDigest(java.security.MessageDigest) RunWith(org.junit.runner.RunWith) BeforeExam(org.codice.ddf.test.common.annotations.BeforeExam) AZP(org.pac4j.oidc.profile.OidcProfileDefinition.AZP) REFRESH_TOKEN(org.pac4j.oidc.profile.OidcProfileDefinition.REFRESH_TOKEN) LOCATION(javax.ws.rs.core.HttpHeaders.LOCATION) Condition.post(com.xebialabs.restito.semantics.Condition.post) ImmutableList(com.google.common.collect.ImmutableList) Configuration(org.osgi.service.cm.Configuration) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Condition.get(com.xebialabs.restito.semantics.Condition.get) AUTHORIZATION(javax.ws.rs.core.HttpHeaders.AUTHORIZATION) GsonTypeAdapters(org.codice.gsonsupport.GsonTypeAdapters) Hashtable(java.util.Hashtable) Before(org.junit.Before) Matchers.greaterThanOrEqualTo(org.hamcrest.Matchers.greaterThanOrEqualTo) PublicClaims(com.auth0.jwt.impl.PublicClaims) Assert.assertTrue(org.junit.Assert.assertTrue) AUTH_TIME(org.pac4j.oidc.profile.OidcProfileDefinition.AUTH_TIME) Test(org.junit.Test) USER_AGENT(javax.ws.rs.core.HttpHeaders.USER_AGENT) EMAIL_VERIFIED(org.pac4j.oidc.profile.OidcProfileDefinition.EMAIL_VERIFIED) TimeUnit(java.util.concurrent.TimeUnit) ExamReactorStrategy(org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy) RSAKey(com.nimbusds.jose.jwk.RSAKey) Response(io.restassured.response.Response) Action.contentType(com.xebialabs.restito.semantics.Action.contentType) ACCESS_TOKEN(org.pac4j.oidc.profile.OidcProfileDefinition.ACCESS_TOKEN) LoggingUtils(org.codice.ddf.test.common.LoggingUtils) Call(com.xebialabs.restito.semantics.Call) JSONObject(org.json.simple.JSONObject) AbstractIntegrationTest(org.codice.ddf.itests.common.AbstractIntegrationTest) Test(org.junit.Test)

Example 83 with User

use of com.auth0.flickr2.domain.User in project snow-owl by b2ihealthcare.

the class AuthorizationHeaderVerifier method toUser.

/**
 * Converts the given JWT access token to a {@link User} representation using the configured email and permission claims.
 *
 * @param jwt
 *            - the JWT to convert to a {@link User} object
 * @return
 * @throws BadRequestException
 *             - if either the configured email or permissions property is missing from the given JWT
 */
public User toUser(DecodedJWT jwt) {
    final Claim emailClaim = jwt.getClaim(emailClaimProperty);
    if (emailClaim == null || emailClaim.isNull()) {
        throw new BadRequestException("'%s' JWT access token field is required for email access, but it was missing.", emailClaimProperty);
    }
    Claim permissionsClaim = jwt.getClaim(permissionsClaimProperty);
    if (permissionsClaim == null || permissionsClaim.isNull()) {
        throw new BadRequestException("'%s' JWT access token field is required for permissions access, but it was missing.", permissionsClaimProperty);
    }
    final Set<Permission> permissions = jwt.getClaim(permissionsClaimProperty).asList(String.class).stream().map(Permission::valueOf).collect(Collectors.toSet());
    return new User(emailClaim.asString(), List.of(new Role("jwt_roles", permissions)));
}
Also used : BadRequestException(com.b2international.commons.exceptions.BadRequestException) Claim(com.auth0.jwt.interfaces.Claim)

Example 84 with User

use of com.auth0.flickr2.domain.User in project flowgate by vmware.

the class JwtTokenUtil method generate.

/**
 * generate token with roles
 * @param user
 * @return
 */
public AuthToken generate(WormholeUserDetails user) {
    String secret = FlowgateKeystore.getEncryptKey();
    Algorithm algorithm = null;
    try {
        algorithm = Algorithm.HMAC256(secret);
    } catch (IllegalArgumentException | UnsupportedEncodingException e) {
        logger.error("Error when generating token", e.getMessage());
        return null;
    }
    ObjectMapper mapper = new ObjectMapper();
    AuthToken access_token = new AuthToken();
    Date issure_date = new Date();
    Date expires_date = new Date(System.currentTimeMillis() + expiration * 1000);
    long timeMillis = expires_date.getTime();
    String token = JWT.create().withIssuer(issuer).withIssuedAt(issure_date).withExpiresAt(expires_date).withSubject(user.getUsername()).withClaim("userId", user.getUserId()).sign(algorithm);
    access_token.setAccess_token(token);
    access_token.setExpires_in(timeMillis);
    try {
        mapper.enable(DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT);
        redisTemplate.opsForValue().set(Prefix_token + token, mapper.writeValueAsString(user), expiration, TimeUnit.SECONDS);
    } catch (JsonProcessingException e) {
        logger.error(e.getMessage());
        return null;
    }
    logger.debug(user.getUsername() + "'s token has been generated.");
    return access_token;
}
Also used : UnsupportedEncodingException(java.io.UnsupportedEncodingException) AuthToken(com.vmware.flowgate.common.model.AuthToken) Algorithm(com.auth0.jwt.algorithms.Algorithm) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Date(java.util.Date)

Example 85 with User

use of com.auth0.flickr2.domain.User in project structr by structr.

the class JWTHelper method getPrincipalForAccessTokenWithKeystore.

private static Principal getPrincipalForAccessTokenWithKeystore(String token, PropertyKey<String> eMailKey) throws FrameworkException {
    Key publicKey = getPublicKeyForToken();
    final Algorithm alg = parseAlgorithm(publicKey.getAlgorithm());
    Map<String, Claim> claims = validateTokenWithKeystore(token, alg);
    if (claims == null) {
        return null;
    }
    Principal user = getPrincipalForTokenClaims(claims, eMailKey);
    if (user == null) {
        return null;
    }
    // Check if the access_token is still valid.
    // If access_token isn't valid anymore, then either it timed out, or the user logged out.
    String tokenReference = claims.getOrDefault("tokenId", new NullClaim()).asString();
    if (validateTokenForUser(tokenReference, user)) {
        return user;
    }
    return null;
}
Also used : NullClaim(com.auth0.jwt.impl.NullClaim) Algorithm(com.auth0.jwt.algorithms.Algorithm) RSAPublicKey(java.security.interfaces.RSAPublicKey) PropertyKey(org.structr.core.property.PropertyKey) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) NullClaim(com.auth0.jwt.impl.NullClaim) Claim(com.auth0.jwt.interfaces.Claim) Principal(org.structr.core.entity.Principal)

Aggregations

Algorithm (com.auth0.jwt.algorithms.Algorithm)64 DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)60 IOException (java.io.IOException)51 Test (org.junit.Test)46 JWT (com.auth0.jwt.JWT)42 Instant (java.time.Instant)39 java.util (java.util)37 Duration (java.time.Duration)36 TechnicalException (io.gravitee.repository.exceptions.TechnicalException)35 Maps (io.gravitee.common.util.Maps)34 DEFAULT_JWT_ISSUER (io.gravitee.rest.api.service.common.JWTHelper.DefaultValues.DEFAULT_JWT_ISSUER)34 User (io.gravitee.repository.management.model.User)33 ConfigurableEnvironment (org.springframework.core.env.ConfigurableEnvironment)32 UserRepository (io.gravitee.repository.management.api.UserRepository)30 io.gravitee.rest.api.model (io.gravitee.rest.api.model)30 JWTVerifier (com.auth0.jwt.JWTVerifier)28 MetadataPage (io.gravitee.common.data.domain.MetadataPage)28 MembershipRepository (io.gravitee.repository.management.api.MembershipRepository)28 Membership (io.gravitee.repository.management.model.Membership)28 UserStatus (io.gravitee.repository.management.model.UserStatus)28