@Override protected int beforeHandle(Request request, Response response) { if (Method.OPTIONS.equals(request.getMethod())) { Series<Header> requestHeaders = (Series<Header>) request.getAttributes().get(HeaderConstants.ATTRIBUTE_HEADERS); String origin = requestHeaders.getFirstValue("Origin", false, "*"); String rh = requestHeaders.getFirstValue("Access-Control-Request-Headers", false, "*"); Series<Header> responseHeaders = (Series<Header>) response.getAttributes().get(HeaderConstants.ATTRIBUTE_HEADERS); if (responseHeaders == null) { responseHeaders = new Series<Header>(Header.class); } responseHeaders.add("Access-Control-Allow-Origin", origin); responseHeaders.set("Access-Control-Expose-Headers", "Authorization, Link"); responseHeaders.add("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS"); responseHeaders.add("Access-Control-Allow-Headers", rh); responseHeaders.add("Access-Control-Allow-Credentials", "true"); responseHeaders.add("Access-Control-Max-Age", "60"); response.getAttributes().put(HeaderConstants.ATTRIBUTE_HEADERS, responseHeaders); response.setEntity(new EmptyRepresentation()); return SKIP; } return super.beforeHandle(request, response); }
// TODO The secret should be a char[]. private Representation doNoneFlow( String clientId, String clientSecret, Series<Parameter> params) { Client client = validate(clientId, clientSecret); // null check on failed if (client == null) { setStatus(Status.CLIENT_ERROR_FORBIDDEN); return sendError(OAuthError.invalid_client, "Client id verification failed.", null); } if (!client.containsUser(AUTONOMOUS_USER)) { client.createUser(AUTONOMOUS_USER); } AuthenticatedUser user = client.findUser(AUTONOMOUS_USER); // Adding all scopes since super-user // String[] scopes = parseScope(params.getFirstValue(SCOPE)); List<Role> roles = Scopes.toRoles(params.getFirstValue(SCOPE)); for (Role r : roles) { getLogger().fine("Requested scopes none flow = " + roles); user.addRole(r, ""); getLogger().fine("Adding scope = " + r.getName() + " to auto user"); } Token token = this.generator.generateToken(user, this.tokenTimeSec); JSONObject body = createJsonToken(token, null); // Scopes N/A // Sets the no-store Cache-Control header getResponse().setCacheDirectives(noStore); return new JsonStringRepresentation(body); }
@Override public synchronized void start() throws Exception { // restlet servlet engine will pass parameters from web.xml via the context parameters Series<Parameter> parameters = getContext().getParameters(); dataSource = PSCPDataSource.createDataSource(parameters); daoFactory = PGDaoFactory.createPGDaoFactory(dataSource); lookupCache = new LookupCache(daoFactory); secretResolver = new SecretResolver(); adminPage = parameters.getFirstValue("pscp.web.admin"); urls = new URLS(adminPage); // links out to website urls.putStatic( new Template(getSlashedURL(parameters, "pscp.web.products")), URLS.Name.PRODUCT_LOCATION); urls.putStatic( new Template(getSlashedURL(parameters, "pscp.web.root")), URLS.Name.STATIC_MEDIA); // @todo how to deal with this? baseURIs = new ArrayList<String>(Arrays.asList("localhost:8080")); Map<String, Object> contextAttributes = getContext().getAttributes(); contextAttributes.put(BaseResource.CONTEXT_ATTRIBUTE_DAO_FACTORY, daoFactory); contextAttributes.put(BaseResource.CONTEXT_ATTRIBUTE_URL_MAPPER, urls); contextAttributes.put(BaseResource.CONTEXT_ATTRIBUTE_LOOKUP_CACHE, lookupCache); contextAttributes.put( BaseResource.CONTEXT_ATTRIBUTE_PRODUCT_ROOT, getRootDir(BaseResource.CONTEXT_ATTRIBUTE_PRODUCT_ROOT, "pscp-products")); contextAttributes.put( BaseResource.CONTEXT_ATTRIBUTE_UPLOAD_ROOT, getRootDir(BaseResource.CONTEXT_ATTRIBUTE_UPLOAD_ROOT, "pscp-uploads")); super.start(); }
private String getSlashedURL(Series<Parameter> params, String key) { String url = params.getFirstValue(key); if (url.indexOf('?') < 0 && !url.endsWith("/")) { url = url + "/"; } return url; }
// TODO The secret should be a char[]. private Representation doAuthCodeFlow( String clientId, String clientSecret, Series<Parameter> params) throws IllegalArgumentException { String redirUri = params.getFirstValue(REDIR_URI); if ((redirUri == null) || (redirUri.length() == 0)) { setStatus(Status.CLIENT_ERROR_BAD_REQUEST); return sendError( OAuthError.invalid_request, "Mandatory parameter redirect_uri is missing", null); } String code = params.getFirstValue(CODE); if ((code == null) || (code.length() == 0)) { setStatus(Status.CLIENT_ERROR_BAD_REQUEST); return sendError(OAuthError.invalid_request, "Mandatory parameter code is missing", null); } Client client = validate(clientId, clientSecret); // null check on failed if (client == null) { setStatus(Status.CLIENT_ERROR_FORBIDDEN); return sendError(OAuthError.invalid_request, "Client id verification failed.", null); } // check the client secret if (!clientSecret.equals(client.getClientSecret())) { setStatus(Status.CLIENT_ERROR_UNAUTHORIZED); return sendError(OAuthError.invalid_request, "Client secret did not match", null); } // TODO could add a cookie match on the owner but could fail if code is // sent to other entity // unauthorized_client, right now this is only performed if // ScopedResource getOwner returns the user // 5 min timeout on tokens, 0 for unlimited Token token = generator.exchangeForToken(code, tokenTimeSec); // TODO send back scopes if limited JSONObject body = createJsonToken(token, null); // Sets the no-store Cache-Control header getResponse().setCacheDirectives(noStore); return new JsonStringRepresentation(body); }
@Override public void formatResponse( ChallengeWriter cw, ChallengeResponse challenge, Request request, Series<Header> httpHeaders) { // Setup the Date header String date = ""; if (httpHeaders.getFirstValue("x-ms-date", true) == null) { // X-ms-Date header didn't override the standard Date header date = httpHeaders.getFirstValue(HeaderConstants.HEADER_DATE, true); if (date == null) { // Add a fresh Date header date = DateUtils.format(new Date(), DateUtils.FORMAT_RFC_1123.get(0)); httpHeaders.add(HeaderConstants.HEADER_DATE, date); } } else { date = httpHeaders.getFirstValue("x-ms-date", true); } // Setup the canonicalized path String canonicalizedResource = getCanonicalizedResourceName(request.getResourceRef()); // Setup the message part StringBuilder rest = new StringBuilder(); rest.append(date) .append('\n') .append('/') .append(challenge.getIdentifier()) .append(canonicalizedResource); // Append the SharedKey credentials cw.append(challenge.getIdentifier()) .append(':') .append( Base64.encode( DigestUtils.toHMacSha256(rest.toString(), Base64.decode(challenge.getSecret())), true)); }
// TODO The secret should be a char[]. private Representation doPasswordFlow( String clientId, String clientSecret, Series<Parameter> params) { Client client = validate(clientId, clientSecret); // null check on failed if (client == null) { setStatus(Status.CLIENT_ERROR_FORBIDDEN); return sendError(OAuthError.invalid_client, "Client id verification failed.", null); } String username = params.getFirstValue(USERNAME); AuthenticatedUser user = null; if ((username == null) || ((user = client.findUser(username)) == null)) { setStatus(Status.CLIENT_ERROR_BAD_REQUEST); return sendError(OAuthError.invalid_request, "Mandatory parameter username missing.", null); } String password = params.getFirstValue(PASSWORD); if (password == null) { setStatus(Status.CLIENT_ERROR_BAD_REQUEST); return sendError(OAuthError.invalid_request, "Mandatory parameter password missing.", null); } if (!password.equals(user.getPassword())) { setStatus(Status.CLIENT_ERROR_FORBIDDEN); return sendError(OAuthError.invalid_grant, "Password not correct.", null); } Token token = this.generator.generateToken(user, this.tokenTimeSec); JSONObject body = createJsonToken(token, null); // Scopes N/A // Sets the no-store Cache-Control header getResponse().setCacheDirectives(noStore); return new JsonStringRepresentation(body); }
@Post public Representation acceptItem(Representation entity) { logger.info("Attempting to delete a device"); Series<Cookie> cookies = this.getRequest().getCookies(); String parent_username = cookies.getFirstValue(COOKIE_USER); String auth_Token = cookies.getFirstValue(COOKIE_AUTH); if ((parent_username == null) || (auth_Token == null)) return null; User thisUser = new User(parent_username); // Is this a valid cookie? if (!thisUser.validateCookie(auth_Token)) return null; // Cookie is valid Form form = new Form(entity); String device_id = form.getFirstValue("deviceID"); Device thisDevice = new Device(device_id); thisDevice.deleteDevice(); return null; }
/** * Creates a content type. * * @param mediaType The media type name. * @param parameters The parameters parsed. * @return The content type. */ private ContentType createContentType(StringBuilder mediaType, Series<Parameter> parameters) { // Attempt to extract the character set CharacterSet characterSet = null; if (parameters != null) { String charSet = parameters.getFirstValue("charset"); if (charSet != null) { parameters.removeAll("charset"); characterSet = new CharacterSet(charSet); } return new ContentType(new MediaType(mediaType.toString(), parameters), characterSet); } return new ContentType(new MediaType(mediaType.toString()), null); }
// TODO The secret should be a char[]. private Representation doRefreshFlow( String clientId, String clientSecret, Series<Parameter> params) { String rToken = params.getFirstValue(REFRESH_TOKEN); if ((rToken == null) || (rToken.length() == 0)) { setStatus(Status.CLIENT_ERROR_BAD_REQUEST); return sendError( OAuthError.invalid_request, "Mandatory parameter refresh_token is missing", null); } Client client = validate(clientId, clientSecret); // null check on failed if (client == null) { setStatus(Status.CLIENT_ERROR_FORBIDDEN); return sendError(OAuthError.invalid_client, "Client id verification failed.", null); } Token token = generator.findToken(rToken); if ((token != null) && (token instanceof ExpireToken)) { AuthenticatedUser user = token.getUser(); // Make sure that the user owning the token is owned by this client if (client.containsUser(user.getId())) { // refresh the token generator.refreshToken((ExpireToken) token); JSONObject body = createJsonToken(token, null); // Scopes N/A // Sets the no-store Cache-Control header getResponse().setCacheDirectives(noStore); return new JsonStringRepresentation(body); } else { // error not owner setStatus(Status.CLIENT_ERROR_FORBIDDEN); return sendError(OAuthError.unauthorized_client, "User does not match.", null); } } else { // error no such token. setStatus(Status.CLIENT_ERROR_UNAUTHORIZED); return sendError(OAuthError.invalid_grant, "Refresh token.", null); } }
@Override protected int doHandle(final Request request, final Response response) { int result = super.doHandle(request, response); Map<String, Object> requestAttributes = request.getAttributes(); Map<String, Object> responseAttributes = response.getAttributes(); Series<Header> requestHeaders = (Series<Header>) requestAttributes.computeIfAbsent( "org.restlet.http.headers", key -> new Series<Header>(Header.class)); Series<Header> responseHeaders = (Series<Header>) responseAttributes.computeIfAbsent( "org.restlet.http.headers", key -> new Series<Header>(Header.class)); // TODO fix me responseHeaders.add("Access-Control-Allow-Origin", requestHeaders.getFirstValue("Origin")); responseHeaders.add("Access-Control-Allow-Credentials", "true"); responseHeaders.add( "Access-Control-Allow-Methods", "HEAD, GET, PUT, POST, DELETE, OPTIONS, TRACE"); responseHeaders.add("Access-Control-Allow-Headers", "Content-Type, X-Requested-With"); return result; }