Search in sources :

Example 31 with AuthenticationResponse

use of io.helidon.security.AuthenticationResponse in project helidon by oracle.

the class GoogleTokenProviderTest method testInboundVerificationException.

@Test
public void testInboundVerificationException() throws ExecutionException, InterruptedException, GeneralSecurityException, IOException {
    GoogleIdTokenVerifier verifier = mock(GoogleIdTokenVerifier.class);
    when(verifier.verify(TOKEN_VALUE)).thenThrow(new IOException("Failed to verify token"));
    GoogleTokenProvider provider = GoogleTokenProvider.builder().clientId("clientId").verifier(verifier).build();
    ProviderRequest inboundRequest = createInboundRequest("Authorization", "bearer " + TOKEN_VALUE);
    AuthenticationResponse response = provider.authenticate(inboundRequest).toCompletableFuture().get();
    assertThat(response.status(), is(SecurityResponse.SecurityStatus.FAILURE));
    assertThat(response.statusCode().orElse(200), is(401));
    assertThat(response.responseHeaders().get("WWW-Authenticate"), notNullValue());
}
Also used : GoogleIdTokenVerifier(com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier) IOException(java.io.IOException) AuthenticationResponse(io.helidon.security.AuthenticationResponse) ProviderRequest(io.helidon.security.ProviderRequest) Test(org.junit.jupiter.api.Test)

Example 32 with AuthenticationResponse

use of io.helidon.security.AuthenticationResponse in project helidon by oracle.

the class GoogleTokenProviderTest method testInboundIncorrectToken.

@Test
public void testInboundIncorrectToken() throws ExecutionException, InterruptedException {
    ProviderRequest inboundRequest = createInboundRequest("Authorization", "tearer " + TOKEN_VALUE);
    AuthenticationResponse response = provider.authenticate(inboundRequest).toCompletableFuture().get();
    assertThat(response.status(), is(SecurityResponse.SecurityStatus.FAILURE));
    assertThat(response.statusCode().orElse(200), is(400));
    assertThat(response.responseHeaders().get("WWW-Authenticate"), notNullValue());
}
Also used : AuthenticationResponse(io.helidon.security.AuthenticationResponse) ProviderRequest(io.helidon.security.ProviderRequest) Test(org.junit.jupiter.api.Test)

Example 33 with AuthenticationResponse

use of io.helidon.security.AuthenticationResponse in project helidon by oracle.

the class HttpDigestAuthProvider method validateDigestAuth.

private AuthenticationResponse validateDigestAuth(String headerValue, SecurityEnvironment env) {
    DigestToken token;
    try {
        token = DigestToken.fromAuthorizationHeader(headerValue.substring(DIGEST_PREFIX.length()), env.method().toLowerCase());
    } catch (HttpAuthException e) {
        LOGGER.log(Level.FINEST, "Failed to process digest token", e);
        return failOrAbstain(e.getMessage());
    }
    // decrypt
    byte[] bytes;
    try {
        bytes = Base64.getDecoder().decode(token.getNonce());
    } catch (IllegalArgumentException e) {
        LOGGER.log(Level.FINEST, "Failed to base64 decode nonce", e);
        // not base 64
        return failOrAbstain("Nonce must be base64 encoded");
    }
    if (bytes.length < 17) {
        return failOrAbstain("Invalid nonce length");
    }
    byte[] salt = new byte[SALT_LENGTH];
    byte[] aesNonce = new byte[AES_NONCE_LENGTH];
    byte[] encryptedBytes = new byte[bytes.length - SALT_LENGTH - AES_NONCE_LENGTH];
    System.arraycopy(bytes, 0, salt, 0, salt.length);
    System.arraycopy(bytes, SALT_LENGTH, aesNonce, 0, aesNonce.length);
    System.arraycopy(bytes, SALT_LENGTH + AES_NONCE_LENGTH, encryptedBytes, 0, encryptedBytes.length);
    Cipher cipher = HttpAuthUtil.cipher(digestServerSecret, salt, aesNonce, Cipher.DECRYPT_MODE);
    try {
        byte[] timestampBytes = cipher.doFinal(encryptedBytes);
        long nonceTimestamp = HttpAuthUtil.toLong(timestampBytes, 0, timestampBytes.length);
        // validate nonce
        if ((System.currentTimeMillis() - nonceTimestamp) > digestNonceTimeoutMillis) {
            return failOrAbstain("Nonce timeout");
        }
    } catch (Exception e) {
        LOGGER.log(Level.FINEST, "Failed to validate nonce", e);
        return failOrAbstain("Invalid nonce value");
    }
    // validate realm
    if (!realm.equals(token.getRealm())) {
        return failOrAbstain("Invalid realm");
    }
    return userStore.user(token.getUsername()).map(user -> {
        if (token.validateLogin(user)) {
            // yay, correct user and password!!!
            if (subjectType == SubjectType.USER) {
                return AuthenticationResponse.success(buildSubject(user));
            } else {
                return AuthenticationResponse.successService(buildSubject(user));
            }
        } else {
            return failOrAbstain("Invalid username or password");
        }
    }).orElse(failOrAbstain("Invalid username or password"));
}
Also used : Arrays(java.util.Arrays) ProviderRequest(io.helidon.security.ProviderRequest) Random(java.util.Random) Cipher(javax.crypto.Cipher) Level(java.util.logging.Level) SecureRandom(java.security.SecureRandom) AuthenticationProvider(io.helidon.security.spi.AuthenticationProvider) Map(java.util.Map) BigInteger(java.math.BigInteger) Subject(io.helidon.security.Subject) LinkedList(java.util.LinkedList) Config(io.helidon.config.Config) SubjectType(io.helidon.security.SubjectType) SynchronousProvider(io.helidon.security.spi.SynchronousProvider) Logger(java.util.logging.Logger) AuthenticationResponse(io.helidon.security.AuthenticationResponse) Collectors(java.util.stream.Collectors) Principal(io.helidon.security.Principal) Objects(java.util.Objects) TimeUnit(java.util.concurrent.TimeUnit) SecurityResponse(io.helidon.security.SecurityResponse) Base64(java.util.Base64) List(java.util.List) SecurityEnvironment(io.helidon.security.SecurityEnvironment) Role(io.helidon.security.Role) Optional(java.util.Optional) Cipher(javax.crypto.Cipher)

