Spring boot CORS withCredentials - java

I am getting Credential is not supported if the CORS header 'Access-Control-Allow-Origin' is '*' error. Below is the response of preflight request
As you can see the value of access-control-allow-origin is set to *. It should be value of origin header in the request. Because of this * I am getting above error.
If I invoke preflight from CURL, I get the correct response,
Below is my CORS filter,
#Bean
public CorsFilter corsFilter() {
List<String> allowedMethods = Arrays.asList("GET", "PUT", "DELETE", "PATCH", "POST", "HEAD", "OPTIONS");
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOriginPatterns(corsUrls);
config.setAllowedMethods(allowedMethods);
config.setAllowCredentials(true);
config.addAllowedHeader(ALL);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
But for actual request it sets value of access-control-allow-origin to value of origin header in the request.

Related

Spring Boot Webclient with NTLM Authentication

I am using Spring WebClient to hit a Rest Service which requires NTLM Authentication. It works in Postman like below:
Hit the URL - http://example.com:83/api/auth/token with authentication as NTLM authentication and provide the user name and password. When hitting this service, it returns a token.
This token has to be passed in header as bearer token for the actual post service -
http://example.com:89/api/v1/employee
But when I tried the same using Spring WebClient, I am facing 401 - Unauthorized error. Below the code snippet I am using.
BasicCredentialsProvider tokenProvider = new BasicCredentialsProvider();
tokenProvider.setCredentials(
new AuthScope("http", "example.com", 83, "/api/auth/token", StandardAuthScheme.NTLM),
new NTCredentials("testuser", "pwd".toCharArray(), null, null)
);
webClient = WebClient.builder()
.clientConnector(new HttpComponentsClientHttpConnector
(HttpAsyncClients
.custom()
.setDefaultCredentialsProvider(tokenProvider)
.setTargetAuthenticationStrategy(DefaultAuthenticationStrategy.INSTANCE)
.setDefaultRequestConfig(
RequestConfig.custom()
.setAuthenticationEnabled(true)
.setTargetPreferredAuthSchemes(Collections.singletonList(StandardAuthScheme.NTLM))
.setExpectContinueEnabled(true)
.build())
.build()))
.build();
ParameterizedTypeReference<LinkedHashMap<String, Object>> result =
new ParameterizedTypeReference<LinkedHashMap<String, Object>>() {};
Map<String, Object> body = new HashMap<>();
body.put("test-key", "value");
webClient.post().uri("http://example.com:89/api/v1/employee").contentType(MediaType.APPLICATION_JSON).accept(MediaType.ALL).bodyValue(body).retrieve().bodyToMono(result).block();
Is this right approach?

form-data request, with okHttp3

I'm trying to make a request where I pass some parameters in the Body, as shown in the image.
Example Image
Example:
Key: file[], Value: "xml", Content-Type: application/xml Key: query, Value: {"boxe/File": false}, Content-Type: application/xml
I'm getting a Bad Request error, I think my code isn't right. Follow how it is being done
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file[]", xml, RequestBody.create(null, "application/xml"))
.addFormDataPart("query", "{\"boxe/File\": false}", RequestBody.create(null, "application/xml"))
.build();
Request request = new Request.Builder().url(endPoint).addHeader("x-integration-key", integrationKey)
.addHeader("Authorization", "Bearer " + token)
.post(requestBody).build();
Managed to solve it, the order of the parameters were wrong,
follow the correct order
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file[]","", RequestBody.create(MediaType.parse("application/xml"), xml))
.addFormDataPart("query", "", RequestBody.create(MediaType.parse("application/json"), boxFileJson))
.build();

how to get session cookie from server and set it into the api header?

There is cookie header in my api request, every time I have to copy this cookie from postman and paste in my code to make it work. how can I generate cookie in my app and give that value in cookie header?
this is my login code:
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("username","zee#earthonetechno.com")
.addFormDataPart("password","E1234567")
.build();
Request request = new Request.Builder()
.url("192.168.1.51/auth/login")
.method("POST", body)
.addHeader("User-Agent", "Koala Admin")
.addHeader("Content-Type", "application/json")
.addHeader("Cookie", "session=3e3710cb-9b41-47ea-ab1b-a1e1801e188b")
.build();
Response response = client.newCall(request).execute();
I want to put the cookie here in addHeader("Cookie", "session=3e3710cb-9b41-47ea-ab1b-a1e1801e188b")
I am developing in android studio
I found the solution for this
just include these lines in login part to get cookie
Headers allHeaders = response.headers();
headerValue = allHeaders.get("Set-Cookie");
and use this headerValue for subsequent api calls

Authorization header not recognized by Yelp Fusion API

I am passing an authorization header with my Retrofit GET requests as documented by the Yelp Fusion documentation, which is shown below:
Authorization: Bearer MY_API_KEY
I am adding a network interceptor in my onCreate() method as shown below:
OkHttpClient.Builder okHttpBuilder = new OkHttpClient.Builder();
okHttpBuilder.addInterceptor(new Interceptor() {
#Override
public okhttp3.Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
// Request customization: add request headers
Request.Builder requestBuilder = original.newBuilder()
.addHeader("Authorization", "Bearer MY_API_KEY");
Request request = requestBuilder.build();
return chain.proceed(request);
}
});
//Yelp Client init
yelpRetrofit = new Retrofit.Builder()
.baseUrl("https://httpbin.org/")
.client(okHttpBuilder.build())
.addConverterFactory(GsonConverterFactory.create())
.build();
yelpClient = yelpRetrofit.create(YelpClient.class);
Here is my YelpClient class :
public interface YelpClient {
#GET("headers")
Call<YelpJSON> searchTest(); }
This is the response I get when sending the request:
{"error": {"code": "TOKEN_MISSING", "description": "An access token must be supplied in order to use this endpoint."}}
I have successfully retrieved a response from the Yelp Fusion API with Postman and curl both using identical parameters and headers as my Retrofit request, so I can't blame Yelp. I have also attempted statically and dynamically setting the header with no success. Can anyone help me figure out what is wrong here?

Spring - changing Content-type HTTP header

I am communicating with a JSON API using Robospice. This is how I set the headers for a POST request:
mHttpHeaders = new HttpHeaders();
mHttpHeaders.add("Content-Type", "application/json");
Log.d(Global.TAG, mHttpHeaders.toString());
The problem is that I get a header which looks like that: {Content-Type=[application/json]} where I need to send Content-Type:application/json (which seems to be the only header that my server accepts). I can't find any way to change it (tried with both add() and setContentType() methods), how do I do that?
You should try followings and it works for me. I'm using Spring rest template inside Robospice.
MediaType mediaType = new MediaType("application", "json");
List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
acceptableMediaTypes.add(mediaType);
HttpHeaders headers = new HttpHeaders();
headers.setAccept(acceptableMediaTypes);
The output
{Content-Type=[application/json]}
you see in the Log statement is just the String returned by the toString() method, it's not the actual header sent. For example
public static void main(String[] args) throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/json");
System.out.println(headers);
}
prints
{Content-Type=[application/json]}
If you are using the HttpClient and HttpRequestBase (HttpGet, HttpPost, etc.) correctly, the header will be sent just fine.

Categories