Categories
discuss

HTTP status code 405 error when adding headers to request

I have a problem making get requests to a server when headers are being set with the Axios/http request. Any header I add (except the content-type header) causes the same error: “Response for preflight has invalid HTTP status code 405.” This is true in Chrome, Firefox, Edge, etc.

Specifically, I need to add the Authorization header for account validation for a service I need to connect with.

Running a GET request on Postman using the API URI works fine and I get the required response. Running this in my React application in the browser gives me the HTTP 405 error. I’m running this on a local Node server with Google’s Allow-Control-Origin extension installed and enabled using http://localhost:3000.

When I run the request without any header parameters:

axios.get("https://myrequest.com/req/reqservice.svc/Login",).then(data => console.log(data)).catch(err => console.log(err))

The request works fine. When I run it with headers (any header, but in my case, the Authorization header), I get the error:

axios.get("https://myrequest.com/req/reqservice.svc/Login", { headers: { "Authorization": "randomExample" } }).then(data => console.log(data)).catch(err => console.log(err))

So, what could be causing the issue? If it was a CORS or connection issue, wouldn’t I have trouble making a request in general? I’ve been perusing Stack Overflow forever with no answer giving me the solution. I’m totally lost at what to do and I’ve been working on it for days already without a single solution. Any input would be much appreciated.

Answer

It is due to CORS. You need to specify the correct value for Access-Control-Allow-Headers server side for the preflight (OPTIONS) request (Documentation)

More details about CORS in general

Modify your server to add the missing header(s). From your question, you need to at least add Authorization value.

node js server

