Search in sources :

Example 11 with NonNull

use of io.micronaut.core.annotation.NonNull in project micronaut-views by micronaut-projects.

the class ViewsFilter method resolveMediaType.

/**
 * Resolves the response content type for the matched route.
 * @param response HTTP response
 * @param responseBody HTTP Response body
 * @return The resolved content type
 */
@NonNull
protected MediaType resolveMediaType(@NonNull HttpResponse<?> response, @Nullable Object responseBody) {
    Optional<AnnotationMetadata> routeMatch = response.getAttribute(HttpAttributes.ROUTE_MATCH, AnnotationMetadata.class);
    if (!routeMatch.isPresent()) {
        return MediaType.APPLICATION_JSON_TYPE;
    }
    AnnotationMetadata route = routeMatch.get();
    return route.getValue(Produces.class, MediaType.class).orElse((route.getValue(View.class).isPresent() || responseBody instanceof ModelAndView) ? MediaType.TEXT_HTML_TYPE : MediaType.APPLICATION_JSON_TYPE);
}
Also used : Produces(io.micronaut.http.annotation.Produces) MediaType(io.micronaut.http.MediaType) AnnotationMetadata(io.micronaut.core.annotation.AnnotationMetadata) NonNull(io.micronaut.core.annotation.NonNull)

Example 12 with NonNull

use of io.micronaut.core.annotation.NonNull in project micronaut-gcp by micronaut-projects.

the class GoogleFunctionHttpRequest method getBody.

@NonNull
@Override
public <T> Optional<T> getBody(@NonNull Argument<T> arg) {
    if (arg != null) {
        final Class<T> type = arg.getType();
        final MediaType contentType = getContentType().orElse(MediaType.APPLICATION_JSON_TYPE);
        if (body == null) {
            if (isFormSubmission(contentType)) {
                body = getParameters();
                if (ConvertibleValues.class == type) {
                    return (Optional<T>) Optional.of(body);
                } else {
                    return Optional.empty();
                }
            } else {
                final MediaTypeCodec codec = codecRegistry.findCodec(contentType, type).orElse(null);
                if (codec != null) {
                    try (InputStream inputStream = googleRequest.getInputStream()) {
                        if (ConvertibleValues.class == type) {
                            final Map map = codec.decode(Map.class, inputStream);
                            body = ConvertibleValues.of(map);
                            return (Optional<T>) Optional.of(body);
                        } else {
                            final T value = codec.decode(arg, inputStream);
                            body = value;
                            return Optional.ofNullable(value);
                        }
                    } catch (IOException e) {
                        throw new CodecException("Error decoding request body: " + e.getMessage(), e);
                    }
                }
            }
        } else {
            if (type.isInstance(body)) {
                return (Optional<T>) Optional.of(body);
            } else {
                if (body != httpParameters) {
                    final T result = ConversionService.SHARED.convertRequired(body, arg);
                    return Optional.ofNullable(result);
                }
            }
        }
    }
    return Optional.empty();
}
Also used : InputStream(java.io.InputStream) CodecException(io.micronaut.http.codec.CodecException) IOException(java.io.IOException) MutableConvertibleValuesMap(io.micronaut.core.convert.value.MutableConvertibleValuesMap) MediaTypeCodec(io.micronaut.http.codec.MediaTypeCodec) NonNull(io.micronaut.core.annotation.NonNull)

Example 13 with NonNull

use of io.micronaut.core.annotation.NonNull in project micronaut-gcp by micronaut-projects.

the class GoogleFunctionInitializer method newApplicationContextBuilder.

@NonNull
@Override
protected ApplicationContextBuilder newApplicationContextBuilder() {
    ApplicationContextBuilder builder = super.newApplicationContextBuilder();
    builder.deduceEnvironment(false);
    builder.environments(Environment.GOOGLE_COMPUTE);
    return builder;
}
Also used : ApplicationContextBuilder(io.micronaut.context.ApplicationContextBuilder) NonNull(io.micronaut.core.annotation.NonNull)

Example 14 with NonNull

use of io.micronaut.core.annotation.NonNull in project micronaut-security by micronaut-projects.

the class DefaultTokenEndpointClient method secureRequest.

/**
 * Secures the request according to the context's endpoint supported authentication
 * methods.
 *
 * @param request Token endpoint Request
 * @param requestContext The request context
 * @param <G> The token request grant or body
 * @param <R> The token response type
 */
