简体   繁体   中英

How to use Basic Authentication with Spring's Resource abstraction

I have a file on a server available via Https I want to access using Spring's Resource abstraction. I want Spring to resolve the resource and inject it into the constructor of my Bean like this:

public class MyClass {

    public MyClass(
            @Value("https://myserver.com/myfile") Resource resource) {
        // do something using the resource
    }
}

The issue is that I cannot figure out how to include the username and password for basic authentication into this pattern. I tried the "common" style

@Value("https://username:password@myserver.com/myfile")

but it looks like this is not understood correctly. The server is responding with HTTP status 401 - Unauthorized. I copied the string and perfomed the same query using wget and it worked. So there is no issue with my credentials but most likely with the syntax used to define the resource.

Is there a valid syntax for this in Spring or must I fetch the config in an alternative way setting the Authentication header by hand?

This feels wrong , and I'd prefer it if you didn't do it this way...but you can rely on @Value to inject the property value. Note the use of @Autowired here.

@Component
public class MyClass {
    private String resourceUrl;

    @Autowired
    public MyClass(@Value(${external.resource.url}) String resourceUrl) {
        this.resourceUrl = resourceUrl;
    }
    // The rest of your code
}

Then you could place into the property external.resource.url whichever value you liked...including your full URL with username and password.

I want to call attention that this is probably not a desirable thing to do, since you want to be able to inject the URL, username and password as separate things into your application. This gives you an idea of how you can accomplish it with one component, and while I strongly encourage you to split this up instead (and whatever you do, do not check the properties file in with those values into your source control), I leave the mechanical part of splitting this into more values as an exercise for the reader.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM