Search in sources :

Example 36 with GetMapping

use of org.springframework.web.bind.annotation.GetMapping in project cas by apereo.

the class ConfigurationStateController method getConfiguration.

/**
 * Gets configuration.
 *
 * @param request  the request
 * @param response the response
 * @return the configuration
 */
@GetMapping("/getConfiguration")
@ResponseBody
public Map getConfiguration(final HttpServletRequest request, final HttpServletResponse response) {
    final Map results = new TreeMap();
    ensureEndpointAccessIsAuthorized(request, response);
    if (environmentEndpoint == null || !environmentEndpoint.isEnabled()) {
        LOGGER.warn("Environment endpoint is either undefined or disabled");
        return results;
    }
    final Pattern pattern = RegexUtils.createPattern("(configService:|applicationConfig:).+(application|cas).+");
    final Map<String, Object> environmentSettings = environmentEndpoint.invoke();
    environmentSettings.entrySet().stream().filter(entry -> pattern.matcher(entry.getKey()).matches()).forEach(entry -> {
        final Map<String, Object> keys = (Map<String, Object>) entry.getValue();
        keys.keySet().forEach(key -> {
            if (!results.containsKey(key)) {
                final String propHolder = String.format("${%s}", key);
                final String value = this.environment.resolvePlaceholders(propHolder);
                results.put(key, environmentEndpoint.sanitize(key, value));
            }
        });
    });
    return results;
}
Also used : CasConfigurationProperties(org.apereo.cas.configuration.CasConfigurationProperties) BaseCasMvcEndpoint(org.apereo.cas.web.BaseCasMvcEndpoint) Autowired(org.springframework.beans.factory.annotation.Autowired) HashMap(java.util.HashMap) RequestBody(org.springframework.web.bind.annotation.RequestBody) HttpServletRequest(javax.servlet.http.HttpServletRequest) Pair(org.apache.commons.lang3.tuple.Pair) ConfigurableEnvironment(org.springframework.core.env.ConfigurableEnvironment) Map(java.util.Map) CasConfigurationPropertiesEnvironmentManager(org.apereo.cas.configuration.CasConfigurationPropertiesEnvironmentManager) Qualifier(org.springframework.beans.factory.annotation.Qualifier) ApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher) GetMapping(org.springframework.web.bind.annotation.GetMapping) PostMapping(org.springframework.web.bind.annotation.PostMapping) HttpServletResponse(javax.servlet.http.HttpServletResponse) EnvironmentEndpoint(org.springframework.boot.actuate.endpoint.EnvironmentEndpoint) ResponseBody(org.springframework.web.bind.annotation.ResponseBody) RegexUtils(org.apereo.cas.util.RegexUtils) ControllerUtils(org.apereo.cas.web.report.util.ControllerUtils) ModelAndView(org.springframework.web.servlet.ModelAndView) Slf4j(lombok.extern.slf4j.Slf4j) TreeMap(java.util.TreeMap) Pattern(java.util.regex.Pattern) CasConfigurationModifiedEvent(org.apereo.cas.support.events.config.CasConfigurationModifiedEvent) RefreshEndpoint(org.springframework.cloud.endpoint.RefreshEndpoint) Pattern(java.util.regex.Pattern) TreeMap(java.util.TreeMap) HashMap(java.util.HashMap) Map(java.util.Map) TreeMap(java.util.TreeMap) GetMapping(org.springframework.web.bind.annotation.GetMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 37 with GetMapping

use of org.springframework.web.bind.annotation.GetMapping in project cas by apereo.

the class IdPInitiatedProfileHandlerController method handleIdPInitiatedSsoRequest.

/**
 * Handle idp initiated sso requests.
 *
 * @param response the response
 * @param request  the request
 * @throws Exception the exception
 */
@GetMapping(path = SamlIdPConstants.ENDPOINT_SAML2_IDP_INIT_PROFILE_SSO)
protected void handleIdPInitiatedSsoRequest(final HttpServletResponse response, final HttpServletRequest request) throws Exception {
    // The name (i.e., the entity ID) of the service provider.
    final String providerId = CommonUtils.safeGetParameter(request, SamlIdPConstants.PROVIDER_ID);
    if (StringUtils.isBlank(providerId)) {
        LOGGER.warn("No providerId parameter given in unsolicited SSO authentication request.");
        throw new MessageDecodingException("No providerId parameter given in unsolicited SSO authentication request.");
    }
    final SamlRegisteredService registeredService = verifySamlRegisteredService(providerId);
    final Optional<SamlRegisteredServiceServiceProviderMetadataFacade> adaptor = getSamlMetadataFacadeFor(registeredService, providerId);
    if (!adaptor.isPresent()) {
        throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE, "Cannot find metadata linked to " + providerId);
    }
    // The URL of the response location at the SP (called the "Assertion Consumer Service")
    // but can be omitted in favor of the IdP picking the default endpoint location from metadata.
    String shire = CommonUtils.safeGetParameter(request, SamlIdPConstants.SHIRE);
    final SamlRegisteredServiceServiceProviderMetadataFacade facade = adaptor.get();
    if (StringUtils.isBlank(shire)) {
        LOGGER.warn("Resolving service provider assertion consumer service URL for [{}] and binding [{}]", providerId, SAMLConstants.SAML2_POST_BINDING_URI);
        @NonNull final AssertionConsumerService acs = facade.getAssertionConsumerService(SAMLConstants.SAML2_POST_BINDING_URI);
        shire = acs.getLocation();
    }
    if (StringUtils.isBlank(shire)) {
        LOGGER.warn("Unable to resolve service provider assertion consumer service URL for AuthnRequest construction for entityID: [{}]", providerId);
        throw new MessageDecodingException("Unable to resolve SP ACS URL for AuthnRequest construction");
    }
    // The target resource at the SP, or a state token generated by an SP to represent the resource.
    final String target = CommonUtils.safeGetParameter(request, SamlIdPConstants.TARGET);
    // A timestamp to help with stale request detection.
    final String time = CommonUtils.safeGetParameter(request, SamlIdPConstants.TIME);
    final SAMLObjectBuilder builder = (SAMLObjectBuilder) configBean.getBuilderFactory().getBuilder(AuthnRequest.DEFAULT_ELEMENT_NAME);
    final AuthnRequest authnRequest = (AuthnRequest) builder.buildObject();
    authnRequest.setAssertionConsumerServiceURL(shire);
    final SAMLObjectBuilder isBuilder = (SAMLObjectBuilder) configBean.getBuilderFactory().getBuilder(Issuer.DEFAULT_ELEMENT_NAME);
    final Issuer issuer = (Issuer) isBuilder.buildObject();
    issuer.setValue(providerId);
    authnRequest.setIssuer(issuer);
    authnRequest.setProtocolBinding(SAMLConstants.SAML2_POST_BINDING_URI);
    final SAMLObjectBuilder pBuilder = (SAMLObjectBuilder) configBean.getBuilderFactory().getBuilder(NameIDPolicy.DEFAULT_ELEMENT_NAME);
    final NameIDPolicy nameIDPolicy = (NameIDPolicy) pBuilder.buildObject();
    nameIDPolicy.setAllowCreate(Boolean.TRUE);
    authnRequest.setNameIDPolicy(nameIDPolicy);
    if (NumberUtils.isCreatable(time)) {
        authnRequest.setIssueInstant(new DateTime(TimeUnit.SECONDS.convert(Long.parseLong(time), TimeUnit.MILLISECONDS), ISOChronology.getInstanceUTC()));
    } else {
        authnRequest.setIssueInstant(new DateTime(DateTime.now(), ISOChronology.getInstanceUTC()));
    }
    authnRequest.setForceAuthn(Boolean.FALSE);
    if (StringUtils.isNotBlank(target)) {
        request.setAttribute(SamlProtocolConstants.PARAMETER_SAML_RELAY_STATE, target);
    }
    final MessageContext ctx = new MessageContext();
    ctx.setAutoCreateSubcontexts(true);
    if (facade.isAuthnRequestsSigned()) {
        samlObjectSigner.encode(authnRequest, registeredService, facade, response, request, SAMLConstants.SAML2_POST_BINDING_URI);
    }
    ctx.setMessage(authnRequest);
    ctx.getSubcontext(SAMLBindingContext.class, true).setHasBindingSignature(false);
    final Pair<SignableSAMLObject, MessageContext> pair = Pair.of(authnRequest, ctx);
    initiateAuthenticationRequest(pair, response, request);
}
Also used : SAMLBindingContext(org.opensaml.saml.common.messaging.context.SAMLBindingContext) SAMLObjectBuilder(org.opensaml.saml.common.SAMLObjectBuilder) Issuer(org.opensaml.saml.saml2.core.Issuer) NameIDPolicy(org.opensaml.saml.saml2.core.NameIDPolicy) SamlRegisteredServiceServiceProviderMetadataFacade(org.apereo.cas.support.saml.services.idp.metadata.SamlRegisteredServiceServiceProviderMetadataFacade) UnauthorizedServiceException(org.apereo.cas.services.UnauthorizedServiceException) DateTime(org.joda.time.DateTime) MessageDecodingException(org.opensaml.messaging.decoder.MessageDecodingException) AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) SignableSAMLObject(org.opensaml.saml.common.SignableSAMLObject) SamlRegisteredService(org.apereo.cas.support.saml.services.SamlRegisteredService) NonNull(lombok.NonNull) AssertionConsumerService(org.opensaml.saml.saml2.metadata.AssertionConsumerService) MessageContext(org.opensaml.messaging.context.MessageContext) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Example 38 with GetMapping

