Java 如何在api url中传递用户名和密码
我有一个由spring security保护的应用程序。 我还添加了Java 如何在api url中传递用户名和密码,java,spring,rest,security,url,Java,Spring,Rest,Security,Url,我有一个由spring security保护的应用程序。 我还添加了基本的CAUTHInterceptor。但当我向服务器请求RESTAPI url时,我看到的是html登录页面,而不是json。 所以我想也许在url中为请求的api传递用户名和密码。但我不知道如何传递。非常感谢您的任何想法/建议。干杯 这是我的基本计算机接口课程 public class BasicAuthInterceptor implements ClientHttpRequestInterceptor { privat
基本的CAUTHInterceptor
。但当我向服务器请求RESTAPI url时,我看到的是html登录页面,而不是json。
所以我想也许在url中为请求的api传递用户名和密码。但我不知道如何传递。非常感谢您的任何想法/建议。干杯
这是我的基本计算机接口
课程
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()中的客户端应用程序进行测试:
publicstaticvoidmain(字符串[]args){
SpringApplication.run(App.class,args);
//获取新的Rest模板
最终RestTemplate模板=新RestTemplate();
//创建并初始化拦截器
最终列表拦截器=新的ArrayList();
添加(新的基本侦听器(“admin”、“admin”));
模板.设置拦截器(拦截器);
//你的要求正常吗
最后一个字符串hellorResponse=template.getForObject(“http://localhost:9000/api/brands“,String.class);
System.out.println(helloreresponse);
}
这取决于您使用的服务器端身份验证类型
例如,对于基本身份验证,您需要在请求头中添加一个名为Authorization
的特定头,其中包含此内容
Basic[TOKEN]
其中,[TOKEN]
代表
Base64(用户名:密码)
即,用户名和密码由一个“:”连接起来,全部用Base64编码。
()
所有这些都应该在方法intercept
中完成(在代码中)
您可以通过HttpRequest
对象访问标题(请参阅文档@)
如果您使用的是与基本身份验证不同的内容,那么只需谷歌搜索要添加的正确标题。这取决于您使用的服务器端身份验证类型 例如,对于基本身份验证,您需要在请求头中添加一个名为
Authorization
的特定头,其中包含此内容
Basic[TOKEN]
其中,[TOKEN]
代表
Base64(用户名:密码)
即,用户名和密码由一个“:”连接起来,全部用Base64编码。
()
所有这些都应该在方法intercept
中完成(在代码中)
您可以通过HttpRequest
对象访问标题(请参阅文档@)
如果您使用的是与基本身份验证不同的东西,那么只需谷歌并搜索正确的页眉来添加。
@ RANZYBLYES很高兴它有帮助:-你可以考虑接受答案吗?谢谢。“谢谢你的帮助。”——你可以考虑接受这个答案吗?谢谢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);
}