Search in sources :

Example 16 with User

use of com.auth0.flickr2.domain.User in project kemenu-web by afdezcl.

the class JWTAuthorizationFilter method getAuthentication.

private UsernamePasswordAuthenticationToken getAuthentication(String authorizationHeader) {
    DecodedJWT decodedJWT = jwtService.decodeAccessToken(authorizationHeader);
    String user = decodedJWT.getSubject();
    if (Objects.nonNull(user) && !user.isEmpty()) {
        List<SimpleGrantedAuthority> authorities = jwtService.getRolesFrom(decodedJWT);
        return new UsernamePasswordAuthenticationToken(user, null, authorities);
    }
    return null;
}
Also used : SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT)

Example 17 with User

use of com.auth0.flickr2.domain.User in project mapsmessaging_server by Maps-Messaging.

the class AwsJwtLoginModule method login.

@Override
public boolean login() throws LoginException {
    // prompt for a user name and password
    if (callbackHandler == null) {
        throw new LoginException("Error: no CallbackHandler available to garner authentication information from the user");
    }
    Callback[] callbacks = new Callback[2];
    callbacks[0] = new NameCallback("user name: ");
    callbacks[1] = new PasswordCallback("password: ", false);
    try {
        callbackHandler.handle(callbacks);
        username = ((NameCallback) callbacks[0]).getName();
        char[] tmpPassword = ((PasswordCallback) callbacks[1]).getPassword();
        if (tmpPassword == null) {
            tmpPassword = new char[0];
        }
        String token = new String(tmpPassword);
        ((PasswordCallback) callbacks[1]).clearPassword();
        // Password should be a valid JWT
        RSAKeyProvider keyProvider = new AwsCognitoRSAKeyProvider(region, poolId);
        Algorithm algorithm = Algorithm.RSA256(keyProvider);
        JWTVerifier jwtVerifier = JWT.require(algorithm).withAudience(clientId).build();
        jwtVerifier.verify(token);
        return true;
    } catch (IOException ioe) {
        throw new LoginException(ioe.toString());
    } catch (UnsupportedCallbackException uce) {
        throw new LoginException("Error: " + uce.getCallback().toString() + " not available to garner authentication information " + "from the user");
    }
}
Also used : RSAKeyProvider(com.auth0.jwt.interfaces.RSAKeyProvider) IOException(java.io.IOException) Algorithm(com.auth0.jwt.algorithms.Algorithm) PasswordCallback(javax.security.auth.callback.PasswordCallback) NameCallback(javax.security.auth.callback.NameCallback) Callback(javax.security.auth.callback.Callback) NameCallback(javax.security.auth.callback.NameCallback) LoginException(javax.security.auth.login.LoginException) PasswordCallback(javax.security.auth.callback.PasswordCallback) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) JWTVerifier(com.auth0.jwt.JWTVerifier)

Example 18 with User

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

the class OpenVpnClientConfigurationService method getOvpnProfile.

public byte[] getOvpnProfile(String deviceName, OperatingSystemType type) throws IOException {
    Path path;
    if (type == OperatingSystemType.WINDOWS) {
        path = FileSystems.getDefault().getPath(windowsClientTemplatePath);
        newLine = "\r\n";
    } else if (type == OperatingSystemType.MAC) {
        path = FileSystems.getDefault().getPath(macosClientTemplatePath);
        newLine = "\n";
    } else {
        path = FileSystems.getDefault().getPath(unixClientTemplatePath);
        newLine = "\n";
    }
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    // ** use user defined port with fallback to 1194 to avoid errors
    Integer mappedPortInRouter = openVpnServerService.getOpenVpnMappedPort();
    String remoteString = String.format("remote %s %d%s%s", openVpnServerService.getOpenVpnServerHost(), mappedPortInRouter, newLine, newLine);
    try {
        outputStream.write(remoteString.getBytes());
        outputStream.write(readFileWithNewLine(path));
        outputStream.write(createTag(extractLinesFromFile(String.format("%s/ca.crt", openVpnServerPath)), "ca"));
        outputStream.write(createTag(extractLinesFromFile(String.format("%s/easy-rsa/keys/%s.crt", openVpnServerPath, deviceName)), "cert"));
        outputStream.write(createTag(extractLinesFromFile(String.format("%s/easy-rsa/keys/%s.key", openVpnServerPath, deviceName)), "key"));
        outputStream.write(createTag(extractLinesFromFile(String.format("%s/ta.key", openVpnServerPath)), "tls-auth"));
    } catch (Exception e) {
        log.error("Error creating ovpn-profile.", e);
        throw (e);
    } finally {
        outputStream.close();
    }
    outputStream.close();
    return outputStream.toByteArray();
}
Also used : Path(java.nio.file.Path) ByteArrayOutputStream(com.auth0.jwt.internal.org.apache.commons.io.output.ByteArrayOutputStream) IOException(java.io.IOException)

Example 19 with User

use of com.auth0.flickr2.domain.User in project supertokens-core by supertokens.

the class JWTSigningFunctions method createJWTToken.

