首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在api url中传递用户名和密码?

如何在api url中传递用户名和密码?
EN

Stack Overflow用户
提问于 2015-12-09 15:42:15
回答 1查看 4.6K关注 0票数 1

我有一个由spring security保护的应用程序。我添加了BasicAuthInterceptor。但是当我向服务器请求rest api url时,我看到的是html登录页面,而不是json。所以我想也许可以在url中为请求的api.But传递用户名和密码,我不知道怎么做。任何想法/建议都是非常感谢的。干杯!

这是我的BasicAuthInterceptor

代码语言:javascript
复制
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 ...
}

在MAIN()中使用客户端应用程序进行AM测试:

代码语言:javascript
复制
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);
}
EN

回答 1

Stack Overflow用户

发布于 2015-12-11 19:34:10

这取决于您使用的服务器端的身份验证类型。

例如,对于基本身份验证,您需要向请求标头添加一个名为Authorization的特定标头,其中包含以下内容

Basic [TOKEN]

其中[TOKEN]代表

Base64(username:password)

也就是说,用户名和密码由':‘连接,并且都是用Base64编码的。(https://en.wikipedia.org/wiki/Basic_access_authentication#Client_side)

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

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

如果您使用的是与基本身份验证不同的内容,那么只需Google并搜索要添加的正确标题即可。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34173263

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档