Search in sources :

Example 21 with MessageContext

use of org.apache.cxf.jaxrs.ext.MessageContext in project tomee by apache.

the class JAXRSUtils method processFormParam.

private static Object processFormParam(Message m, String key, Class<?> pClass, Type genericType, Annotation[] paramAnns, String defaultValue, boolean decode) {
    MessageContext mc = new MessageContextImpl(m);
    MediaType mt = mc.getHttpHeaders().getMediaType();
    @SuppressWarnings("unchecked") MultivaluedMap<String, String> params = (MultivaluedMap<String, String>) m.get(FormUtils.FORM_PARAM_MAP);
    String enc = HttpUtils.getEncoding(mt, StandardCharsets.UTF_8.name());
    if (params == null) {
        params = new MetadataMap<>();
        m.put(FormUtils.FORM_PARAM_MAP, params);
        if (mt == null || mt.isCompatible(MediaType.APPLICATION_FORM_URLENCODED_TYPE)) {
            InputStream entityStream = copyAndGetEntityStream(m);
            String body = FormUtils.readBody(entityStream, enc);
            // Do not decode unless the key is empty value, fe @FormParam("")
            FormUtils.populateMapFromStringOrHttpRequest(params, m, body, enc, StringUtils.isEmpty(key) && decode);
        } else {
            if ("multipart".equalsIgnoreCase(mt.getType()) && MediaType.MULTIPART_FORM_DATA_TYPE.isCompatible(mt)) {
                MultipartBody body = AttachmentUtils.getMultipartBody(mc);
                FormUtils.populateMapFromMultipart(params, body, m, decode);
            } else {
                org.apache.cxf.common.i18n.Message errorMsg = new org.apache.cxf.common.i18n.Message("WRONG_FORM_MEDIA_TYPE", BUNDLE, mt.toString());
                LOG.warning(errorMsg.toString());
                throw ExceptionUtils.toNotSupportedException(null, null);
            }
        }
    }
    if (decode && !MessageUtils.getContextualBoolean(m, FormUtils.FORM_PARAM_MAP_DECODED, false)) {
        List<String> values = params.get(key);
        if (values != null) {
            values = values.stream().map(value -> HttpUtils.urlDecode(value, enc)).collect(Collectors.toList());
            params.replace(key, values);
        }
    }
    if ("".equals(key)) {
        return InjectionUtils.handleBean(pClass, paramAnns, params, ParameterType.FORM, m, false);
    }
    List<String> results = params.get(key);
    return InjectionUtils.createParameterObject(results, pClass, genericType, paramAnns, defaultValue, false, ParameterType.FORM, m);
}
Also used : Message(org.apache.cxf.message.Message) ReaderInputStream(org.apache.cxf.io.ReaderInputStream) InputStream(java.io.InputStream) MultipartBody(org.apache.cxf.jaxrs.ext.multipart.MultipartBody) MediaType(javax.ws.rs.core.MediaType) MessageContext(org.apache.cxf.jaxrs.ext.MessageContext) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) MessageContextImpl(org.apache.cxf.jaxrs.ext.MessageContextImpl)

Example 22 with MessageContext

use of org.apache.cxf.jaxrs.ext.MessageContext in project tomee by apache.

the class JAXRSUtils method processRequestBodyParameter.

private static Object processRequestBodyParameter(Class<?> parameterClass, Type parameterType, Annotation[] parameterAnns, Message message, OperationResourceInfo ori) throws IOException, WebApplicationException {
    if (parameterClass == AsyncResponse.class) {
        return new AsyncResponseImpl(message);
    }
    String contentType = (String) message.get(Message.CONTENT_TYPE);
    if (contentType == null) {
        String defaultCt = (String) message.getContextualProperty(DEFAULT_CONTENT_TYPE);
        contentType = defaultCt == null ? MediaType.APPLICATION_OCTET_STREAM : defaultCt;
    }
    final MediaType contentTypeMt = toMediaType(contentType);
    final MessageContext mc = new MessageContextImpl(message);
    MediaType mt = mc.getHttpHeaders().getMediaType();
    if (mt == null) {
        mt = contentTypeMt;
    }
    InputStream is;
    if (mt.isCompatible(MediaType.APPLICATION_FORM_URLENCODED_TYPE)) {
        is = copyAndGetEntityStream(message);
    } else {
        is = message.getContent(InputStream.class);
    }
    if (is == null) {
        Reader reader = message.getContent(Reader.class);
        if (reader != null) {
            is = new ReaderInputStream(reader);
        }
    }
    return readFromMessageBody(parameterClass, parameterType, parameterAnns, is, contentTypeMt, ori, message);
}
Also used : ReaderInputStream(org.apache.cxf.io.ReaderInputStream) ReaderInputStream(org.apache.cxf.io.ReaderInputStream) InputStream(java.io.InputStream) AsyncResponseImpl(org.apache.cxf.jaxrs.impl.AsyncResponseImpl) MediaType(javax.ws.rs.core.MediaType) Reader(java.io.Reader) MessageBodyReader(javax.ws.rs.ext.MessageBodyReader) MessageContext(org.apache.cxf.jaxrs.ext.MessageContext) MessageContextImpl(org.apache.cxf.jaxrs.ext.MessageContextImpl)

