Example usage for org.springframework.security.oauth2.common.exceptions UnauthorizedUserException UnauthorizedUserException

List of usage examples for org.springframework.security.oauth2.common.exceptions UnauthorizedUserException UnauthorizedUserException

Introduction

In this page you can find the example usage for org.springframework.security.oauth2.common.exceptions UnauthorizedUserException UnauthorizedUserException.

Prototype

public UnauthorizedUserException(String msg) 

Source Link

Usage

From source file:org.openbaton.nfvo.core.api.ConfigurationManagement.java

@Override
public Configuration update(Configuration newConfiguration, String id, String projectId) {
    if (configurationRepository.findFirstById(id) != null
            && configurationRepository.findFirstById(id).getProjectId().equals(projectId))
        return configurationRepository.save(newConfiguration);
    throw new UnauthorizedUserException(
            "Configuration not under the project chosen, are you trying to hack us? Just kidding, it's a bug :)");
}

From source file:org.openbaton.nfvo.core.api.KeyManagement.java

@Override
public Key queryById(String projectId, String id) throws NotFoundException {
    Key key = keyRepository.findFirstById(id);
    if (key == null) {
        throw new NotFoundException("Not found key with id " + id);
    }//ww  w . ja v a2 s  .c  om
    if (!key.getProjectId().equals(projectId)) {
        throw new UnauthorizedUserException("Forbidden to query this project");
    }
    return key;
}

From source file:org.openbaton.nfvo.core.api.ConfigurationManagement.java

@Override
public Configuration query(String id, String projectId) {
    Configuration configuration = configurationRepository.findFirstById(id);
    if (configuration == null)
        return configuration;
    if (configuration.getProjectId().equals(projectId))
        return configuration;
    throw new UnauthorizedUserException(
            "Configuration not under the project chosen, are you trying to hack us? Just kidding, it's a bug :)");
}

From source file:org.openbaton.nfvo.core.api.KeyManagement.java

@Override
public void delete(String projectId, String id) throws NotFoundException {
    Key keyToDelete = keyRepository.findFirstById(id);
    if (keyToDelete == null) {
        throw new NotFoundException("Not found key with id " + id);
    }//  w ww  .j av a 2s .  co m
    if (!keyToDelete.getProjectId().equals(projectId)) {
        throw new UnauthorizedUserException("Forbidden to delete this project");
    }
    keyRepository.delete(id);
}

From source file:org.springframework.security.oauth2.common.exceptions.OAuth2ExceptionJackson2Deserializer.java

@Override
public OAuth2Exception deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {

    JsonToken t = jp.getCurrentToken();// w w w .  j a  v a2  s  . c o m
    if (t == JsonToken.START_OBJECT) {
        t = jp.nextToken();
    }
    Map<String, Object> errorParams = new HashMap<String, Object>();
    for (; t == JsonToken.FIELD_NAME; t = jp.nextToken()) {
        // Must point to field name
        String fieldName = jp.getCurrentName();
        // And then the value...
        t = jp.nextToken();
        // Note: must handle null explicitly here; value deserializers won't
        Object value;
        if (t == JsonToken.VALUE_NULL) {
            value = null;
        }
        // Some servers might send back complex content
        else if (t == JsonToken.START_ARRAY) {
            value = jp.readValueAs(List.class);
        } else if (t == JsonToken.START_OBJECT) {
            value = jp.readValueAs(Map.class);
        } else {
            value = jp.getText();
        }
        errorParams.put(fieldName, value);
    }

    Object errorCode = errorParams.get("error");
    String errorMessage = errorParams.containsKey("error_description")
            ? errorParams.get("error_description").toString()
            : null;
    if (errorMessage == null) {
        errorMessage = errorCode == null ? "OAuth Error" : errorCode.toString();
    }

    OAuth2Exception ex;
    if ("invalid_client".equals(errorCode)) {
        ex = new InvalidClientException(errorMessage);
    } else if ("unauthorized_client".equals(errorCode)) {
        ex = new UnauthorizedUserException(errorMessage);
    } else if ("invalid_grant".equals(errorCode)) {
        if (errorMessage.toLowerCase().contains("redirect") && errorMessage.toLowerCase().contains("match")) {
            ex = new RedirectMismatchException(errorMessage);
        } else {
            ex = new InvalidGrantException(errorMessage);
        }
    } else if ("invalid_scope".equals(errorCode)) {
        ex = new InvalidScopeException(errorMessage);
    } else if ("invalid_token".equals(errorCode)) {
        ex = new InvalidTokenException(errorMessage);
    } else if ("invalid_request".equals(errorCode)) {
        ex = new InvalidRequestException(errorMessage);
    } else if ("redirect_uri_mismatch".equals(errorCode)) {
        ex = new RedirectMismatchException(errorMessage);
    } else if ("unsupported_grant_type".equals(errorCode)) {
        ex = new UnsupportedGrantTypeException(errorMessage);
    } else if ("unsupported_response_type".equals(errorCode)) {
        ex = new UnsupportedResponseTypeException(errorMessage);
    } else if ("insufficient_scope".equals(errorCode)) {
        ex = new InsufficientScopeException(errorMessage,
                OAuth2Utils.parseParameterList((String) errorParams.get("scope")));
    } else if ("access_denied".equals(errorCode)) {
        ex = new UserDeniedAuthorizationException(errorMessage);
    } else {
        ex = new OAuth2Exception(errorMessage);
    }

    Set<Map.Entry<String, Object>> entries = errorParams.entrySet();
    for (Map.Entry<String, Object> entry : entries) {
        String key = entry.getKey();
        if (!"error".equals(key) && !"error_description".equals(key)) {
            Object value = entry.getValue();
            ex.addAdditionalInformation(key, value == null ? null : value.toString());
        }
    }

    return ex;

}

