我有一个由spring security保护的应用程序。我添加了BasicAuthInterceptor。但是当我向服务器请求rest api url时,我看到的是html登录页面,而不是json。所以我想也许可以在url中为请求的api.But传递用户名和密码,我不知道怎么做。任何想法/建议都是非常感谢的。干杯!
这是我的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 ...
}在MAIN()中使用客户端应用程序进行AM测试:
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);
}发布于 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并搜索要添加的正确标题即可。
https://stackoverflow.com/questions/34173263
复制相似问题