Example 23 with MessageContext

use of org.apache.cxf.jaxrs.ext.MessageContext in project meecrowave by apache.

the class OAuth2Configurer method preCompute.

// TODO: still some missing configuration for jwt etc to add/wire from OAuth2Options
@PostConstruct
private void preCompute() {
    configuration = builder.getExtension(OAuth2Options.class);
    final Function<JwtClaims, JwtClaims> customizeClaims = configuration.isUseJwtFormatForAccessTokens() ? claims -> {
        if (claims.getIssuer() == null) {
            claims.setIssuer(configuration.getJwtIssuer());
        }
        return claims;
    } : identity();
    AbstractOAuthDataProvider provider;
    switch(configuration.getProvider().toLowerCase(ENGLISH)) {
        case "jpa":
            {
                if (!configuration.isAuthorizationCodeSupport()) {
                    // else use code impl
                    final JPAOAuthDataProvider jpaProvider = new JPAOAuthDataProvider() {

                        @Override
                        protected JwtClaims createJwtAccessToken(final ServerAccessToken at) {
                            return customizeClaims.apply(super.createJwtAccessToken(at));
                        }

                        @Override
                        protected ServerAccessToken createNewAccessToken(final Client client, final UserSubject userSub) {
                            final ServerAccessToken token = super.createNewAccessToken(client, userSub);
                            forwardClaims(client, userSub, token);
                            return token;
                        }
                    };
                    jpaProvider.setEntityManagerFactory(JPAAdapter.createEntityManagerFactory(configuration));
                    provider = jpaProvider;
                    break;
                }
            }
        case "jpa-code":
            {
                final JPACodeDataProvider jpaProvider = new JPACodeDataProvider() {

                    @Override
                    protected JwtClaims createJwtAccessToken(final ServerAccessToken at) {
                        return customizeClaims.apply(super.createJwtAccessToken(at));
                    }

                    @Override
                    protected ServerAccessToken createNewAccessToken(final Client client, final UserSubject userSub) {
                        final ServerAccessToken token = super.createNewAccessToken(client, userSub);
                        forwardClaims(client, userSub, token);
                        return token;
                    }
                };
                jpaProvider.setEntityManagerFactory(JPAAdapter.createEntityManagerFactory(configuration));
                provider = jpaProvider;
                break;
            }
        case "jcache":
            if (!configuration.isAuthorizationCodeSupport()) {
                // else use code impl
                jCacheConfigurer.doSetup(configuration);
                try {
                    provider = new JCacheOAuthDataProvider(configuration.getJcacheConfigUri(), bus, configuration.isJcacheStoreJwtKeyOnly()) {

                        @Override
                        protected JwtClaims createJwtAccessToken(final ServerAccessToken at) {
                            return customizeClaims.apply(super.createJwtAccessToken(at));
                        }

                        @Override
                        protected ServerAccessToken createNewAccessToken(final Client client, final UserSubject userSub) {
                            final ServerAccessToken token = super.createNewAccessToken(client, userSub);
                            forwardClaims(client, userSub, token);
                            return token;
                        }
                    };
                } catch (final Exception e) {
                    throw new IllegalStateException(e);
                }
                break;
            }
        case "jcache-code":
            jCacheConfigurer.doSetup(configuration);
            try {
                provider = new JCacheCodeDataProvider(configuration, bus) {

                    @Override
                    protected JwtClaims createJwtAccessToken(final ServerAccessToken at) {
                        return customizeClaims.apply(super.createJwtAccessToken(at));
                    }

                    @Override
                    protected ServerAccessToken createNewAccessToken(final Client client, final UserSubject userSub) {
                        final ServerAccessToken token = super.createNewAccessToken(client, userSub);
                        forwardClaims(client, userSub, token);
                        return token;
                    }
                };
            } catch (final Exception e) {
                throw new IllegalStateException(e);
            }
            break;
        case "encrypted":
            if (!configuration.isAuthorizationCodeSupport()) {
                // else use code impl
                provider = new DefaultEncryptingOAuthDataProvider(new SecretKeySpec(configuration.getEncryptedKey().getBytes(StandardCharsets.UTF_8), configuration.getEncryptedAlgo())) {

                    @Override
                    protected JwtClaims createJwtAccessToken(final ServerAccessToken at) {
                        return customizeClaims.apply(super.createJwtAccessToken(at));
                    }

                    @Override
                    protected ServerAccessToken createNewAccessToken(final Client client, final UserSubject userSub) {
                        final ServerAccessToken token = super.createNewAccessToken(client, userSub);
                        forwardClaims(client, userSub, token);
                        return token;
                    }
                };
                break;
            }
        case "encrypted-code":
            provider = new DefaultEncryptingCodeDataProvider(new SecretKeySpec(configuration.getEncryptedKey().getBytes(StandardCharsets.UTF_8), configuration.getEncryptedAlgo())) {

                @Override
                protected JwtClaims createJwtAccessToken(final ServerAccessToken at) {
                    return customizeClaims.apply(super.createJwtAccessToken(at));
                }

                @Override
                protected ServerAccessToken createNewAccessToken(final Client client, final UserSubject userSub) {
                    final ServerAccessToken token = super.createNewAccessToken(client, userSub);
                    forwardClaims(client, userSub, token);
                    return token;
                }
            };
            break;
        default:
            throw new IllegalArgumentException("Unsupported oauth2 provider: " + configuration.getProvider());
    }
    final RefreshTokenGrantHandler refreshTokenGrantHandler = new RefreshTokenGrantHandler() {

        @Override
        public ServerAccessToken createAccessToken(final Client client, final MultivaluedMap<String, String> params) throws OAuthServiceException {
            final ServerAccessToken accessToken = super.createAccessToken(client, params);
            forwardClaims(client, accessToken.getSubject(), accessToken);
            return accessToken;
        }
    };
    refreshTokenGrantHandler.setDataProvider(provider);
    refreshTokenGrantHandler.setUseAllClientScopes(configuration.isUseAllClientScopes());
    refreshTokenGrantHandler.setPartialMatchScopeValidation(configuration.isPartialMatchScopeValidation());
    final ResourceOwnerLoginHandler loginHandler = configuration.isJaas() ? new JAASResourceOwnerLoginHandler() {

        @Override
        public UserSubject createSubject(final Client client, final String name, final String password) {
            final UserSubject subject = super.createSubject(client, name, password);
            forwardRolesAsClaims(subject);
            return subject;
        }
    } : (client, name, password) -> {
        try {
            request.login(name, password);
            try {
                final Principal pcp = request.getUserPrincipal();
                return doCreateUserSubject(pcp);
            } finally {
                request.logout();
            }
        } catch (final ServletException e) {
            throw new AuthenticationException(e.getMessage());
        }
    };
    final List<AccessTokenGrantHandler> handlers = new ArrayList<>();
    handlers.add(refreshTokenGrantHandler);
    handlers.add(new ClientCredentialsGrantHandler() {

        @Override
        protected ServerAccessToken doCreateAccessToken(final Client client, final UserSubject subject, final String requestedGrant, final List<String> requestedScopes, final List<String> audiences) {
            final ServerAccessToken serverAccessToken = super.doCreateAccessToken(client, subject, requestedGrant, requestedScopes, audiences);
            forwardClaims(client, subject, serverAccessToken);
            return serverAccessToken;
        }
    });
    handlers.add(new ResourceOwnerGrantHandler() {

        {
            setLoginHandler(loginHandler);
        }

        @Override
        protected ServerAccessToken doCreateAccessToken(final Client client, final UserSubject subject, final String requestedGrant, final List<String> requestedScopes, final List<String> audiences) {
            final ServerAccessToken serverAccessToken = super.doCreateAccessToken(client, subject, requestedGrant, requestedScopes, audiences);
            forwardClaims(client, subject, serverAccessToken);
            return serverAccessToken;
        }
    });
    handlers.add(new AuthorizationCodeGrantHandler() {

        @Override
        public ServerAccessToken createAccessToken(final Client client, final MultivaluedMap<String, String> params) throws OAuthServiceException {
            if (configuration.isUseS256CodeChallenge()) {
                setCodeVerifierTransformer(new DigestCodeVerifier());
            }
            return super.createAccessToken(client, params);
        }

        @Override
        protected ServerAccessToken doCreateAccessToken(final Client client, final UserSubject subject, final String requestedGrant, final List<String> requestedScopes, final List<String> audiences) {
            final ServerAccessToken serverAccessToken = super.doCreateAccessToken(client, subject, requestedGrant, requestedScopes, audiences);
            forwardClaims(client, subject, serverAccessToken);
            return serverAccessToken;
        }
    });
    handlers.add(new JwtBearerGrantHandler() {

        @Override
        protected ServerAccessToken doCreateAccessToken(final Client client, final UserSubject subject, final String requestedGrant, final List<String> requestedScopes, final List<String> audiences) {
            final ServerAccessToken serverAccessToken = super.doCreateAccessToken(client, subject, requestedGrant, requestedScopes, audiences);
            forwardClaims(client, subject, serverAccessToken);
            return serverAccessToken;
        }
    });
    provider.setUseJwtFormatForAccessTokens(configuration.isUseJwtFormatForAccessTokens());
    provider.setAccessTokenLifetime(configuration.getAccessTokenLifetime());
    provider.setRefreshTokenLifetime(configuration.getRefreshTokenLifetime());
    provider.setRecycleRefreshTokens(configuration.isRecycleRefreshTokens());
    provider.setSupportPreauthorizedTokens(configuration.isSupportPreauthorizedTokens());
    ofNullable(configuration.getRequiredScopes()).map(s -> asList(s.split(","))).ifPresent(provider::setRequiredScopes);
    ofNullable(configuration.getDefaultScopes()).map(s -> asList(s.split(","))).ifPresent(provider::setDefaultScopes);
    ofNullable(configuration.getInvisibleToClientScopes()).map(s -> asList(s.split(","))).ifPresent(provider::setInvisibleToClientScopes);
    ofNullable(configuration.getJwtAccessTokenClaimMap()).map(s -> new Properties() {

        {
            try {
                load(new StringReader(s));
            } catch (IOException e) {
                throw new IllegalArgumentException("Bad claim map configuration, use properties syntax");
            }
        }
    }).ifPresent(m -> provider.setJwtAccessTokenClaimMap(new HashMap<>(Map.class.cast(m))));
    final OAuthDataProvider dataProvider;
    if (configuration.isRefreshToken()) {
        dataProvider = new RefreshTokenEnabledProvider(provider);
        if (provider.getInvisibleToClientScopes() == null) {
            provider.setInvisibleToClientScopes(new ArrayList<>());
        }
        provider.getInvisibleToClientScopes().add(OAuthConstants.REFRESH_TOKEN_SCOPE);
    } else {
        dataProvider = provider;
    }
    handlers.stream().filter(AbstractGrantHandler.class::isInstance).forEach(h -> {
        final AbstractGrantHandler handler = AbstractGrantHandler.class.cast(h);
        handler.setDataProvider(dataProvider);
        handler.setCanSupportPublicClients(configuration.isCanSupportPublicClients());
        handler.setPartialMatchScopeValidation(configuration.isPartialMatchScopeValidation());
    });
    abstractTokenServiceConsumer = s -> {
        // this is used @RequestScoped so ensure it is not slow for no reason
        s.setCanSupportPublicClients(configuration.isCanSupportPublicClients());
        s.setBlockUnsecureRequests(configuration.isBlockUnsecureRequests());
        s.setWriteCustomErrors(configuration.isWriteCustomErrors());
        s.setWriteOptionalParameters(configuration.isWriteOptionalParameters());
        s.setDataProvider(dataProvider);
    };
    tokenServiceConsumer = s -> {
        // this is used @RequestScoped so ensure it is not slow for no reason
        abstractTokenServiceConsumer.accept(s);
        s.setGrantHandlers(handlers);
    };
    final List<String> noConsentScopes = ofNullable(configuration.getScopesRequiringNoConsent()).map(s -> asList(s.split(","))).orElse(null);
    // we prefix them oauth2.cxf. but otherwise it is the plain cxf config
    securityProperties = ofNullable(builder.getProperties()).map(Properties::stringPropertyNames).orElse(emptySet()).stream().filter(s -> s.startsWith("oauth2.cxf.rs.security.")).collect(toMap(s -> s.substring("oauth2.cxf.".length()), s -> builder.getProperties().getProperty(s)));
    final JoseSessionTokenProvider sessionAuthenticityTokenProvider = new JoseSessionTokenProvider() {

        @Override
        public String createSessionToken(final MessageContext mc, final MultivaluedMap<String, String> params, final UserSubject subject, final OAuthRedirectionState secData) {
            // CXF-8368
            secData.setClientCodeChallenge(params.getFirst(OAuthConstants.AUTHORIZATION_CODE_CHALLENGE));
            return super.createSessionToken(mc, params, subject, secData);
        }
    };
    sessionAuthenticityTokenProvider.setMaxDefaultSessionInterval(configuration.getMaxDefaultSessionInterval());
    // TODO: other configs
    redirectionBasedGrantServiceConsumer = s -> {
        s.setDataProvider(dataProvider);
        s.setBlockUnsecureRequests(configuration.isBlockUnsecureRequests());
        s.setWriteOptionalParameters(configuration.isWriteOptionalParameters());
        s.setUseAllClientScopes(configuration.isUseAllClientScopes());
        s.setPartialMatchScopeValidation(configuration.isPartialMatchScopeValidation());
        s.setUseRegisteredRedirectUriIfPossible(configuration.isUseRegisteredRedirectUriIfPossible());
        s.setMaxDefaultSessionInterval(configuration.getMaxDefaultSessionInterval());
        s.setMatchRedirectUriWithApplicationUri(configuration.isMatchRedirectUriWithApplicationUri());
        s.setScopesRequiringNoConsent(noConsentScopes);
        s.setSessionAuthenticityTokenProvider(sessionAuthenticityTokenProvider);
        s.setCanSupportPublicClients(configuration.isCanSupportPublicClients());
    };
}
Also used : JCacheOAuthDataProvider(org.apache.cxf.rs.security.oauth2.provider.JCacheOAuthDataProvider) ServletException(javax.servlet.ServletException) AccessTokenService(org.apache.cxf.rs.security.oauth2.services.AccessTokenService) SecretKeySpec(javax.crypto.spec.SecretKeySpec) JAXRSUtils(org.apache.cxf.jaxrs.utils.JAXRSUtils) ServerAccessToken(org.apache.cxf.rs.security.oauth2.common.ServerAccessToken) Collectors.toMap(java.util.stream.Collectors.toMap) AbstractTokenService(org.apache.cxf.rs.security.oauth2.services.AbstractTokenService) JwtClaims(org.apache.cxf.rs.security.jose.jwt.JwtClaims) ClientCredentialsGrantHandler(org.apache.cxf.rs.security.oauth2.grants.clientcred.ClientCredentialsGrantHandler) Arrays.asList(java.util.Arrays.asList) Map(java.util.Map) JCacheCodeDataProvider(org.apache.meecrowave.oauth2.provider.JCacheCodeDataProvider) RefreshTokenEnabledProvider(org.apache.meecrowave.oauth2.data.RefreshTokenEnabledProvider) AuthorizationCodeGrantHandler(org.apache.cxf.rs.security.oauth2.grants.code.AuthorizationCodeGrantHandler) DefaultEncryptingCodeDataProvider(org.apache.cxf.rs.security.oauth2.grants.code.DefaultEncryptingCodeDataProvider) JwtBearerGrantHandler(org.apache.cxf.rs.security.oauth2.grants.jwt.JwtBearerGrantHandler) ResourceOwnerLoginHandler(org.apache.cxf.rs.security.oauth2.grants.owner.ResourceOwnerLoginHandler) ENGLISH(java.util.Locale.ENGLISH) AuthenticationMethod(org.apache.cxf.rs.security.oauth2.common.AuthenticationMethod) ResourceOwnerGrantHandler(org.apache.cxf.rs.security.oauth2.grants.owner.ResourceOwnerGrantHandler) JPACodeDataProvider(org.apache.cxf.rs.security.oauth2.grants.code.JPACodeDataProvider) StandardCharsets(java.nio.charset.StandardCharsets) OAuthDataProvider(org.apache.cxf.rs.security.oauth2.provider.OAuthDataProvider) List(java.util.List) Principal(java.security.Principal) AbstractGrantHandler(org.apache.cxf.rs.security.oauth2.grants.AbstractGrantHandler) PostConstruct(javax.annotation.PostConstruct) Function.identity(java.util.function.Function.identity) ApplicationScoped(javax.enterprise.context.ApplicationScoped) PASSWORD(org.apache.cxf.rs.security.oauth2.common.AuthenticationMethod.PASSWORD) AccessTokenGrantHandler(org.apache.cxf.rs.security.oauth2.provider.AccessTokenGrantHandler) Meecrowave(org.apache.meecrowave.Meecrowave) Bus(org.apache.cxf.Bus) JAASResourceOwnerLoginHandler(org.apache.cxf.rs.security.oauth2.grants.owner.JAASResourceOwnerLoginHandler) OAuthServiceException(org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException) RefreshTokenGrantHandler(org.apache.cxf.rs.security.oauth2.grants.refresh.RefreshTokenGrantHandler) AuthorizationCodeGrantService(org.apache.cxf.rs.security.oauth2.services.AuthorizationCodeGrantService) HashMap(java.util.HashMap) Function(java.util.function.Function) ArrayList(java.util.ArrayList) Inject(javax.inject.Inject) AbstractOAuthDataProvider(org.apache.cxf.rs.security.oauth2.provider.AbstractOAuthDataProvider) HttpServletRequest(javax.servlet.http.HttpServletRequest) AuthenticationException(org.apache.cxf.interceptor.security.AuthenticationException) MessageContext(org.apache.cxf.jaxrs.ext.MessageContext) DefaultEncryptingOAuthDataProvider(org.apache.cxf.rs.security.oauth2.provider.DefaultEncryptingOAuthDataProvider) PlainCodeVerifier(org.apache.cxf.rs.security.oauth2.grants.code.PlainCodeVerifier) JoseSessionTokenProvider(org.apache.cxf.rs.security.oauth2.provider.JoseSessionTokenProvider) Client(org.apache.cxf.rs.security.oauth2.common.Client) GenericPrincipal(org.apache.catalina.realm.GenericPrincipal) Properties(java.util.Properties) JPAOAuthDataProvider(org.apache.cxf.rs.security.oauth2.provider.JPAOAuthDataProvider) Collections.emptySet(java.util.Collections.emptySet) Message(org.apache.cxf.message.Message) Optional.ofNullable(java.util.Optional.ofNullable) IOException(java.io.IOException) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) Consumer(java.util.function.Consumer) StringReader(java.io.StringReader) PhaseInterceptorChain(org.apache.cxf.phase.PhaseInterceptorChain) OAuthConstants(org.apache.cxf.rs.security.oauth2.utils.OAuthConstants) UserSubject(org.apache.cxf.rs.security.oauth2.common.UserSubject) DigestCodeVerifier(org.apache.cxf.rs.security.oauth2.grants.code.DigestCodeVerifier) Collections(java.util.Collections) OAuthRedirectionState(org.apache.cxf.rs.security.oauth2.common.OAuthRedirectionState) AbstractGrantHandler(org.apache.cxf.rs.security.oauth2.grants.AbstractGrantHandler) JwtClaims(org.apache.cxf.rs.security.jose.jwt.JwtClaims) JPAOAuthDataProvider(org.apache.cxf.rs.security.oauth2.provider.JPAOAuthDataProvider) AuthenticationException(org.apache.cxf.interceptor.security.AuthenticationException) OAuthServiceException(org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) JPACodeDataProvider(org.apache.cxf.rs.security.oauth2.grants.code.JPACodeDataProvider) ResourceOwnerLoginHandler(org.apache.cxf.rs.security.oauth2.grants.owner.ResourceOwnerLoginHandler) JAASResourceOwnerLoginHandler(org.apache.cxf.rs.security.oauth2.grants.owner.JAASResourceOwnerLoginHandler) JoseSessionTokenProvider(org.apache.cxf.rs.security.oauth2.provider.JoseSessionTokenProvider) ServletException(javax.servlet.ServletException) SecretKeySpec(javax.crypto.spec.SecretKeySpec) Client(org.apache.cxf.rs.security.oauth2.common.Client) JCacheCodeDataProvider(org.apache.meecrowave.oauth2.provider.JCacheCodeDataProvider) OAuthRedirectionState(org.apache.cxf.rs.security.oauth2.common.OAuthRedirectionState) DefaultEncryptingOAuthDataProvider(org.apache.cxf.rs.security.oauth2.provider.DefaultEncryptingOAuthDataProvider) RefreshTokenGrantHandler(org.apache.cxf.rs.security.oauth2.grants.refresh.RefreshTokenGrantHandler) RefreshTokenEnabledProvider(org.apache.meecrowave.oauth2.data.RefreshTokenEnabledProvider) ServerAccessToken(org.apache.cxf.rs.security.oauth2.common.ServerAccessToken) JCacheOAuthDataProvider(org.apache.cxf.rs.security.oauth2.provider.JCacheOAuthDataProvider) Collectors.toMap(java.util.stream.Collectors.toMap) Map(java.util.Map) HashMap(java.util.HashMap) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) DefaultEncryptingCodeDataProvider(org.apache.cxf.rs.security.oauth2.grants.code.DefaultEncryptingCodeDataProvider) AccessTokenGrantHandler(org.apache.cxf.rs.security.oauth2.provider.AccessTokenGrantHandler) Properties(java.util.Properties) UserSubject(org.apache.cxf.rs.security.oauth2.common.UserSubject) ResourceOwnerGrantHandler(org.apache.cxf.rs.security.oauth2.grants.owner.ResourceOwnerGrantHandler) StringReader(java.io.StringReader) MessageContext(org.apache.cxf.jaxrs.ext.MessageContext) AbstractOAuthDataProvider(org.apache.cxf.rs.security.oauth2.provider.AbstractOAuthDataProvider) DigestCodeVerifier(org.apache.cxf.rs.security.oauth2.grants.code.DigestCodeVerifier) JwtBearerGrantHandler(org.apache.cxf.rs.security.oauth2.grants.jwt.JwtBearerGrantHandler) AuthorizationCodeGrantHandler(org.apache.cxf.rs.security.oauth2.grants.code.AuthorizationCodeGrantHandler) IOException(java.io.IOException) ServletException(javax.servlet.ServletException) OAuthServiceException(org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException) AuthenticationException(org.apache.cxf.interceptor.security.AuthenticationException) IOException(java.io.IOException) ClientCredentialsGrantHandler(org.apache.cxf.rs.security.oauth2.grants.clientcred.ClientCredentialsGrantHandler) JCacheOAuthDataProvider(org.apache.cxf.rs.security.oauth2.provider.JCacheOAuthDataProvider) OAuthDataProvider(org.apache.cxf.rs.security.oauth2.provider.OAuthDataProvider) AbstractOAuthDataProvider(org.apache.cxf.rs.security.oauth2.provider.AbstractOAuthDataProvider) DefaultEncryptingOAuthDataProvider(org.apache.cxf.rs.security.oauth2.provider.DefaultEncryptingOAuthDataProvider) JPAOAuthDataProvider(org.apache.cxf.rs.security.oauth2.provider.JPAOAuthDataProvider) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) JAASResourceOwnerLoginHandler(org.apache.cxf.rs.security.oauth2.grants.owner.JAASResourceOwnerLoginHandler) Principal(java.security.Principal) GenericPrincipal(org.apache.catalina.realm.GenericPrincipal) PostConstruct(javax.annotation.PostConstruct)

