2015-12-09 128 views
1

我有一个由spring安全保护的应用程序。 而我已添加BasicAuthInterceptor。但是当我向服务器请求一个休息api url时,我看到了html登录页面而不是json。 所以我想可能会传递用户名和密码在URL中请求的API。但我不知道如何。任何想法/建议非常感谢。干杯!我如何在api url中传递用户名和密码

THIS IS MY BasicAuthInterceptor

public class BasicAuthInterceptor implements ClientHttpRequestInterceptor { 

private static final Logger logger = LoggerFactory.getLogger(BasicAuthInterceptor.class); 

private final String username; 
private final String password; 

public BasicAuthInterceptor(String username, String password) { 
    this.username = username; 
    this.password = password; 
} 

@Override 
public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes, ClientHttpRequestExecution clientHttpRequestExecution) throws IOException { 

    // code here ... 
} 

与正在测试与客户端APP在main():

public static void main(String[] args) { 
    SpringApplication.run(App.class, args); 

    //Get a new Rest-Template 
    final RestTemplate template = new RestTemplate(); 

    //Create and initialize the interceptor 
    final List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>(); 
    interceptors.add(new BasicAuthInterceptor("admin", "admin")); 
    template.setInterceptors(interceptors); 

    //Do your request as normal 
    final String helloResponse = template.getForObject("http://localhost:9000/api/brands", String.class); 

    System.out.println(helloResponse); 
} 

回答

0

这取决于正在使用服务器侧的认证类型。

例如,对于基本身份验证您需要添加到请求头Authorization命名为特定的头与此内容

Basic [TOKEN]

其中[TOKEN]代表

Base64(username:password)

即用户名和密码由':'连接,并且全部用Base64编码。 (https://en.wikipedia.org/wiki/Basic_access_authentication#Client_side

所有这些都应该在方法intercept中完成(在您的代码中)。

您可以通过HttpRequest对象访问头(见文档@https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/http/HttpRequest.html

如果你正在使用的东西从基本的身份验证不同,那么就谷歌和搜索正确的标题添加。

+0

非常感谢:) –

+0

@RanzyBlessings很高兴它帮助:-)可否考虑接受答案,以防万一?谢谢。 –

相关问题