Search in sources :

Example 6 with Subject

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

the class IdcsMain method main.

/**
 * Start the example.
 *
 * @param args ignored
 */
public static void main(String[] args) {
    // load logging configuration
    LogConfig.configureRuntime();
    Config config = buildConfig();
    Security security = Security.create(config.get("security"));
    // this is needed for proper encryption/decryption of cookies
    Contexts.globalContext().register(security);
    Routing.Builder routing = Routing.builder().register(WebSecurity.create(security, config.get("security"))).register(OidcSupport.create(config)).get("/rest/profile", (req, res) -> {
        Optional<SecurityContext> securityContext = req.context().get(SecurityContext.class);
        res.headers().contentType(MediaType.TEXT_PLAIN.withCharset("UTF-8"));
        res.send("Response from config based service, you are: \n" + securityContext.flatMap(SecurityContext::user).map(Subject::toString).orElse("Security context is null"));
    }).get("/loggedout", (req, res) -> res.send("You have been logged out"));
    theServer = WebServer.create(routing, config.get("server"));
    IdcsUtil.start(theServer);
}
Also used : Security(io.helidon.security.Security) Config(io.helidon.config.Config) SecurityContext(io.helidon.security.SecurityContext) Contexts(io.helidon.common.context.Contexts) MediaType(io.helidon.common.http.MediaType) ConfigSources.file(io.helidon.config.ConfigSources.file) WebServer(io.helidon.webserver.WebServer) Optional(java.util.Optional) WebSecurity(io.helidon.security.integration.webserver.WebSecurity) Subject(io.helidon.security.Subject) OidcSupport(io.helidon.security.providers.oidc.OidcSupport) ConfigSources.classpath(io.helidon.config.ConfigSources.classpath) LogConfig(io.helidon.common.LogConfig) Routing(io.helidon.webserver.Routing) Optional(java.util.Optional) Config(io.helidon.config.Config) LogConfig(io.helidon.common.LogConfig) SecurityContext(io.helidon.security.SecurityContext) Routing(io.helidon.webserver.Routing) Security(io.helidon.security.Security) WebSecurity(io.helidon.security.integration.webserver.WebSecurity) Subject(io.helidon.security.Subject)

Example 7 with Subject

use of io.helidon.security.Subject 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 8 with Subject

use of io.helidon.security.Subject 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 9 with Subject

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

the class JwtAuthProviderTest 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).addAttribute("roles", Set.of("role1", "role2")).build();
    Subject subject = Subject.builder().principal(principal).addGrant(Role.create("group1")).addGrant(Role.create("group2")).addGrant(Role.create("group3")).build();
    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("/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();
    // MP specific additions
    assertThat(jwt.payloadClaim("upn"), not(Optional.empty()));
    assertThat(jwt.payloadClaim("groups"), not(Optional.empty()));
    assertThat(jwt.userPrincipal(), is(Optional.of(username)));
    assertThat(jwt.userGroups(), not(Optional.empty()));
    assertThat(jwt.userGroups().get(), hasItems("group1", "group2", "group3"));
    // End of MP specific additions
    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 = mockRequest(signedToken);
    AuthenticationResponse authenticationResponse = provider.syncAuthenticate(atnRequest);
    authenticationResponse.user().map(Subject::principal).ifPresentOrElse(atnPrincipal -> {
        assertThat(atnPrincipal, instanceOf(JsonWebTokenImpl.class));
        JsonWebTokenImpl jsonWebToken = (JsonWebTokenImpl) atnPrincipal;
        String upn = jsonWebToken.getClaim(Claims.upn.name());
        assertThat(upn, is(username));
        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 10 with Subject

use of io.helidon.security.Subject 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)

Aggregations

Subject (io.helidon.security.Subject)36 ProviderRequest (io.helidon.security.ProviderRequest)22 SecurityContext (io.helidon.security.SecurityContext)18 SecurityEnvironment (io.helidon.security.SecurityEnvironment)18 AuthenticationResponse (io.helidon.security.AuthenticationResponse)17 Test (org.junit.jupiter.api.Test)17 Principal (io.helidon.security.Principal)16 EndpointConfig (io.helidon.security.EndpointConfig)15 OutboundSecurityResponse (io.helidon.security.OutboundSecurityResponse)15 SignedJwt (io.helidon.security.jwt.SignedJwt)11 Config (io.helidon.config.Config)10 Jwt (io.helidon.security.jwt.Jwt)9 Optional (java.util.Optional)8 Instant (java.time.Instant)7 Locale (java.util.Locale)7 TokenCredential (io.helidon.security.providers.common.TokenCredential)6 LinkedList (java.util.LinkedList)6 List (java.util.List)6 Errors (io.helidon.common.Errors)4 MediaType (io.helidon.common.http.MediaType)4