From source file:org.openbaton.nfvo.core.api.VimManagement.java

@Override
public void delete(String id, String projectId) {

    VimInstance vimInstance = vimRepository.findFirstById(id);
    if (!vimInstance.getProjectId().equals(projectId))
        throw new UnauthorizedUserException(
                "Vim not under the project chosen, are you trying to hack us? Just kidding, it's a bug :)");
    vimRepository.delete(vimInstance);//from   ww w. j a v a2s. c om
}

From source file:org.openbaton.nfvo.core.api.VimManagement.java

@Override
public VimInstance update(VimInstance vimInstance, String id, String projectId)
        throws VimException, PluginException, EntityUnreachableException, IOException {
    if (!vimInstance.getProjectId().equals(projectId))
        throw new UnauthorizedUserException(
                "Vim not under the project chosen, are you trying to hack us? Just kidding, it's a bug :)");
    vimInstance = vimRepository.save(vimInstance);
    refresh(vimInstance);//  w w  w. j a  va 2  s.  c  o  m
    return vimInstance;
}

From source file:org.openbaton.nfvo.core.api.VimManagement.java

@Override
public VimInstance query(String id, String projectId) {
    VimInstance vimInstance = vimRepository.findFirstById(id);
    if (vimInstance == null)
        return vimInstance;
    if (!vimInstance.getProjectId().equals(projectId))
        throw new UnauthorizedUserException("Sorry VimInstance not under the project used");
    return vimInstance;
}

From source file:io.curly.artifact.web.ArtifactResourceController.java

/**
 * @param pageable  current pagination/* w w w  .  j a  v  a  2s. co  m*/
 * @param user      current logged user
 * @param assembler hateoas assember
 * @return if found a page of resources if not 404 and if no user is found a 401
 */
@RequestMapping(value = "/owned", method = GET, produces = MediaTypes.HAL_JSON)
public DeferredResult<HttpEntity<PagedResources<ArtifactResource>>> artifactsOwned(
        @PageableDefault(20) Pageable pageable, @GitHubAuthentication User user,
        PagedResourcesAssembler<Artifact> assembler) {
    if (user == null) {
        throw new UnauthorizedUserException("No user found!");
    }
    return defer(artifactService.findAllOwned(pageable, user)
            .map(o -> o.<ResourceNotFoundException>orElseThrow(ResourceNotFoundException::new))
            .map(artifacts -> assembler.toResource(artifacts, this.assembler)).map(ResponseEntity::ok));
}

From source file:od.lti.LTIController.java

@RequestMapping(value = { "/lti" }, method = RequestMethod.POST)
public String lti(HttpServletRequest request, Model model)
        throws ProviderException, ProviderDataConfigurationException {
    LaunchRequest launchRequest = new LaunchRequest(request.getParameterMap());

    String consumerKey = launchRequest.getOauth_consumer_key();
    String contextId = launchRequest.getContext_id();

    Tenant tenant = mongoTenantRepository.findByConsumersOauthConsumerKey(consumerKey);

    ContextMapping contextMapping = contextMappingRepository.findByTenantIdAndContext(tenant.getId(),
            contextId);//  www. j av  a2  s. co m

    if (contextMapping == null) {
        contextMapping = new ContextMapping();
        contextMapping.setContext(contextId);
        contextMapping.setTenantId(tenant.getId());
        contextMapping.setModified(new Date());

        Set<Dashboard> dashboards = tenant.getDashboards();
        if (dashboards != null && !dashboards.isEmpty()) {
            Set<Dashboard> dashboardSet = new HashSet<>();
            for (Dashboard db : dashboards) {
                db.setId(UUID.randomUUID().toString());
                List<Card> cards = db.getCards();
                if (cards != null && !cards.isEmpty()) {
                    for (Card c : cards) {
                        c.setId(UUID.randomUUID().toString());
                    }
                }
                dashboardSet.add(db);
            }
            contextMapping.setDashboards(dashboardSet);
        } else {
            //TODO make better
            throw new RuntimeException("no dashboards");
        }

        contextMapping = contextMappingRepository.save(contextMapping);
    }

    String uuid = UUID.randomUUID().toString();
    //    model.addAttribute("token", uuid);

    // Create a token using spring provided class : LTIAuthenticationToken
    String role;
    if (LTIController.hasInstructorRole(null, launchRequest.getRoles())) {
        role = "ROLE_INSTRUCTOR";
    } else {
        throw new UnauthorizedUserException("Does not have the instructor role");
        //role = "ROLE_STUDENT";
    }

    LTIAuthenticationToken token = new LTIAuthenticationToken(launchRequest,
            launchRequest.getOauth_consumer_key(), launchRequest.toJSON(), uuid,
            AuthorityUtils.commaSeparatedStringToAuthorityList(role));

    // generate session if one doesn't exist
    request.getSession();

    // save details as WebAuthenticationDetails records the remote address and
    // will also set the session Id if a session already exists (it won't create
    // one).
    token.setDetails(new WebAuthenticationDetails(request));

    // authenticationManager injected as spring bean, : LTIAuthenticationProvider
    Authentication authentication = authenticationManager.authenticate(token);

    // Need to set this as thread locale as available throughout
    SecurityContextHolder.getContext().setAuthentication(authentication);

    // Set SPRING_SECURITY_CONTEXT attribute in session as Spring identifies
    // context through this attribute
    request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
            SecurityContextHolder.getContext());

    //return "index";
    String cmUrl = String.format("/cm/%s/dashboard/%s", contextMapping.getId(),
            (new ArrayList<>(contextMapping.getDashboards())).get(0).getId());
    return "redirect:" + cmUrl;
}