protected <G, R extends TokenResponse> void secureRequest(@NonNull MutableHttpRequest<G> request, TokenRequestContext<G, R> requestContext) {
    List<AuthenticationMethod> authMethodsSupported = requestContext.getEndpoint().getSupportedAuthenticationMethods().orElseGet(() -> Collections.singletonList(AuthenticationMethod.CLIENT_SECRET_BASIC));
    OauthClientConfiguration clientConfiguration = requestContext.getClientConfiguration();
    if (LOG.isTraceEnabled()) {
        LOG.trace("The token endpoint supports [{}] authentication methods", authMethodsSupported);
    }
    if (authMethodsSupported.contains(AuthenticationMethod.CLIENT_SECRET_BASIC)) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Using client_secret_basic authentication. Adding an Authorization header");
        }
        request.basicAuth(clientConfiguration.getClientId(), clientConfiguration.getClientSecret());
    } else if (authMethodsSupported.contains(AuthenticationMethod.CLIENT_SECRET_POST)) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Using client_secret_post authentication. The client_id and client_secret will be present in the body");
        }
        request.getBody().filter(SecureGrant.class::isInstance).map(SecureGrant.class::cast).ifPresent(body -> {
            body.setClientId(clientConfiguration.getClientId());
            body.setClientSecret(clientConfiguration.getClientSecret());
        });
    } else {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Unsupported or no authentication method. The client_id will be present in the body");
        }
        request.getBody().filter(SecureGrant.class::isInstance).map(SecureGrant.class::cast).ifPresent(body -> body.setClientId(clientConfiguration.getClientId()));
    }
}
Also used : Logger(org.slf4j.Logger) BeanContext(io.micronaut.context.BeanContext) Publisher(org.reactivestreams.Publisher) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) LoggerFactory(org.slf4j.LoggerFactory) HttpClientConfiguration(io.micronaut.http.client.HttpClientConfiguration) Qualifiers(io.micronaut.inject.qualifiers.Qualifiers) Singleton(jakarta.inject.Singleton) AuthenticationMethod(io.micronaut.security.oauth2.endpoint.AuthenticationMethod) OauthClientConfiguration(io.micronaut.security.oauth2.configuration.OauthClientConfiguration) Supplier(java.util.function.Supplier) TokenResponse(io.micronaut.security.oauth2.endpoint.token.response.TokenResponse) NonNull(io.micronaut.core.annotation.NonNull) List(java.util.List) SecureGrant(io.micronaut.security.oauth2.grants.SecureGrant) MediaType(io.micronaut.http.MediaType) Optional(java.util.Optional) HttpRequest(io.micronaut.http.HttpRequest) SupplierUtil(io.micronaut.core.util.SupplierUtil) MutableHttpRequest(io.micronaut.http.MutableHttpRequest) HttpClient(io.micronaut.http.client.HttpClient) LoadBalancer(io.micronaut.http.client.LoadBalancer) Collections(java.util.Collections) TokenRequestContext(io.micronaut.security.oauth2.endpoint.token.request.context.TokenRequestContext) SecureGrant(io.micronaut.security.oauth2.grants.SecureGrant) AuthenticationMethod(io.micronaut.security.oauth2.endpoint.AuthenticationMethod) OauthClientConfiguration(io.micronaut.security.oauth2.configuration.OauthClientConfiguration)

Example 15 with NonNull

use of io.micronaut.core.annotation.NonNull in project micronaut-security by micronaut-projects.

the class DefaultOpenIdTokenResponseValidator method validateClaims.

/**
 * @param clientConfiguration The OAuth 2.0 client configuration
 * @param openIdProviderMetadata The OpenID provider metadata
 * @param jwt JWT with valida signature
 * @param nonce The persisted nonce value
 * @return the same JWT supplied as a parameter if the claims validation were succesful or empty if not.
 */