Example 34 with AuthenticationResponse

use of io.helidon.security.AuthenticationResponse in project helidon by oracle.

the class HeaderAtnProviderTest method testServiceExtraction.

@Test
public void testServiceExtraction() {
    HeaderAtnProvider provider = getServiceProvider();
    String username = "service";
    SecurityEnvironment env = SecurityEnvironment.builder().header("Authorization", "bearer " + username).build();
    ProviderRequest request = mock(ProviderRequest.class);
    when(request.env()).thenReturn(env);
    AuthenticationResponse response = provider.syncAuthenticate(request);
    assertThat(response.status(), is(SecurityResponse.SecurityStatus.SUCCESS));
    assertThat(response.user(), is(Optional.empty()));
    assertThat(response.service(), is(not(Optional.empty())));
    response.service().map(Subject::principal).map(Principal::getName).ifPresent(name -> assertThat(name, is(username)));
}
Also used : SecurityEnvironment(io.helidon.security.SecurityEnvironment) AuthenticationResponse(io.helidon.security.AuthenticationResponse) Subject(io.helidon.security.Subject) ProviderRequest(io.helidon.security.ProviderRequest) Test(org.junit.jupiter.api.Test)

Example 35 with AuthenticationResponse

use of io.helidon.security.AuthenticationResponse in project helidon by oracle.

the class HeaderAtnProviderTest method testServiceNoHeaderExtraction.

@Test
public void testServiceNoHeaderExtraction() {
    HeaderAtnProvider provider = getServiceProvider();
    SecurityEnvironment env = SecurityEnvironment.create();
    ProviderRequest request = mock(ProviderRequest.class);
    when(request.env()).thenReturn(env);
    AuthenticationResponse response = provider.syncAuthenticate(request);
    assertThat(response.status(), is(SecurityResponse.SecurityStatus.FAILURE));
    assertThat(response.service(), is(Optional.empty()));
    assertThat(response.user(), is(Optional.empty()));
}
Also used : SecurityEnvironment(io.helidon.security.SecurityEnvironment) AuthenticationResponse(io.helidon.security.AuthenticationResponse) ProviderRequest(io.helidon.security.ProviderRequest) Test(org.junit.jupiter.api.Test)

Aggregations

AuthenticationResponse (io.helidon.security.AuthenticationResponse)60 Test (org.junit.jupiter.api.Test)52 ProviderRequest (io.helidon.security.ProviderRequest)28 SecurityEnvironment (io.helidon.security.SecurityEnvironment)22 SecurityContext (io.helidon.security.SecurityContext)19 EndpointConfig (io.helidon.security.EndpointConfig)15 Subject (io.helidon.security.Subject)15 Principal (io.helidon.security.Principal)12 OutboundSecurityResponse (io.helidon.security.OutboundSecurityResponse)10 SignedJwt (io.helidon.security.jwt.SignedJwt)8 Instant (java.time.Instant)8 Jwt (io.helidon.security.jwt.Jwt)6 Locale (java.util.Locale)6 SecurityResponse (io.helidon.security.SecurityResponse)5 List (java.util.List)5 CoreMatchers.containsString (org.hamcrest.CoreMatchers.containsString)5 Config (io.helidon.config.Config)4 GoogleIdTokenVerifier (com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier)3 Role (io.helidon.security.Role)3 Security (io.helidon.security.Security)3