app.use(function (req, res, next) {
//...
res.setHeader('Access-Control-Allow-Headers', 'Authorization');

About Access-Control-Allow-Headers

The Access-Control-Allow-Headers response header is used in response to a preflight request to indicate which HTTP headers can be used during the actual request.

So, in your server side response, when setting Access-Control-Allow-Headers, you need to specify a list of comma-separated headers.

Access-Control-Allow-Headers: <header-name>, <header-name>, ...

You only need to specify it for custom headers, as by default some headers are already accepted.

The simple headers, Accept, Accept-Language, Content-Language, Content-Type (but only with a MIME type of its parsed value (ignoring parameters) of either application/x-www-form-urlencoded, multipart/form-data, or text/plain), are always available and don’t need to be listed by this header.

So in your case it works if you just specify Content-type because Content-Type is accepted by default (as explained just above)

Note If the value for Content-type is not of one of the types above (e.g. if you submit your authorization request as application/json), then you need to add it in the list (comma-separated)

node js server

app.use(function (req, res, next) {
//...
res.setHeader('Access-Control-Allow-Headers', 'Authorization, Content-Type');
Categories
discuss

Unable to disable EditText programmatically in kotlin android

I am trying to disable an EditText programmatically in Kotlin but I am not finding any method to do. I tried below code which didnt work:

panEditText.focusable = false //Requires API 26 and above.

panEditText.enabled = false //No such method found

How to disable EditText in Kotlin programming language?

Answer

You should use isEnabled.

Set the enabled state of this view.

 panEditText.isEnabled =false

Method Overview

@android.view.RemotableViewMethod
    @Override
    public void setEnabled(boolean enabled) {
        if (enabled == isEnabled()) {
            return;
        }

        if (!enabled) {
            // Hide the soft input if the currently active TextView is disabled
            InputMethodManager imm = InputMethodManager.peekInstance();
            if (imm != null && imm.isActive(this)) {
                imm.hideSoftInputFromWindow(getWindowToken(), 0);
            }
        }

        super.setEnabled(enabled);

        if (enabled) {
            // Make sure IME is updated with current editor info.
            InputMethodManager imm = InputMethodManager.peekInstance();
            if (imm != null) imm.restartInput(this);
        }

        // Will change text color
        if (mEditor != null) {
            mEditor.invalidateTextDisplayList();
            mEditor.prepareCursorControllers();

            // start or stop the cursor blinking as appropriate
            mEditor.makeBlink();
        }
    }
Categories
discuss

spring-boot-maven-plugin doesn’t create fat jar

I’m using spring-boot-maven-plugin to package my REST service. I’m building the jar using mvn clean install or mvn clean package. After I decompile the jar, I don’t find any of the dependencies added (I was expecting it to be a fat jar with all dependencies)

enter image description here

 <plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <version>1.5.9.RELEASE</version>
    <executions>
        <execution>
           <phase>install</phase>
           <goals>
              <goal>repackage</goal>
              <goal>build-info</goal>
           </goals>
        </execution>
    </executions>
    <configuration>
        <executable>true</executable>
        <finalName>myapp</finalName>
        <includeSystemScope>true</includeSystemScope>
    </configuration>
</plugin>

When I run the spring boot using java -jar myapp.jar -Drun.jvmArguments="-Dspring.profiles.active=qal" I’m getting ClassNotFoundException for many of the classes. It’s clear that artifact didn’t build as expected. However, if I start spring boot application using maven ./mvnw spring-boot:run -Drun.jvmArguments="-Dspring.profiles.active=qal" I guess, it finds all the dependencies in target folder hence works fine. How can I fix the build issue so that I can start app using java -jar command.

EDIT: It’s multi-module maven project

Answer

it seems you are using a wrong command. mvn clean package is maven command, you should use command ‘repackage’, it used for

Repackages existing JAR and WAR archives so that they can be executed from the command line using java -jar

as it mentioned here https://docs.spring.io/spring-boot/docs/current/maven-plugin/repackage-mojo.html

Or probably it’s plugin configuration issue. Just checked: it works with spring-boot-maven-plugin-2.0.0.RELEASE

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <executions>
        <execution>
            <goals>
                <goal>repackage</goal>
            </goals>
            <configuration>
                 <classifier>exec</classifier>
            </configuration>
         </execution>
    </executions>
</plugin>
Categories
discuss

Catch block not working in node fetch

Trying to learn, Javascript. Pardon if this is really a basic thin i am missing.

I am trying to run node-fetch to a wrong url, and i expect that it should be catched and log my appropriate message. However when i run this file through node, it gives me uncatched error

    const fetch = require('node-fetch');

    fetch('http://api.icnd.com/jokes/random/10')
        .then(response => {
            response.json().then((data) => {
                console.log(data)
            });
        }).
        catch(error => {
            console.log('There is some error');
        });



(node:864) UnhandledPromiseRejectionWarning: FetchError: invalid json response body at http://api.icnd.com/jokes/random/10 reason: Unexpected token < in JSON at position 0
    at /Users/raheel/code/js-tutorial/node_modules/node-fetch/lib/index.js:254:32
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:118:7)
(node:864) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:864) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Answer

Its this part that is uncatched:

 response.json()

Therefore attach a catch handler to it:

 response.json().catch(...)

or simply return it so that it is catched by the other handler:

 return response.json()
Categories
discuss

How to detect a zip-bomb with Java 10

Apache POI is opening zip-files on a regular basis because Microsoft Excel/Word/… files are zip-files in their newer format. In order to prevent some types of denial-of-service-attacks, it has functionality when opening Zip-files to not read files which expand a lot and thus could be used to overwhelm the main memory by providing a small malicious file which explodes when uncompressed into memory. Apache POI calls this zip-bomb-protection.

Up to Java 9 it could use some workaround via reflection to inject a counting-InputStream into ZipFile/ZipEntry to detect an explosion in expanded data and this way prevent zip-bombs.

However in Java 10 this is not possible any more because the implementation of ZipFile was changed in a way that prevents this (hard cast to ZipFile$ZipFileInputStream in ZipFile).

So we are looking for a different way to count the number of extracted bytes during extracting to be able to stop as soon as the compression ratio reaches a certain limit.

Is there a way to do zip-bomb-detection differently without resorting to reflection?

Answer

After some investigation we used zip-functionality from Apache commons-compress, which allows to perform this kind of check without having to resort to reflection, so we now can do these checks with any version of Java.

Look at https://github.com/apache/poi/tree/trunk/src/ooxml/java/org/apache/poi/openxml4j/util for the resulting implementation in Apache POI, especially ZipArchiveThresholdInputStream.

Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..