@NonNull
protected Optional<JWT> validateClaims(@NonNull OauthClientConfiguration clientConfiguration, @NonNull OpenIdProviderMetadata openIdProviderMetadata, @NonNull JWT jwt, @Nullable String nonce) {
    try {
        JWTClaimsSet claimsSet = jwt.getJWTClaimsSet();
        OpenIdClaims claims = new JWTOpenIdClaims(claimsSet);
        if (genericJwtClaimsValidators.stream().allMatch(validator -> validator.validate(claims, null))) {
            if (openIdClaimsValidators.stream().allMatch(validator -> validator.validate(claims, clientConfiguration, openIdProviderMetadata))) {
                if (nonceClaimValidator == null) {
                    if (LOG.isTraceEnabled()) {
                        LOG.trace("Skipping nonce validation because no bean of type {} present. ", NonceClaimValidator.class.getSimpleName());
                    }
                    return Optional.of(jwt);
                }
                if (nonceClaimValidator.validate(claims, clientConfiguration, openIdProviderMetadata, nonce)) {
                    return Optional.of(jwt);
                } else if (LOG.isErrorEnabled()) {
                    LOG.error("Nonce {} validation failed for claims {}", nonce, claims.getClaims().keySet().stream().map(key -> key + "=" + claims.getClaims().get(key)).collect(Collectors.joining(", ", "{", "}")));
                }
            } else if (LOG.isErrorEnabled()) {
                LOG.error("JWT OpenID specific claims validation failed for provider [{}]", clientConfiguration.getName());
            }
        } else if (LOG.isErrorEnabled()) {
            LOG.error("JWT generic claims validation failed for provider [{}]", clientConfiguration.getName());
        }
    } catch (ParseException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Failed to parse the JWT returned from provider [{}]", clientConfiguration.getName(), e);
        }
    }
    return Optional.empty();
}
Also used : JwkValidator(io.micronaut.security.token.jwt.signature.jwks.JwkValidator) Logger(org.slf4j.Logger) Collection(java.util.Collection) JWTOpenIdClaims(io.micronaut.security.oauth2.endpoint.token.response.JWTOpenIdClaims) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) LoggerFactory(org.slf4j.LoggerFactory) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) JwksSignatureConfigurationProperties(io.micronaut.security.token.jwt.signature.jwks.JwksSignatureConfigurationProperties) Singleton(jakarta.inject.Singleton) OauthClientConfiguration(io.micronaut.security.oauth2.configuration.OauthClientConfiguration) JwksSignature(io.micronaut.security.token.jwt.signature.jwks.JwksSignature) Collectors(java.util.stream.Collectors) OpenIdProviderMetadata(io.micronaut.security.oauth2.client.OpenIdProviderMetadata) NonNull(io.micronaut.core.annotation.NonNull) OpenIdClaims(io.micronaut.security.oauth2.endpoint.token.response.OpenIdClaims) GenericJwtClaimsValidator(io.micronaut.security.token.jwt.validator.GenericJwtClaimsValidator) JWT(com.nimbusds.jwt.JWT) Nullable(io.micronaut.core.annotation.Nullable) JwtValidator(io.micronaut.security.token.jwt.validator.JwtValidator) Map(java.util.Map) OpenIdTokenResponse(io.micronaut.security.oauth2.endpoint.token.response.OpenIdTokenResponse) Optional(java.util.Optional) ParseException(java.text.ParseException) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) JWTOpenIdClaims(io.micronaut.security.oauth2.endpoint.token.response.JWTOpenIdClaims) OpenIdClaims(io.micronaut.security.oauth2.endpoint.token.response.OpenIdClaims) JWTOpenIdClaims(io.micronaut.security.oauth2.endpoint.token.response.JWTOpenIdClaims) ParseException(java.text.ParseException) NonNull(io.micronaut.core.annotation.NonNull)

Aggregations

NonNull (io.micronaut.core.annotation.NonNull)19 Singleton (jakarta.inject.Singleton)4 Map (java.util.Map)4 Optional (java.util.Optional)4 Logger (org.slf4j.Logger)3 LoggerFactory (org.slf4j.LoggerFactory)3 ApplicationContextBuilder (io.micronaut.context.ApplicationContextBuilder)2 BeanContext (io.micronaut.context.BeanContext)2 StringUtils (io.micronaut.core.util.StringUtils)2 MediaType (io.micronaut.http.MediaType)2 Qualifiers (io.micronaut.inject.qualifiers.Qualifiers)2 OauthClientConfiguration (io.micronaut.security.oauth2.configuration.OauthClientConfiguration)2 AccessTokenGeneratedEvent (io.micronaut.security.token.event.AccessTokenGeneratedEvent)2 IOException (java.io.IOException)2 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2 BindableRockerModel (com.fizzed.rocker.BindableRockerModel)1 BatchingSettings (com.google.api.gax.batching.BatchingSettings)1 CredentialsProvider (com.google.api.gax.core.CredentialsProvider)1 FixedExecutorProvider (com.google.api.gax.core.FixedExecutorProvider)1 TransportChannelProvider (com.google.api.gax.rpc.TransportChannelProvider)1