Search in sources :

Example 16 with Principal

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

the class JwtProviderTest method testInvalidSignatureFail.

@Test
@DisplayName("RSA Invalid Signature: verify-signature = true")
public void testInvalidSignatureFail() {
    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("/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());
    // the token is headers.body.signature
    int lastDot = signedToken.lastIndexOf('.') + 1;
    signedToken = signedToken.substring(0, lastDot) + Base64.getEncoder().encodeToString("invalidSignature".getBytes());
    SignedJwt signedJwt = SignedJwt.parseToken(signedToken);
    assertThat("Should not be valid signature (wrong length)", signedJwt.verifySignature(verifyKeys).isValid(), is(false));
    // 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);
    assertThat(authenticationResponse.status(), is(SecurityResponse.SecurityStatus.FAILURE));
}
Also used : Locale(java.util.Locale) SecurityEnvironment(io.helidon.security.SecurityEnvironment) 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) DisplayName(org.junit.jupiter.api.DisplayName)

Example 17 with Principal

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

the class JwtProvider method buildPrincipal.

Principal buildPrincipal(Jwt jwt) {
    String subject = jwt.subject().orElseThrow(() -> new JwtException("JWT does not contain subject claim, cannot create principal."));
    String name = jwt.preferredUsername().orElse(subject);
    Principal.Builder builder = Principal.builder();
    builder.name(name).id(subject);
    jwt.payloadClaims().forEach((key, jsonValue) -> builder.addAttribute(key, JwtUtil.toObject(jsonValue)));
    jwt.email().ifPresent(value -> builder.addAttribute("email", value));
    jwt.emailVerified().ifPresent(value -> builder.addAttribute("email_verified", value));
    jwt.locale().ifPresent(value -> builder.addAttribute("locale", value));
    jwt.familyName().ifPresent(value -> builder.addAttribute("family_name", value));
    jwt.givenName().ifPresent(value -> builder.addAttribute("given_name", value));
    jwt.fullName().ifPresent(value -> builder.addAttribute("full_name", value));
    return builder.build();
}
Also used : JwtException(io.helidon.security.jwt.JwtException) Principal(io.helidon.security.Principal)

Example 18 with Principal

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

the class JwtProvider method propagate.

private OutboundSecurityResponse propagate(JwtOutboundTarget ot, Subject subject) {
    Map<String, List<String>> headers = new HashMap<>();
    Jwk jwk = signKeys.forKeyId(ot.jwkKid).orElseThrow(() -> new JwtException("Signing JWK with kid: " + ot.jwkKid + " is not defined."));
    Principal principal = subject.principal();
    Jwt.Builder builder = Jwt.builder();
    principal.abacAttributeNames().forEach(name -> {
        principal.abacAttribute(name).ifPresent(val -> builder.addPayloadClaim(name, val));
    });
    principal.abacAttribute("full_name").ifPresentOrElse(name -> builder.addPayloadClaim("name", name), () -> builder.removePayloadClaim("name"));
    builder.subject(principal.id()).preferredUsername(principal.getName()).issuer(issuer).algorithm(jwk.algorithm());
    ot.update(builder);
    Jwt jwt = builder.build();
    SignedJwt signed = SignedJwt.sign(jwt, jwk);
    ot.outboundHandler.header(headers, signed.tokenContent());
    return OutboundSecurityResponse.withHeaders(headers);
}
Also used : HashMap(java.util.HashMap) IdentityHashMap(java.util.IdentityHashMap) SignedJwt(io.helidon.security.jwt.SignedJwt) Jwt(io.helidon.security.jwt.Jwt) List(java.util.List) JwtException(io.helidon.security.jwt.JwtException) SignedJwt(io.helidon.security.jwt.SignedJwt) Principal(io.helidon.security.Principal) Jwk(io.helidon.security.jwt.jwk.Jwk)

Example 19 with Principal

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

the class JwtProviderTest method testInvalidSignatureOk.

@Test
@DisplayName("RSA Invalid Signature: verify-signature = false")
public void testInvalidSignatureOk() {
    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-no-verification"));
    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());
    // the token is headers.body.signature
    int lastDot = signedToken.lastIndexOf('.') + 1;
    signedToken = signedToken.substring(0, lastDot) + Base64.getEncoder().encodeToString("invalidSignature".getBytes());
    SignedJwt signedJwt = SignedJwt.parseToken(signedToken);
    assertThat("Should not be valid signature (wrong length)", signedJwt.verifySignature(verifyKeys).isValid(), is(false));
    // 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) 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) DisplayName(org.junit.jupiter.api.DisplayName)

Example 20 with Principal

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

the class HttpSignProvider method validateSignature.

private AuthenticationResponse validateSignature(SecurityEnvironment env, HttpSignature httpSignature, InboundClientDefinition clientDefinition) {
    // validate algorithm
    Optional<String> validationResult = httpSignature.validate(env, clientDefinition, inboundRequiredHeaders.headers(env.method(), env.headers()));
    if (validationResult.isPresent()) {
        return AuthenticationResponse.failed(validationResult.get());
    }
    Principal principal = Principal.builder().name(clientDefinition.principalName()).addAttribute(ATTRIB_NAME_KEY_ID, clientDefinition.keyId()).build();
    Subject subject = Subject.builder().principal(principal).build();
    if (clientDefinition.subjectType() == SubjectType.USER) {
        return AuthenticationResponse.success(subject);
    } else {
        return AuthenticationResponse.successService(subject);
    }
}
Also used : Principal(io.helidon.security.Principal) Subject(io.helidon.security.Subject)

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