Example 24 with MessageContext

use of org.apache.cxf.jaxrs.ext.MessageContext in project carbon-apimgt by wso2.

the class RuntimeArtifactsApiServiceImpl method runtimeArtifactsGet.

public Response runtimeArtifactsGet(String xWSO2Tenant, String apiId, String gatewayLabel, String type, String name, String version, MessageContext messageContext) throws APIManagementException {
    xWSO2Tenant = SubscriptionValidationDataUtil.validateTenantDomain(xWSO2Tenant, messageContext);
    RuntimeArtifactDto runtimeArtifactDto = RuntimeArtifactGeneratorUtil.generateRuntimeArtifact(apiId, name, version, gatewayLabel, type, xWSO2Tenant);
    if (runtimeArtifactDto != null) {
        if (runtimeArtifactDto.isFile()) {
            File artifact = (File) runtimeArtifactDto.getArtifact();
            StreamingOutput streamingOutput = (outputStream) -> {
                try {
                    Files.copy(artifact.toPath(), outputStream);
                } finally {
                    Files.delete(artifact.toPath());
                }
            };
            return Response.ok(streamingOutput).header(RestApiConstants.HEADER_CONTENT_DISPOSITION, "attachment; filename=apis.zip").header(RestApiConstants.HEADER_CONTENT_TYPE, APIConstants.APPLICATION_ZIP).build();
        } else {
            SynapseArtifactListDTO synapseArtifactListDTO = new SynapseArtifactListDTO();
            if (runtimeArtifactDto.getArtifact() instanceof List) {
                synapseArtifactListDTO.setList((List<String>) runtimeArtifactDto.getArtifact());
                synapseArtifactListDTO.setCount(((List<String>) runtimeArtifactDto.getArtifact()).size());
            }
            return Response.ok().entity(synapseArtifactListDTO).header(RestApiConstants.HEADER_CONTENT_TYPE, RestApiConstants.APPLICATION_JSON).build();
        }
    } else {
        return Response.status(Response.Status.NOT_FOUND).entity(RestApiUtil.getErrorDTO(ExceptionCodes.NO_API_ARTIFACT_FOUND)).build();
    }
}
Also used : SynapseArtifactListDTO(org.wso2.carbon.apimgt.internal.service.dto.SynapseArtifactListDTO) Files(java.nio.file.Files) RuntimeArtifactDto(org.wso2.carbon.apimgt.impl.dto.RuntimeArtifactDto) RuntimeArtifactGeneratorUtil(org.wso2.carbon.apimgt.impl.gatewayartifactsynchronizer.RuntimeArtifactGeneratorUtil) RestApiUtil(org.wso2.carbon.apimgt.rest.api.util.utils.RestApiUtil) StreamingOutput(javax.ws.rs.core.StreamingOutput) File(java.io.File) APIConstants(org.wso2.carbon.apimgt.impl.APIConstants) SubscriptionValidationDataUtil(org.wso2.carbon.apimgt.internal.service.utils.SubscriptionValidationDataUtil) List(java.util.List) MessageContext(org.apache.cxf.jaxrs.ext.MessageContext) Response(javax.ws.rs.core.Response) RestApiConstants(org.wso2.carbon.apimgt.rest.api.common.RestApiConstants) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ExceptionCodes(org.wso2.carbon.apimgt.api.ExceptionCodes) RuntimeArtifactsApiService(org.wso2.carbon.apimgt.internal.service.RuntimeArtifactsApiService) SynapseArtifactListDTO(org.wso2.carbon.apimgt.internal.service.dto.SynapseArtifactListDTO) RuntimeArtifactDto(org.wso2.carbon.apimgt.impl.dto.RuntimeArtifactDto) StreamingOutput(javax.ws.rs.core.StreamingOutput) List(java.util.List) File(java.io.File)

