I am using SignalR
java client in android and .net core3
as my webservice. I configured a set-cookie header in my responses from webservice to prevent DDOS attacks
, but now I can't connect to my Hub because there is no option in SignalR
java client to Handle set-cookie header . How can I fix this problem?
Well after alot of search I came to this :
hubConnection = HubConnectionBuilder.create(HUB_URL).withHandshakeResponseTimeout(60000).withHeaders(mapHeader).setHttpClientBuilderCallback(param1 -> {
param1.addInterceptor(new ApiClient.ReceivedCookiesInterceptor(G.context));
param1.addInterceptor(new ApiClient.AddCookiesInterceptor(G.context));
}).withTransport(TransportEnum.ALL).withAccessTokenProvider(Single.defer(() -> Single.just("An Access Token"))).build();
(setHttpClientBuilderCallback) will give me a configuration builder which I can use to handle setcookie
from response .
this is my ReceivedCookiesInterceptor
:
public static class ReceivedCookiesInterceptor implements Interceptor {
private Context context;
public ReceivedCookiesInterceptor(Context context) {
this.context = context;
}
@Override
public Response intercept(Chain chain) throws IOException {
Response originalResponse = chain.proceed(chain.request());
if (!originalResponse.headers("Set-Cookie").isEmpty()) {
Log.i("HubLogin", "intercept: "+originalResponse.headers("Set-Cookie"));
HashSet<String> cookies = (HashSet<String>) PreferenceManager.getDefaultSharedPreferences(context).getStringSet("PREF_COOKIES", new HashSet<String>());
for (String header : originalResponse.headers("Set-Cookie")) {
cookies.add(header);
}
SharedPreferences.Editor memes = PreferenceManager.getDefaultSharedPreferences(context).edit();
memes.putStringSet("PREF_COOKIES", cookies).apply();
memes.apply();
}
return originalResponse;
}
}
and this is my AddCookiesInterceptor
:
public static class AddCookiesInterceptor implements Interceptor {
public static final String PREF_COOKIES = "PREF_COOKIES";
private Context context;
public AddCookiesInterceptor(Context context ) {
this.context = context;
}
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request.Builder builder = chain.request().newBuilder();
HashSet<String> preferences = (HashSet<String>) PreferenceManager.getDefaultSharedPreferences(context).getStringSet(PREF_COOKIES, new HashSet<>());
for (String cookie : preferences) {
builder.addHeader("Cookie", cookie);
}
return chain.proceed(builder.build());
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.