Search in sources :

Example 6 with Principal

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

the class JwtAuthTest method testRsa.

@Test
void testRsa() {
    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"));
    io.helidon.security.SecurityContext context = Mockito.mock(io.helidon.security.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);
    // authenticated
    String httpResponse = target.path("/hello").request().header("Authorization", signedToken).get(String.class);
    assertThat(httpResponse, is("Hello user1"));
    httpResponse = target.path("/public").path("/hello").request().header("Authorization", signedToken).get(String.class);
    assertThat(httpResponse, is("Hello user1"));
}
Also used : Locale(java.util.Locale) SecurityEnvironment(io.helidon.security.SecurityEnvironment) JsonString(jakarta.json.JsonString) Principal(io.helidon.security.Principal) Subject(io.helidon.security.Subject) EndpointConfig(io.helidon.security.EndpointConfig) ProviderRequest(io.helidon.security.ProviderRequest) OutboundSecurityResponse(io.helidon.security.OutboundSecurityResponse) HelidonTest(io.helidon.microprofile.tests.junit5.HelidonTest) Test(org.junit.jupiter.api.Test)

Example 7 with Principal

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

the class GoogleTokenProvider method buildSubject.

private Subject buildSubject(String accessToken, GoogleIdToken.Payload payload) {
    TokenCredential.Builder builder = TokenCredential.builder();
    builder.issueTime(toInstant(payload.getIssuedAtTimeSeconds()));
    builder.expTime(toInstant(payload.getExpirationTimeSeconds()));
    builder.issuer(payload.getIssuer());
    builder.token(accessToken);
    builder.addToken(GoogleIdToken.Payload.class, payload);
    String email = payload.getEmail();
    String userId = payload.getSubject();
    Principal principal = Principal.builder().id(userId).name((null == email) ? userId : email).addAttribute("fullName", payload.get("name")).addAttribute("emailVerified", payload.getEmailVerified()).addAttribute("locale", payload.get("locale")).addAttribute("familyName", payload.get("family_name")).addAttribute("givenName", payload.get("given_name")).addAttribute("pictureUrl", payload.get("picture")).build();
    return Subject.builder().principal(principal).addPublicCredential(TokenCredential.class, builder.build()).build();
}
Also used : TokenCredential(io.helidon.security.providers.common.TokenCredential) GoogleIdToken(com.google.api.client.googleapis.auth.oauth2.GoogleIdToken) Principal(io.helidon.security.Principal)

Example 8 with Principal

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

the class GoogleTokenProviderTest method testInbound.

@Test
public void testInbound() {
    ProviderRequest inboundRequest = createInboundRequest("Authorization", "bearer " + TOKEN_VALUE);
    AuthenticationResponse response = provider.syncAuthenticate(inboundRequest);
    assertThat(response.user(), is(not(Optional.empty())));
    response.user().ifPresent(subject -> {
        Principal principal = subject.principal();
        assertThat(principal.getName(), is(name));
        assertThat(principal.id(), is(userId));
    });
}
Also used : AuthenticationResponse(io.helidon.security.AuthenticationResponse) Principal(io.helidon.security.Principal) ProviderRequest(io.helidon.security.ProviderRequest) Test(org.junit.jupiter.api.Test)

Example 9 with Principal

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

the class JwtProvider method buildSubject.