Example 25 with MessageContext

use of org.apache.cxf.jaxrs.ext.MessageContext in project carbon-apimgt by wso2.

the class AlertSubscriptionsApiServiceImpl method subscribeToAlerts.

/**
 * Subscribes the logged in user for requested admin alert types
 *
 * @param body
 * @param messageContext
 * @return
 */
@Override
public Response subscribeToAlerts(AlertsSubscriptionDTO body, MessageContext messageContext) {
    // Validate for empty list of emails
    List<String> emailsList = body.getEmailList();
    if (emailsList == null || emailsList.size() == 0) {
        RestApiUtil.handleBadRequest("Email list cannot be empty", log);
    }
    // Validate for empty list of alerts
    List<AlertTypeDTO> subscribingAlertDTOs = body.getAlerts();
    if (subscribingAlertDTOs == null || subscribingAlertDTOs.size() == 0) {
        RestApiUtil.handleBadRequest("Alert list should not be empty", log);
    }
    String fullyQualifiedUsername = getFullyQualifiedUsername(RestApiCommonUtil.getLoggedInUsername());
    try {
        AdminAlertConfigurator adminAlertConfigurator = (AdminAlertConfigurator) AlertConfigManager.getInstance().getAlertConfigurator(AlertMgtConstants.ADMIN_DASHBOARD_AGENT);
        // Retrieve the supported alert types
        List<org.wso2.carbon.apimgt.impl.dto.AlertTypeDTO> supportedAlertTypes = adminAlertConfigurator.getSupportedAlertTypes();
        Map<String, org.wso2.carbon.apimgt.impl.dto.AlertTypeDTO> supportedAlertTypesMap = supportedAlertTypes.stream().collect(Collectors.toMap(org.wso2.carbon.apimgt.impl.dto.AlertTypeDTO::getName, alertType -> alertType));
        List<org.wso2.carbon.apimgt.impl.dto.AlertTypeDTO> alertTypesToSubscribe = new ArrayList<>();
        // Validate the request alerts against supported alert types
        for (AlertTypeDTO subscribingAlertDTO : subscribingAlertDTOs) {
            if (supportedAlertTypesMap.containsKey(subscribingAlertDTO.getName())) {
                alertTypesToSubscribe.add(supportedAlertTypesMap.get(subscribingAlertDTO.getName()));
            } else {
                RestApiUtil.handleBadRequest("Unsupported alert type : " + subscribingAlertDTO.getName() + " is provided.", log);
                return null;
            }
        }
        adminAlertConfigurator.subscribe(fullyQualifiedUsername, emailsList, alertTypesToSubscribe);
        AlertsSubscriptionDTO subscribedAlerts = new AlertsSubscriptionDTO();
        subscribedAlerts.setAlerts(AlertsMappingUtil.fromAlertTypesListToAlertTypeDTOList(alertTypesToSubscribe));
        subscribedAlerts.setEmailList(emailsList);
        return Response.status(Response.Status.OK).entity(subscribedAlerts).build();
    } catch (AlertManagementException e) {
        return Response.status(Response.Status.BAD_REQUEST).entity("API Manager analytics is not Enabled").build();
    } catch (APIManagementException e) {
        RestApiUtil.handleInternalServerError("Error while subscribing to alert types", e, log);
    }
    return null;
}
Also used : MultitenantConstants(org.wso2.carbon.utils.multitenancy.MultitenantConstants) APIAdminImpl(org.wso2.carbon.apimgt.impl.APIAdminImpl) AlertMgtConstants(org.wso2.carbon.apimgt.impl.alertmgt.AlertMgtConstants) APIAdmin(org.wso2.carbon.apimgt.api.APIAdmin) StringUtils(org.apache.commons.lang3.StringUtils) ArrayList(java.util.ArrayList) AlertsSubscriptionDTO(org.wso2.carbon.apimgt.rest.api.admin.v1.dto.AlertsSubscriptionDTO) RestApiCommonUtil(org.wso2.carbon.apimgt.rest.api.common.RestApiCommonUtil) AlertsMappingUtil(org.wso2.carbon.apimgt.rest.api.admin.v1.utils.mappings.AlertsMappingUtil) MessageContext(org.apache.cxf.jaxrs.ext.MessageContext) AlertConfigManager(org.wso2.carbon.apimgt.impl.alertmgt.AlertConfigManager) Map(java.util.Map) AlertManagementException(org.wso2.carbon.apimgt.impl.alertmgt.exception.AlertManagementException) AdminAlertConfigurator(org.wso2.carbon.apimgt.impl.alertmgt.AdminAlertConfigurator) ExceptionCodes(org.wso2.carbon.apimgt.api.ExceptionCodes) BotDetectionData(org.wso2.carbon.apimgt.api.model.botDataAPI.BotDetectionData) RestApiUtil(org.wso2.carbon.apimgt.rest.api.util.utils.RestApiUtil) Collectors(java.util.stream.Collectors) AlertSubscriptionsApiService(org.wso2.carbon.apimgt.rest.api.admin.v1.AlertSubscriptionsApiService) BotDetectionAlertSubscriptionDTO(org.wso2.carbon.apimgt.rest.api.admin.v1.dto.BotDetectionAlertSubscriptionDTO) List(java.util.List) BotDetectionAlertSubscriptionListDTO(org.wso2.carbon.apimgt.rest.api.admin.v1.dto.BotDetectionAlertSubscriptionListDTO) Response(javax.ws.rs.core.Response) AlertTypeDTO(org.wso2.carbon.apimgt.rest.api.admin.v1.dto.AlertTypeDTO) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Log(org.apache.commons.logging.Log) LogFactory(org.apache.commons.logging.LogFactory) BotDetectionMappingUtil(org.wso2.carbon.apimgt.rest.api.admin.v1.utils.mappings.BotDetectionMappingUtil) AlertsSubscriptionDTO(org.wso2.carbon.apimgt.rest.api.admin.v1.dto.AlertsSubscriptionDTO) ArrayList(java.util.ArrayList) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) AlertManagementException(org.wso2.carbon.apimgt.impl.alertmgt.exception.AlertManagementException) AlertTypeDTO(org.wso2.carbon.apimgt.rest.api.admin.v1.dto.AlertTypeDTO) AdminAlertConfigurator(org.wso2.carbon.apimgt.impl.alertmgt.AdminAlertConfigurator)

Aggregations

MessageContext (org.apache.cxf.jaxrs.ext.MessageContext)31 List (java.util.List)11 Map (java.util.Map)11 ArrayList (java.util.ArrayList)7 MultivaluedMap (javax.ws.rs.core.MultivaluedMap)7 Response (javax.ws.rs.core.Response)7 MessageContextImpl (org.apache.cxf.jaxrs.ext.MessageContextImpl)7 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)7 RestApiUtil (org.wso2.carbon.apimgt.rest.api.util.utils.RestApiUtil)7 HashMap (java.util.HashMap)6 XMLStreamWriter (javax.xml.stream.XMLStreamWriter)5 StringUtils (org.apache.commons.lang3.StringUtils)5 Message (org.apache.cxf.message.Message)5 ExceptionCodes (org.wso2.carbon.apimgt.api.ExceptionCodes)5 RestApiConstants (org.wso2.carbon.apimgt.rest.api.common.RestApiConstants)5 InputStream (java.io.InputStream)4 XMLStreamException (javax.xml.stream.XMLStreamException)4 URI (java.net.URI)3 MediaType (javax.ws.rs.core.MediaType)3 Log (org.apache.commons.logging.Log)3