Search in sources :

Example 1 with AuthenticationResponse

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

the class AtnProviderSyncTest method testFailure.

@Test
public void testFailure() {
    Config config = Config.create(ConfigSources.create(Map.of("atn-object.size", String.valueOf(SIZE))));
    SecurityContext context = mock(SecurityContext.class);
    when(context.user()).thenReturn(Optional.empty());
    when(context.service()).thenReturn(Optional.empty());
    SecurityEnvironment se = SecurityEnvironment.create();
    EndpointConfig ep = EndpointConfig.builder().config("atn-object", config).build();
    ProviderRequest request = mock(ProviderRequest.class);
    when(request.securityContext()).thenReturn(context);
    when(request.env()).thenReturn(se);
    when(request.endpointConfig()).thenReturn(ep);
    AtnProviderSync provider = new AtnProviderSync();
    AuthenticationResponse response = provider.syncAuthenticate(request);
    assertThat(response.status(), is(SecurityResponse.SecurityStatus.FAILURE));
}
Also used : Config(io.helidon.config.Config) EndpointConfig(io.helidon.security.EndpointConfig) SecurityEnvironment(io.helidon.security.SecurityEnvironment) SecurityContext(io.helidon.security.SecurityContext) AuthenticationResponse(io.helidon.security.AuthenticationResponse) EndpointConfig(io.helidon.security.EndpointConfig) ProviderRequest(io.helidon.security.ProviderRequest) Test(org.junit.jupiter.api.Test)

Example 2 with AuthenticationResponse

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

the class ProgrammaticSecurity method login.

private Subject login() {
    SecurityContext securityContext = CONTEXT.get();
    securityContext.env(securityContext.env().derive().path("/some/path").header("Authorization", buildBasic("aUser", "aPassword")));
    AuthenticationResponse response = securityContext.atnClientBuilder().buildAndGet();
    if (response.status().isSuccess()) {
        return response.user().orElseThrow(() -> new IllegalStateException("No user authenticated!"));
    }
    throw new RuntimeException("Failed to authenticate", response.throwable().orElse(null));
}
Also used : SecurityContext(io.helidon.security.SecurityContext) AuthenticationResponse(io.helidon.security.AuthenticationResponse)

Example 3 with AuthenticationResponse

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

the class JwtAuthProviderTest method testRsaBothWays.

@Test
public void testRsaBothWays() {
    String username = "user1";
    String userId = "user1-id";
    String email = "user1@example.org";
    String familyName = "Novak";
    String givenName = "Standa";
    String fullName = "Standa Novak";
    Locale locale = Locale.CANADA_FRENCH;
    Principal principal = Principal.builder().name(username).id(userId).addAttribute("email", email).addAttribute("email_verified", true).addAttribute("family_name", familyName).addAttribute("given_name", givenName).addAttribute("full_name", fullName).addAttribute("locale", locale).build();
    Subject subject = Subject.create(principal);
    JwtAuthProvider provider = JwtAuthProvider.create(Config.create().get("security.providers.0.mp-jwt-auth"));
    SecurityContext context = Mockito.mock(SecurityContext.class);
    when(context.user()).thenReturn(Optional.of(subject));
    ProviderRequest request = mock(ProviderRequest.class);
    when(request.securityContext()).thenReturn(context);
    SecurityEnvironment outboundEnv = SecurityEnvironment.builder().path("/rsa").transport("http").targetUri(URI.create("http://localhost:8080/rsa")).build();
    EndpointConfig outboundEp = EndpointConfig.create();
    assertThat(provider.isOutboundSupported(request, outboundEnv, outboundEp), is(true));
    OutboundSecurityResponse response = provider.syncOutbound(request, outboundEnv, outboundEp);
    String signedToken = response.requestHeaders().get("Authorization").get(0);
    signedToken = signedToken.substring("bearer ".length());
    // now I want to validate it to prove it was correctly signed
    SignedJwt signedJwt = SignedJwt.parseToken(signedToken);
    signedJwt.verifySignature(verifyKeys).checkValid();
    Jwt jwt = signedJwt.getJwt();
    assertThat(jwt.subject(), is(Optional.of(userId)));
    assertThat(jwt.preferredUsername(), is(Optional.of(username)));
    assertThat(jwt.email(), is(Optional.of(email)));
    assertThat(jwt.emailVerified(), is(Optional.of(true)));
    assertThat(jwt.familyName(), is(Optional.of(familyName)));
    assertThat(jwt.givenName(), is(Optional.of(givenName)));
    assertThat(jwt.fullName(), is(Optional.of(fullName)));
    assertThat(jwt.locale(), is(Optional.of(locale)));
    assertThat(jwt.audience(), is(Optional.of(List.of("audience.application.id"))));
    assertThat(jwt.issuer(), is(Optional.of("jwt.example.com")));
    assertThat(jwt.algorithm(), is(Optional.of(JwkRSA.ALG_RS256)));
    assertThat(jwt.issueTime(), is(not(Optional.empty())));
    jwt.issueTime().ifPresent(instant -> {
        boolean compareResult = Instant.now().minusSeconds(10).compareTo(instant) < 0;
        assertThat("Issue time must not be older than 10 seconds", compareResult, is(true));
        Instant expectedNotBefore = instant.minus(60, ChronoUnit.SECONDS);
        assertThat(jwt.notBefore(), is(Optional.of(expectedNotBefore)));
        Instant expectedExpiry = instant.plus(3600, ChronoUnit.SECONDS);
        assertThat(jwt.expirationTime(), is(Optional.of(expectedExpiry)));
    });
    // now we need to use the same token to invoke authentication
    ProviderRequest atnRequest = mockRequest(signedToken);
    AuthenticationResponse authenticationResponse = provider.syncAuthenticate(atnRequest);
    authenticationResponse.user().map(Subject::principal).ifPresentOrElse(atnPrincipal -> {
        assertThat(atnPrincipal.id(), is(userId));
        assertThat(atnPrincipal.getName(), is(username));
        assertThat(atnPrincipal.abacAttribute("email"), is(Optional.of(email)));
        assertThat(atnPrincipal.abacAttribute("email_verified"), is(Optional.of(true)));
        assertThat(atnPrincipal.abacAttribute("family_name"), is(Optional.of(familyName)));
        assertThat(atnPrincipal.abacAttribute("given_name"), is(Optional.of(givenName)));
        assertThat(atnPrincipal.abacAttribute("full_name"), is(Optional.of(fullName)));
        assertThat(atnPrincipal.abacAttribute("locale"), is(Optional.of(locale)));
    }, () -> fail("User must be present in response"));
}
Also used : Locale(java.util.Locale) SecurityEnvironment(io.helidon.security.SecurityEnvironment) SignedJwt(io.helidon.security.jwt.SignedJwt) Jwt(io.helidon.security.jwt.Jwt) Instant(java.time.Instant) SignedJwt(io.helidon.security.jwt.SignedJwt) AuthenticationResponse(io.helidon.security.AuthenticationResponse) Subject(io.helidon.security.Subject) ProviderRequest(io.helidon.security.ProviderRequest) OutboundSecurityResponse(io.helidon.security.OutboundSecurityResponse) SecurityContext(io.helidon.security.SecurityContext) Principal(io.helidon.security.Principal) EndpointConfig(io.helidon.security.EndpointConfig) Test(org.junit.jupiter.api.Test)

Example 4 with AuthenticationResponse

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

the class JwtAuthProviderTest method testOctBothWays.