use of org.springframework.web.bind.annotation.GetMapping in project cas by apereo.

the class OidcRevocationEndpointController method handleRequestInternal.

/**
 * Handle request for revocation.
 *
 * @param request  the request
 * @param response the response
 * @return the jwk set
 */
@GetMapping(value = '/' + OidcConstants.BASE_OIDC_URL + '/' + OidcConstants.REVOCATION_URL)
public ResponseEntity<String> handleRequestInternal(final HttpServletRequest request, final HttpServletResponse response) {
    try {
        final CredentialsExtractor<UsernamePasswordCredentials> authExtractor = new BasicAuthExtractor();
        final UsernamePasswordCredentials credentials = authExtractor.extract(Pac4jUtils.getPac4jJ2EContext(request, response));
        if (credentials == null) {
            throw new IllegalArgumentException("No credentials are provided to verify introspection on the access token");
        }
        final OAuthRegisteredService service = OAuth20Utils.getRegisteredOAuthServiceByClientId(this.servicesManager, credentials.getUsername());
        if (this.validator.checkServiceValid(service) && this.validator.checkParameterExist(request, OAuth20Constants.ACCESS_TOKEN) && this.validator.checkClientSecret(service, credentials.getPassword())) {
            final String token = request.getParameter(OidcConstants.TOKEN);
            if (StringUtils.isNotBlank(token)) {
                this.ticketRegistry.deleteTicket(token);
            }
        }
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
    }
    return new ResponseEntity<>(HttpStatus.OK);
}
Also used : BasicAuthExtractor(org.pac4j.core.credentials.extractor.BasicAuthExtractor) ResponseEntity(org.springframework.http.ResponseEntity) OAuthRegisteredService(org.apereo.cas.support.oauth.services.OAuthRegisteredService) UsernamePasswordCredentials(org.pac4j.core.credentials.UsernamePasswordCredentials) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Example 39 with GetMapping

