简体   繁体   English

如何在Spring的资源抽象中使用基本身份验证

[英]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. 我在服务器上有一个文件,可通过Https进行访问,我想使用Spring的Resource抽象访问该文件。 I want Spring to resolve the resource and inject it into the constructor of my Bean like this: 我希望Spring解析资源并将其注入到我的Bean的构造函数中,如下所示:

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. 服务器以HTTP状态401-未授权进行响应。 I copied the string and perfomed the same query using wget and it worked. 我复制了字符串,并使用wget执行了相同的查询,并且该查询有效。 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? 在Spring中是否有有效的语法,还是我必须以另一种方式手动设置Authentication标头来获取配置?

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. 感觉不对 ,如果您不是这样的话,我会更喜欢...但是您可以依靠@Value注入属性值。 Note the use of @Autowired here. 注意这里使用@Autowired

@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. 然后,您可以在属性external.resource.url放入您喜欢的任何值...包括带有用户名和密码的完整URL。

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. 我想提醒您,这可能不是一件好事,因为您希望能够将URL,用户名和密码作为单独的内容注入到您的应用程序中。 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. 这给你如何可以与一个组件完成它的想法,虽然我强烈建议您拆分这件事,而不是(不管你做什么, 检查属性文件中使用这些值到你的源代码控制),我离开将其分解为更多价值的机械部分,作为读者的练习。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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