@Test
public void testOctBothWays() {
    String userId = "user1-id";
    Principal tp = Principal.create(userId);
    Subject subject = Subject.create(tp);
    JwtAuthProvider provider = JwtAuthProvider.create(Config.create().get("security.providers.0.mp-jwt-auth"));
    SecurityContext context = Mockito.mock(SecurityContext.class);
    when(context.user()).thenReturn(Optional.of(subject));
    ProviderRequest request = mock(ProviderRequest.class);
    when(request.securityContext()).thenReturn(context);
    SecurityEnvironment outboundEnv = SecurityEnvironment.builder().path("/oct").transport("http").targetUri(URI.create("http://localhost:8080/oct")).build();
    EndpointConfig outboundEp = EndpointConfig.create();
    assertThat(provider.isOutboundSupported(request, outboundEnv, outboundEp), is(true));
    OutboundSecurityResponse response = provider.syncOutbound(request, outboundEnv, outboundEp);
    String signedToken = response.requestHeaders().get("Authorization").get(0);
    signedToken = signedToken.substring("bearer ".length());
    // now I want to validate it to prove it was correctly signed
    SignedJwt signedJwt = SignedJwt.parseToken(signedToken);
    signedJwt.verifySignature(verifyKeys).checkValid();
    Jwt jwt = signedJwt.getJwt();
    assertThat(jwt.subject(), is(Optional.of(userId)));
    assertThat(jwt.preferredUsername(), is(Optional.of(userId)));
    assertThat(jwt.email(), is(Optional.empty()));
    assertThat(jwt.emailVerified(), is(Optional.empty()));
    assertThat(jwt.familyName(), is(Optional.empty()));
    assertThat(jwt.givenName(), is(Optional.empty()));
    // stored as "name" attribute on principal, full name is stored as "name" in JWT
    assertThat(jwt.fullName(), is(Optional.empty()));
    assertThat(jwt.locale(), is(Optional.empty()));
    assertThat(jwt.audience(), is(Optional.of(List.of("audience.application.id"))));
    assertThat(jwt.issuer(), is(Optional.of("jwt.example.com")));
    assertThat(jwt.algorithm(), is(Optional.of(JwkOctet.ALG_HS256)));
    Instant instant = jwt.issueTime().get();
    boolean compareResult = Instant.now().minusSeconds(10).compareTo(instant) < 0;
    assertThat("Issue time must not be older than 10 seconds", compareResult, is(true));
    Instant expectedNotBefore = instant.minus(5, ChronoUnit.SECONDS);
    assertThat(jwt.notBefore(), is(Optional.of(expectedNotBefore)));
    Instant expectedExpiry = instant.plus(60 * 60 * 24, ChronoUnit.SECONDS);
    assertThat(jwt.expirationTime(), is(Optional.of(expectedExpiry)));
    // now we need to use the same token to invoke authentication
    ProviderRequest atnRequest = mockRequest(signedToken);
    AuthenticationResponse authenticationResponse = provider.syncAuthenticate(atnRequest);
    authenticationResponse.user().map(Subject::principal).ifPresentOrElse(atnPrincipal -> {
        assertThat(atnPrincipal.id(), is(userId));
        assertThat(atnPrincipal.getName(), is(userId));
        assertThat(atnPrincipal.abacAttribute("email"), is(Optional.empty()));
        assertThat(atnPrincipal.abacAttribute("email_verified"), is(Optional.empty()));
        assertThat(atnPrincipal.abacAttribute("family_name"), is(Optional.empty()));
        assertThat(atnPrincipal.abacAttribute("given_name"), is(Optional.empty()));
        assertThat(atnPrincipal.abacAttribute("full_name"), is(Optional.empty()));
        assertThat(atnPrincipal.abacAttribute("locale"), is(Optional.empty()));
    }, () -> fail("User must be present in response"));
}
Also used : SecurityEnvironment(io.helidon.security.SecurityEnvironment) SignedJwt(io.helidon.security.jwt.SignedJwt) Jwt(io.helidon.security.jwt.Jwt) Instant(java.time.Instant) SignedJwt(io.helidon.security.jwt.SignedJwt) AuthenticationResponse(io.helidon.security.AuthenticationResponse) Subject(io.helidon.security.Subject) ProviderRequest(io.helidon.security.ProviderRequest) OutboundSecurityResponse(io.helidon.security.OutboundSecurityResponse) SecurityContext(io.helidon.security.SecurityContext) Principal(io.helidon.security.Principal) EndpointConfig(io.helidon.security.EndpointConfig) Test(org.junit.jupiter.api.Test)

Example 5 with AuthenticationResponse

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

the class JwtAuthProviderTest method testWrongToken.

@Test
public void testWrongToken() {
    JwtAuthProvider provider = JwtAuthProvider.create(Config.create().get("security.providers.0.mp-jwt-auth"));
    // now we need to use the same token to invoke authentication
    ProviderRequest atnRequest = mock(ProviderRequest.class);
    SecurityEnvironment se = SecurityEnvironment.builder().header("Authorization", "bearer " + WRONG_TOKEN).build();
    EndpointConfig ec = mock(EndpointConfig.class);
    SecurityLevel appSecurityLevel = mock(SecurityLevel.class);
    SecurityLevel classSecurityLevel = mock(SecurityLevel.class);
    List<SecurityLevel> securityLevels = new ArrayList<>();
    securityLevels.add(appSecurityLevel);
    securityLevels.add(classSecurityLevel);
    when(ec.securityLevels()).thenReturn(securityLevels);
    when(appSecurityLevel.filterAnnotations(LoginConfig.class, EndpointConfig.AnnotationScope.CLASS)).thenReturn(List.of(new LoginConfig() {

        @Override
        public Class<? extends Annotation> annotationType() {
            return LoginConfig.class;
        }

        @Override
        public String authMethod() {
            return JwtAuthAnnotationAnalyzer.LOGIN_CONFIG_METHOD;
        }

        @Override
        public String realmName() {
            return "helidon-realm";
        }
    }));
    when(atnRequest.env()).thenReturn(se);
    when(atnRequest.endpointConfig()).thenReturn(ec);
    AuthenticationResponse authenticationResponse = provider.syncAuthenticate(atnRequest);
    assertThat(authenticationResponse.service(), is(Optional.empty()));
    assertThat(authenticationResponse.user(), is(Optional.empty()));
    assertThat(authenticationResponse.status(), is(SecurityResponse.SecurityStatus.FAILURE));
}
Also used : SecurityEnvironment(io.helidon.security.SecurityEnvironment) SecurityLevel(io.helidon.security.SecurityLevel) ArrayList(java.util.ArrayList) LoginConfig(org.eclipse.microprofile.auth.LoginConfig) AuthenticationResponse(io.helidon.security.AuthenticationResponse) EndpointConfig(io.helidon.security.EndpointConfig) 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