/**
 * Creates and returns a JWT string
 *
 * @param main
 * @param algorithm   The signing algorithm to use when creating the token. Refer to
 *                    {@link JWTSigningKey.SupportedAlgorithms}
 * @param payload     JSON object containing user defined claims to be added to the JWT payload
 * @param jwksDomain  Used as the issuer in the JWT payload
 * @param jwtValidity Used to set iat anf exp claims in the JWT payload
 * @return String token
 * @throws StorageQueryException                   If there is an error interacting with the database
 * @throws StorageTransactionLogicException        If there is an error interacting with the database
 * @throws NoSuchAlgorithmException                If there is an error when using Java's cryptography packages
 * @throws InvalidKeySpecException                 If there is an error when using Java's cryptography packages
 * @throws JWTCreationException                    If there is an error when creating JWTs
 * @throws UnsupportedJWTSigningAlgorithmException If the algorithm provided does not match any of the supported
 *                                                 algorithms
 */
@SuppressWarnings("unchecked")
public static String createJWTToken(Main main, String algorithm, JsonObject payload, String jwksDomain, long jwtValidity) throws StorageQueryException, StorageTransactionLogicException, NoSuchAlgorithmException, InvalidKeySpecException, JWTCreationException, UnsupportedJWTSigningAlgorithmException {
    // TODO: In the future we will have a way for the user to send a custom key id to use
    JWTSigningKey.SupportedAlgorithms supportedAlgorithm;
    try {
        supportedAlgorithm = JWTSigningKey.SupportedAlgorithms.valueOf(algorithm);
    } catch (IllegalArgumentException e) {
        // If it enters this block then the string value provided does not match the algorithms we support
        throw new UnsupportedJWTSigningAlgorithmException();
    }
    JWTSigningKeyInfo keyToUse = JWTSigningKey.getInstance(main).getOrCreateAndGetKeyForAlgorithm(supportedAlgorithm);
    // Get an instance of auth0's Algorithm which is needed when signing using auth0's package
    Algorithm signingAlgorithm = getAuth0Algorithm(supportedAlgorithm, keyToUse);
    // Create the claims for the JWT header
    Map<String, Object> headerClaims = new HashMap<>();
    // All examples in the RFC have the algorithm
    headerClaims.put("alg", supportedAlgorithm.name().toUpperCase());
    // in upper case
    headerClaims.put("typ", "JWT");
    headerClaims.put("kid", keyToUse.keyId);
    long currentTimeInMillis = System.currentTimeMillis();
    // JWT Expiry is seconds from epoch not millis
    long jwtExpiry = Double.valueOf(Math.ceil((currentTimeInMillis / 1000.0))).longValue() + (jwtValidity);
    // Add relevant claims to the payload, note we only add/override ones that we absolutely need to.
    Map<String, Object> jwtPayload = new Gson().fromJson(payload, HashMap.class);
    jwtPayload.putIfAbsent("iss", jwksDomain);
    jwtPayload.put("exp", jwtExpiry);
    // JWT uses seconds from epoch not millis
    jwtPayload.put("iat", currentTimeInMillis / 1000);
    return com.auth0.jwt.JWT.create().withPayload(jwtPayload).withHeader(headerClaims).sign(signingAlgorithm);
}
Also used : UnsupportedJWTSigningAlgorithmException(io.supertokens.jwt.exceptions.UnsupportedJWTSigningAlgorithmException) JWTSigningKeyInfo(io.supertokens.pluginInterface.jwt.JWTSigningKeyInfo) Gson(com.google.gson.Gson) JsonObject(com.google.gson.JsonObject) Algorithm(com.auth0.jwt.algorithms.Algorithm)

Example 20 with User

use of com.auth0.flickr2.domain.User in project supertokens-core by supertokens.

the class JWTCreateTest method testThatDecodedJWTUsesCustomIssuer.

/**
 * Test that final JWT uses custom iss claim instead of jwks domain
 */
@Test
public void testThatDecodedJWTUsesCustomIssuer() throws Exception {
    String[] args = { "../" };
    TestingProcessManager.TestingProcess process = TestingProcessManager.start(args);
    assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED));
    String algorithm = "RS256";
    JsonObject payload = new JsonObject();
    payload.addProperty("iss", "http://customiss");
    String jwksDomain = "http://localhost";
    long validity = 3600;
    String jwt = JWTSigningFunctions.createJWTToken(process.getProcess(), algorithm, payload, jwksDomain, validity);
    DecodedJWT decodedJWT = JWT.decode(jwt);
    String issuer = decodedJWT.getIssuer();
    if (!issuer.equals("http://customiss")) {
        throw new Exception("Decoded JWT does not contain 'iss' claim matching user defined value");
    }
    process.kill();
    assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED));
}
Also used : TestingProcessManager(io.supertokens.test.TestingProcessManager) JsonObject(com.google.gson.JsonObject) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) UnsupportedJWTSigningAlgorithmException(io.supertokens.jwt.exceptions.UnsupportedJWTSigningAlgorithmException) Test(org.junit.Test)

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