use of org.springframework.web.bind.annotation.GetMapping in project mzzb-server by mingzuozhibi.

the class DiscController method getOne.

@Transactional
@GetMapping(value = "/api/discs/{id}", produces = MEDIA_TYPE)
public String getOne(@PathVariable Long id) {
    Disc disc = dao.get(Disc.class, id);
    if (disc == null) {
        if (LOGGER.isWarnEnabled()) {
            warnRequest("[获取碟片失败][指定的碟片Id不存在][Id={}]", id);
        }
        return errorMessage("指定的碟片Id不存在");
    }
    JSONObject result = disc.toJSON();
    if (LOGGER.isDebugEnabled()) {
        debugRequest("[获取碟片成功][碟片信息={}]", result);
    }
    result.put("ranks", buildRanks(dao, disc));
    return objectResult(result);
}
Also used : JSONObject(org.json.JSONObject) Disc(mingzuozhibi.persist.disc.Disc) GetMapping(org.springframework.web.bind.annotation.GetMapping) Transactional(org.springframework.transaction.annotation.Transactional)

Example 40 with GetMapping

use of org.springframework.web.bind.annotation.GetMapping in project mzzb-server by mingzuozhibi.

the class DiscController method search.

@Transactional
@PreAuthorize("hasRole('BASIC')")
@GetMapping(value = "/api/discs/search/{asin}", produces = MEDIA_TYPE)
public String search(@PathVariable String asin) {
    AtomicReference<Disc> disc = new AtomicReference<>(dao.lookup(Disc.class, "asin", asin));
    StringBuffer error = new StringBuffer();
    if (disc.get() == null) {
        searchFromAmazon(asin, disc, error);
        waitForSearch(disc);
    }
    if (disc.get() == null) {
        if (error.length() > 0) {
            return errorMessage(error.toString());
        }
        if (LOGGER.isInfoEnabled()) {
            infoRequest("[查找碟片][从Amazon查询超时][asin={}]]", asin);
        }
        return errorMessage("查询超时,你可以稍后再尝试");
    }
    JSONArray result = new JSONArray();
    JSONObject discJSON = disc.get().toJSON();
    if (LOGGER.isInfoEnabled()) {
        infoRequest("[查找碟片成功][碟片信息={}]", discJSON);
    }
    result.put(discJSON);
    return objectResult(result);
}
Also used : JSONObject(org.json.JSONObject) Disc(mingzuozhibi.persist.disc.Disc) JSONArray(org.json.JSONArray) AtomicReference(java.util.concurrent.atomic.AtomicReference) GetMapping(org.springframework.web.bind.annotation.GetMapping) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) Transactional(org.springframework.transaction.annotation.Transactional)

Aggregations

GetMapping (org.springframework.web.bind.annotation.GetMapping)737 ResponseBody (org.springframework.web.bind.annotation.ResponseBody)114 ResponseEntity (org.springframework.http.ResponseEntity)78 ArrayList (java.util.ArrayList)52 ModelAndView (org.springframework.web.servlet.ModelAndView)48 List (java.util.List)46 WebMessageException (org.hisp.dhis.dxf2.webmessage.WebMessageException)45 HttpHeaders (org.springframework.http.HttpHeaders)40 HashMap (java.util.HashMap)38 lombok.val (lombok.val)38 Map (java.util.Map)37 ResponseStatus (org.springframework.web.bind.annotation.ResponseStatus)36 Grid (org.hisp.dhis.common.Grid)35 IOException (java.io.IOException)32 ApiOperation (io.swagger.annotations.ApiOperation)31 RootNode (org.hisp.dhis.node.types.RootNode)31 RequestParam (org.springframework.web.bind.annotation.RequestParam)31 PathVariable (org.springframework.web.bind.annotation.PathVariable)30 HttpServletRequest (javax.servlet.http.HttpServletRequest)29 FieldFilterParams (org.hisp.dhis.fieldfilter.FieldFilterParams)28