Subject buildSubject(Jwt jwt, SignedJwt signedJwt) {
    Principal principal = buildPrincipal(jwt);
    TokenCredential.Builder builder = TokenCredential.builder();
    jwt.issueTime().ifPresent(builder::issueTime);
    jwt.expirationTime().ifPresent(builder::expTime);
    jwt.issuer().ifPresent(builder::issuer);
    builder.token(signedJwt.tokenContent());
    builder.addToken(Jwt.class, jwt);
    builder.addToken(SignedJwt.class, signedJwt);
    Subject.Builder subjectBuilder = Subject.builder().principal(principal).addPublicCredential(TokenCredential.class, builder.build());
    if (useJwtGroups) {
        Optional<List<String>> userGroups = jwt.userGroups();
        userGroups.ifPresent(groups -> groups.forEach(group -> subjectBuilder.addGrant(Role.create(group))));
    }
    Optional<List<String>> scopes = jwt.scopes();
    scopes.ifPresent(scopeList -> {
        scopeList.forEach(scope -> subjectBuilder.addGrant(Grant.builder().name(scope).type("scope").build()));
    });
    return subjectBuilder.build();
}
Also used : OutboundSecurityResponse(io.helidon.security.OutboundSecurityResponse) ProviderRequest(io.helidon.security.ProviderRequest) JwtException(io.helidon.security.jwt.JwtException) HashMap(java.util.HashMap) SignedJwt(io.helidon.security.jwt.SignedJwt) AuthenticationProvider(io.helidon.security.spi.AuthenticationProvider) Map(java.util.Map) Grant(io.helidon.security.Grant) Subject(io.helidon.security.Subject) TokenCredential(io.helidon.security.providers.common.TokenCredential) IdentityHashMap(java.util.IdentityHashMap) Config(io.helidon.config.Config) JwtUtil(io.helidon.security.jwt.JwtUtil) SubjectType(io.helidon.security.SubjectType) OutboundSecurityProvider(io.helidon.security.spi.OutboundSecurityProvider) SynchronousProvider(io.helidon.security.spi.SynchronousProvider) TokenHandler(io.helidon.security.util.TokenHandler) Instant(java.time.Instant) Logger(java.util.logging.Logger) Resource(io.helidon.common.configurable.Resource) AuthenticationResponse(io.helidon.security.AuthenticationResponse) OutboundConfig(io.helidon.security.providers.common.OutboundConfig) Principal(io.helidon.security.Principal) JwkKeys(io.helidon.security.jwt.jwk.JwkKeys) SecurityResponse(io.helidon.security.SecurityResponse) List(java.util.List) ChronoUnit(java.time.temporal.ChronoUnit) EndpointConfig(io.helidon.security.EndpointConfig) SecurityEnvironment(io.helidon.security.SecurityEnvironment) Jwt(io.helidon.security.jwt.Jwt) OutboundTarget(io.helidon.security.providers.common.OutboundTarget) Role(io.helidon.security.Role) Optional(java.util.Optional) Errors(io.helidon.common.Errors) Jwk(io.helidon.security.jwt.jwk.Jwk) List(java.util.List) TokenCredential(io.helidon.security.providers.common.TokenCredential) Principal(io.helidon.security.Principal) Subject(io.helidon.security.Subject)

Example 10 with Principal

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

the class JwtProviderTest method testEcBothWays.

@Test
public void testEcBothWays() {
    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);
    JwtProvider provider = JwtProvider.create(providersConfig.get("jwt"));
    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("/ec").transport("http").targetUri(URI.create("http://localhost:8080/ec")).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(JwkEC.ALG_ES256)));
    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 = mock(ProviderRequest.class);
    SecurityEnvironment se = SecurityEnvironment.builder().header("Authorization", "bearer " + signedToken).build();
    when(atnRequest.env()).thenReturn(se);
    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)

Aggregations

Principal (io.helidon.security.Principal)22 Subject (io.helidon.security.Subject)16 ProviderRequest (io.helidon.security.ProviderRequest)13 AuthenticationResponse (io.helidon.security.AuthenticationResponse)12 EndpointConfig (io.helidon.security.EndpointConfig)12 OutboundSecurityResponse (io.helidon.security.OutboundSecurityResponse)12 SecurityEnvironment (io.helidon.security.SecurityEnvironment)12 SignedJwt (io.helidon.security.jwt.SignedJwt)12 SecurityContext (io.helidon.security.SecurityContext)10 Jwt (io.helidon.security.jwt.Jwt)10 Test (org.junit.jupiter.api.Test)10 Instant (java.time.Instant)7 Locale (java.util.Locale)7 JwtException (io.helidon.security.jwt.JwtException)6 Config (io.helidon.config.Config)5 HashMap (java.util.HashMap)4 List (java.util.List)4 Role (io.helidon.security.Role)3 Jwk (io.helidon.security.jwt.jwk.Jwk)3 OutboundConfig (io.helidon.security.providers.common.OutboundConfig)3