I want to use cookies in Robospice, I have spice service:
public class JsonSpiceService extends SpringAndroidSpiceService {
public RestTemplate createRestTemplate() {
RestTemplate restTemplate = new RestTemplate();
MappingJacksonHttpMessageConverter jsonConverter = new MappingJacksonHttpMessageConverter();
FormHttpMessageConverter formHttpMessageConverter = new FormHttpMessageConverter();
StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter();
final List<HttpMessageConverter<?>> listHttpMessageConverters = restTemplate.getMessageConverters();
HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
restTemplate.setRequestFactory( httpRequestFactory );
listHttpMessageConverters.add(jsonConverter);
listHttpMessageConverters.add(formHttpMessageConverter);
listHttpMessageConverters.add(stringHttpMessageConverter);
restTemplate.setMessageConverters(listHttpMessageConverters);
return restTemplate;
}
public CacheManager createCacheManager(Application application) throws CacheCreationException {
CacheManager cacheManager = new CacheManager();
List< Class< ? >> classCollection = new ArrayList< Class< ? >>();
classCollection.add(User.class);
JacksonObjectPersisterFactory jacksonObjectPersisterFactory = new JacksonObjectPersisterFactory(application);
cacheManager.addPersister(jacksonObjectPersisterFactory);
return cacheManager;
}
}
and my Request class:
public class Request extends SpringAndroidSpiceRequest<HttpModel> {
private Context context;
private HttpMethod httpMethod;
private MultiValueMap<String, String> body;
private String link;
private String what;
private Object object;
public Request(Context context, HttpMethod httpMethod, MultiValueMap<String, String> body, String link, String what, Object object) {
super(HttpModel.class);
this.context = context;
this.httpMethod = httpMethod;
this.body = body;
this.link = link;
this.what = what;
this.object = object;
}
#Override
public HttpModel loadDataFromNetwork() throws Exception {
HttpModel httpModel;
HttpHeaders headers = new HttpHeaders();
HttpEntity<?> requestEntity;
if (!what.equals(LOGIN)) {
headers.setContentType(MediaType.APPLICATION_JSON);
} else {
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
}
requestEntity = new HttpEntity<Object>(body, headers);
ResponseEntity<HttpModel> responseEntity = getRestTemplate().exchange(link, httpMethod, requestEntity, HttpModel.class);
httpModel = responseEntity.getBody();
return httpModel;
}
}
How can i get cookie from response?I try add CookieManager to my Request class, but dont'work:
final CookieManager cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(cookieManager);
In postman Cookie look like this:
enter link description here
CookieManager is used only for managing cookies in your application's WebViews.
You can use responseEntity.getHeaders().get(COOKIE). You can also try SET_COOKIE or SET_COOKIE2 keys instead of COOKIE, depending on your server's response.
Related
I am trying to implement on a Blazor-Server side application a simple login against LDAP server and use cookie to store user claims. I have the MainLayout set to Authorized, if the user is not authenticated it will be re-direct to Login page. I have already tested the LDAP connection and it works properly, the problem is no matter what I do the cookie doesn't get created in the browser. When I run the POST command I see the HttpStatusCode.OK but the cookie it's not created and the browser re-direct again to login page of course.
Can someone please tell me what am I doing wrong? My code:
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddControllersWithViews().AddRazorRuntimeCompilation();
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
}
AuthenticationController.cs
[ApiController]
public class AuthenticationController : Controller
{
[HttpPost]
[Route("authentication/login")]
public async Task<ActionResult> Login([FromBody]UserCredentials credentials)
{
string path = "LDAP://serveraddress.xxx";
try
{
using DirectoryEntry entry = new(path, credentials.Username, credentials.Password);
using DirectorySearcher searcher = new(entry);
searcher.Filter = $"(&(objectclass=user)(objectcategory=person)(samaccountname={credentials.Username}))";
var result = searcher.FindOne();
if (result != null)
{
List<Claim> claims = new();
claims.Add(new Claim(ClaimTypes.Name, credentials.Username));
//Get Groups
ResultPropertyCollection fields = result.Properties;
foreach (var group in result.Properties["memberof"])
{
var distinguishedName = new X500DistinguishedName(group.ToString());
var commonNameData = new AsnEncodedData("CN", distinguishedName.RawData);
var commonName = commonNameData.Format(false);
if (!string.IsNullOrEmpty(commonName))
{
claims.Add(new Claim(ClaimTypes.Role, commonName));
}
}
//Get Emails
foreach (var email in result.Properties["mail"])
{
claims.Add(new Claim(ClaimTypes.Email, email.ToString()));
}
ClaimsIdentity claimsIdentity = new(claims, CookieAuthenticationDefaults.AuthenticationScheme);
AuthenticationProperties authProperties = new()
{
AllowRefresh = true,
IssuedUtc = DateTime.Now,
ExpiresUtc = DateTimeOffset.Now.AddDays(1),
IsPersistent = true,
};
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties);
return Ok();
}
else
{
return NotFound("User Not Found!");
}
}
catch (Exception)
{
return NotFound("Login credentials is incorrect!");
}
}
[HttpPost]
[Route("authentication/logout")]
public async Task<IActionResult> Logout()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return Ok();
}
}
Login.razor
#page "/login"
#page "/login/{ErrorMessage}"
#layout CenteredBlockLayout
#attribute [AllowAnonymous]
<MudPaper Elevation="25" Class="pa-8" Width="100%" MaxWidth="500px">
<MudItem><img src="/images/logo.svg" alt="Logo" style="width:400px; height:50px;" /></MudItem>
<MudText Typo="Typo.h4" GutterBottom="true">Sign In</MudText>
<MudTextField #bind-Value="#Username" T="string" Label="Username"/>
<MudTextField #bind-Value="#Password" T="string" Label="Password"/>
<MudButton OnClick="(() => PerformLoginAsync())">Sign In</MudButton>
</MudPaper>
#if (!string.IsNullOrEmpty(ErrorMessage))
{
<MudAlert Severity="Severity.Error">#ErrorMessage</MudAlert>
}
Login.razor.cs
public partial class Login
{
public string Username { get; set; }
public string Password { get; set; }
[Parameter]
public string ErrorMessage { get; set; }
[Inject]
HttpClient Client { get; set; }
[Inject]
private NavigationManager NavMan { get; set; }
private async Task PerformLoginAsync()
{
if (!string.IsNullOrEmpty(Username) && !string.IsNullOrEmpty(Password))
{
UserCredentials cred = new UserCredentials
{
Username = Username,
Password = Password
};
var serialized = JsonConvert.SerializeObject(cred);
var stringContent = new StringContent(serialized, Encoding.UTF8, "application/json");
using var result = await Client.PostAsync($"NavMan.BaseUri}authentication/login", stringContent);
if (result.StatusCode == System.Net.HttpStatusCode.OK)
{
NavMan.NavigateTo("/", true);
}
else
{
ErrorMessage = await result.Content.ReadAsStringAsync();
}
}
}
}
I believe you need to append the cookie to the response. I haven't tested this with your code but it should work something like this:
HttpContext.Response.Cookies.Append("my_cookie", claimsString, new CookieOptions()
{
Domain = "mydomain.com",
SameSite = SameSiteMode.Lax,
Secure = true,
Path = "/",
Expires = DateTime.UtcNow.AddDays(1)
}
(These cookie options are just an example, of course. Tailor them to your specific needs.)
Keep in mind that you'll need to convert your claims to a string so that you can store it as the value in a cookie. In our case we store claims in a JWT, so that's what gets stored in the cookie. Here's how I do it:
public string CreateJWT(HttpContext httpContext, User user)
{
var handler = new JwtSecurityTokenHandler();
var descriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[] {
new Claim(ClaimTypes.GivenName, user.FirstName),
new Claim(ClaimTypes.Surname, user.LastName),
new Claim(ClaimTypes.Name, $"{user.FirstName} {user.LastName}"),
new Claim(ClaimTypes.Email, user.Email),
}),
Expires = DateTime.UtcNow.AddMinutes(Config.AccessExpMins),
Issuer = Config.Issuer,
Audience = Config.Audience,
SigningCredentials = new SigningCredentials(Key, SecurityAlgorithms.RsaSha256)
};
var token = handler.CreateJwtSecurityToken(descriptor);
var accessToken = handler.WriteToken(token);
httpContext.Response.Cookies.Append("my_cookie", accessToken, new CookieOptions()
{
Domain = Config.CookieDomain,
SameSite = SameSiteMode.Lax,
Secure = true,
Path = "/",
Expires = DateTime.UtcNow.AddMinutes(Config.AccessExpMins)
});
return accessToken;
}
As for parsing the JWT, I'm sure there are a number of ways to go about it. The one that worked for me was this one.
This question already has answers here:
How to call a method in another class of the same package?
(8 answers)
Closed 4 years ago.
I am new and beginner in Java world. I have this code
public class Test2 {
public static void main(String[] args) throws IOException {
try {
String url = "http://www.metalbulletin.com/Login.html?ReturnURL=%2fdefault.aspx&";
String articleURL = "https://www.metalbulletin.com/Article/3838710/Home/CHINA-REBAR-Domestic-prices-recover-after-trading-pick-up.html";
Connection.Response loginForm = Jsoup.connect(url)
.method(Connection.Method.GET)
.execute();
Document welcomePage = loginForm.parse();
Element formElement = welcomePage.body().getElementsByTag("form").get(0);
String formAction = formElement.attr("action");
Elements input = welcomePage.select("input[name=idsrv.xsrf]");
String securityTokenValue =input.attr("value");
Connection.Response mainPage = Jsoup.connect("https://account.metalbulletin.com"+formAction)
.data("idsrv.xsrf", securityTokenValue)
.data("username", "ifiih#rupayamail.com")
.data("password", "Kh457544")
.cookies(loginForm.cookies())
.method(Connection.Method.POST)
.execute();
Map<String, String> cookies = mainPage.cookies();
System.out.println("\n\nloginForm.cookies()==>\n"+loginForm.cookies());
System.out.println("\n\nmainPage.cookies()==>\n"+mainPage.cookies());
Document articlePage = Jsoup.connect(articleURL).cookies(cookies).get();
Element article = articlePage.getElementById("article-body");
Elements lead1 = article.getElementsByClass("articleContainer");
System.out.println("\n\nNews Article==>\n"+lead1);
} catch (IOException e) {
e.printStackTrace();
}
}
}
How can I refactor to this:
private Map<String, String> cookies = new HashMap<String, String>();
private Document get(String url) throws IOException {
Connection connection = Jsoup.connect(url);
for (Map.Entry<String, String> cookie : cookies.entrySet()) {
connection.cookie(cookie.getKey(), cookie.getValue());
}
Response response = connection.execute();
cookies.putAll(response.cookies());
return response.parse();
}
I am not sure as to how I can call this private Document get(String url) method. It may seems to be stupid question but very important for me.
How can I call it within same class?
to do that, the easiest and more efficient solution to retrieve the Document and also the Map of Cookies, would be to create a new class called TestThreadHandler as it follows:
public class TestThreadHandler implements Runnable {
private String url;
private Document doc;
private Map<String, String> cookies;
private Semaphore barrier;
public TestThreadHandler (String url, Document doc, Map<String, String> cookies, Semaphore barrier) {
this.url = url;
this.doc = doc;
this.cookies = cookies;
this.barrier = barrier;
}
public void run () {
try {
Connection connection = Jsoup.connect(this.url);
for (Map.Entry<String, String> cookie : this.cookies.entrySet()) {
connection.cookie(cookie.getKey(), cookie.getValue());
}
Response response = connection.execute();
this.cookies.putAll(response.cookies());
this.doc = response.parse();
} catch (IOException e) {
e.printStackTrace();
}
this.barrier.release();
}
}
And call that Thread from your Test2 class from wherever you want to call it, but a sample call to that Thread would be:
public class Test2 {
public static void main(String[] args) throws IOException {
try {
...
String url = "https://www.google.com";
Document doc;
Map<String, String> cookies = new HashMap<String, String>();
Semaphore barrier = new Semaphore(0);
Thread taskThread = new Thread( new TestThreadHandler(url, doc, cookies, barrier) );
taskThread.start();
barrier.acquireUninterruptibly(1); // Wait until Thread ends
// NOW YOU HAVE BOTH DOC AND COOKIES FILLED AS DESCRIBED IN TestThreadHandler
...
} catch (IOException e) {
e.printStackTrace();
}
}
}
Doing that you can overwrite the variables you are passing as argument to the Thread and get both the Cookies and the JSOUP Document.
For further explanation check the Java doc of ThreadHandling or feel free to ask me!
Hope this helped you! +1
I have an app that allows users to log in via facebook, once user enters their credentials - My api request saves the user onto the database and auto-generates a user token(This is unique to each user). In order to display user specific details once user logs in - the token needs to be referenced. I am trying to get this token to the PCL project but it returns null just for the token. When I tried passing another string like name, it passes the correct value. Any help will be much appreciated.Thanks
FacebookRender in droid:
public class FacebookRender : PageRenderer
{
public FacebookRender()
{
CustomerService customerService = new CustomerService();
String error;
var activity = this.Context as Activity;
var auth = new OAuth2Authenticator(
clientId: "",
scope: "",
authorizeUrl: new Uri("https://www.facebook.com/dialog/oauth/"),
redirectUrl: new Uri("https://www.facebook.com/connect/login_success.html")
);
auth.Completed += async (sender, eventArgs) =>
{
try
{
if (eventArgs.IsAuthenticated)
{
await AccountStore.Create().SaveAsync(eventArgs.Account, "FacebookProviderKey");
var accessToken = eventArgs.Account.Properties["access_token"].ToString();
var expiresIn = Convert.ToDouble(eventArgs.Account.Properties["expires_in"]);
var expiryDate = DateTime.Now + TimeSpan.FromSeconds(expiresIn);
var request = new OAuth2Request("GET", new Uri("https://graph.facebook.com/me?fields=email,first_name,last_name,gender,picture"), null, eventArgs.Account);
var response = await request.GetResponseAsync();
var obj = JObject.Parse(response.GetResponseText());
var id = obj["id"].ToString().Replace("\"", "");
var name = obj["first_name"].ToString().Replace("\"", "");
var surname = obj["last_name"].ToString().Replace("\"", "");
var gender = obj["gender"].ToString().Replace("\"", "");
//var email = obj["email"].ToString().Replace("\"", "");
Customer.Customers cust = new Customer.Customers();
cust.Credentials = new Customer.Credentials();
cust.Name = name;
cust.Surname = surname;
cust.Email = "";
cust.MobilePhone = "";
cust.DOB = DateTime.Now;
cust.Number = "";
cust.City = "";
cust.Region = "";
cust.Country = "";
cust.DeviceToken = "sample";
cust.Credentials.SecretKey = "";
await customerService.AddCustomer(cust);
App.SaveToken(cust.Credentials.Token); - **//This is where I am passing the token**
App.NavigateToProfile(string.Format(name + surname));
}
else
{
App.NavigateToProfile("Invalid Login");
}
}
catch(Exception ex)
{
error = ex.Message;
}
};
activity.StartActivity(auth.GetUI(activity));
}
App.cs
public App()
{
InitializeComponent();
MainPage = new NavigationPage(new MainPage());
}
public static void NavigateToProfile(string message)
{
App.Current.MainPage = (new Profile(message));
}
static string _Token;
public static string Token
{
get { return _Token; }
}
public static void SaveToken(string token)
{
_Token = token;
}
AboutPage.cs - I am passing the token in a label just to see if it's passing
public partial class About : ContentPage
{
private Label _lbltoken;
public About()
{
//InitializeComponent();
Appearing += (object s, EventArgs a) => {
_lbltoken.Text = App.Token;
};
string tk = App.Token;
_lbltoken = new Label()
{
FontSize = 20,
HorizontalOptions = LayoutOptions.CenterAndExpand,
Text = tk,
};
var stack = new StackLayout
{
VerticalOptions = LayoutOptions.StartAndExpand,
Children = { _lbltoken },
};
Content = stack;
}
}
You can use the MessagingCenter.
Messages may be sent as a result like a button click, a system event or some other incident. Subscribers might be listening in order to change the appearance of the user interface, save data or trigger some other operation.
More Info
I don't really now if its good idea use static fields in App class. Xamarin access all fields with service locator, App.Current.[property] I will suggest you try to change these fields to public
string _Token;
public string Token
{
get { return _Token; }
}
public void SaveToken(string token)
{
_Token = token;
}
and use it with App.Current.SaveToken(token) or App.Current.Token
I am having trouble fetching result from my amazon elastic search cluster using the amazon java SDK and an IAm user credential. Now the issue is that when the PATH string is equal to "/" then I am able to fetch the result correctly but when I try with a different path for e.g "/private-search" then I get a 403 forbidden error. Even when for the path that has public access I am getting a 403 forbidden error for this IAm user but it works if I remove "signer.sign(requestToSign, credentials);" line in performSigningSteps method(for public resource only).
My policy in AWS gives this IAM user access to everything in my elastic search service. And also what can I do to avoid hard-coding the access key and secret key in source code?
private static final String SERVICE_NAME = "es";
private static final String REGION = "region-name";
private static final String HOST = "host-name";
private static final String ENDPOINT_ROOT = "http://" + HOST;
private static final String PATH = "/private-search";
private static final String ENDPOINT = ENDPOINT_ROOT + PATH;
private static String accessKey = "IAmUserAccesskey"
private static String secretKey = "IAmUserSecretkey"
public static void main(String[] args) {
// Generate the request
Request<?> request = generateRequest();
// Perform Signature Version 4 signing
performSigningSteps(request);
// Send the request to the server
sendRequest(request);
}
private static Request<?> generateRequest() {
Request<?> request = new DefaultRequest<Void>(SERVICE_NAME);
request.setContent(new ByteArrayInputStream("".getBytes()));
request.setEndpoint(URI.create(ENDPOINT));
request.setHttpMethod(HttpMethodName.GET);
return request;
}
private static void performSigningSteps(Request<?> requestToSign) {
AWS4Signer signer = new AWS4Signer();
signer.setServiceName(requestToSign.getServiceName());
signer.setRegionName(REGION);
AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
signer.sign(requestToSign, credentials);
}
private static void sendRequest(Request<?> request) {
ExecutionContext context = new ExecutionContext();
ClientConfiguration clientConfiguration = new ClientConfiguration();
AmazonHttpClient client = new AmazonHttpClient(clientConfiguration);
MyHttpResponseHandler<Void> responseHandler = new MyHttpResponseHandler<Void>();
MyErrorHandler errorHandler = new MyErrorHandler();
Void response = client.execute(request, responseHandler, errorHandler, context);
}
public static class MyHttpResponseHandler<T> implements HttpResponseHandler<AmazonWebServiceResponse<T>> {
#Override
public AmazonWebServiceResponse<T> handle(com.amazonaws.http.HttpResponse response) throws Exception {
InputStream responseStream = response.getContent();
String responseString = convertStreamToString(responseStream);
System.out.println(responseString);
AmazonWebServiceResponse<T> awsResponse = new AmazonWebServiceResponse<T>();
return awsResponse;
}
#Override
public boolean needsConnectionLeftOpen() {
return false;
}
}
public static class MyErrorHandler implements HttpResponseHandler<AmazonServiceException> {
#Override
public AmazonServiceException handle(com.amazonaws.http.HttpResponse response) throws Exception {
System.out.println("In exception handler!");
AmazonServiceException ase = new AmazonServiceException("exception.");
ase.setStatusCode(response.getStatusCode());
ase.setErrorCode(response.getStatusText());
return ase;
}
#Override
public boolean needsConnectionLeftOpen() {
return false;
}
}
public static String convertStreamToString(InputStream is) throws IOException {
// To convert the InputStream to String we use the
// Reader.read(char[] buffer) method. We iterate until the
// Reader return -1 which means there's no more data to
// read. We use the StringWriter class to produce the string.
if (is != null) {
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
}
finally {
is.close();
}
return writer.toString();
}
return "";
}
I have build a client, that should fetch data from a remote, wsdl-based webservice (using SOAP).
But everytime I try to connect (with a call of a function) with the service I get the following exception:
org.springframework.ws.soap.client.SoapFaultClientException: Username and/or Password cannot be null
at org.springframework.ws.soap.client.core.SoapFaultMessageResolver.resolveFault(SoapFaultMessageResolver.java:38) ~[spring-ws-core-2.2.0.RELEASE.jar:2.2.0.RELEASE]
at org.springframework.ws.client.core.WebServiceTemplate.handleFault(WebServiceTemplate.java:826) ~[spring-ws-core-2.2.0.RELEASE.jar:2.2.0.RELEASE]
at org.springframework.ws.client.core.WebServiceTemplate.doSendAndReceive(WebServiceTemplate.java:621) ~[spring-ws-core-2.2.0.RELEASE.jar:2.2.0.RELEASE]
at org.springframework.ws.client.core.WebServiceTemplate.sendAndReceive(WebServiceTemplate.java:555) ~[spring-ws-core-2.2.0.RELEASE.jar:2.2.0.RELEASE]
at org.springframework.ws.client.core.WebServiceTemplate.marshalSendAndReceive(WebServiceTemplate.java:390) ~[spring-ws-core-2.2.0.RELEASE.jar:2.2.0.RELEASE]
at com.test.adminUI.myPartners.client.MyPartnersServiceClient.sendSoapRequest(MyPartnersServiceClient.java:113) [bin/:na]
at com.test.adminUI.myPartners.client.MyPartnersServiceClient.findUser(PartnersServiceClient.java:70) [bin/:na]...
If I put a wrong password for example, the service registered it, an throws a Unauthorized 401 ERROR
So that mean, it actually validates my useraccount details.
my client:
public class MyServiceClient extends WebServiceGatewaySupport {
#Autowired
private ObjectFactory factory;
#Autowired
private SoapProperties adProperties;
private static final String WS_ADDRESSING_URI = "http://www.w3.org/2005/08/addressing";
private static final String TO_TAG = "To";
private static final String ACTION_TAG = "Action";
private static final String WSA_PREFIX = "wsa";
private static final String SOAP_ACTION_FIND_IFXPERSON = adProperties.getsoapURL();
public List<Person> findUser(String email, String globalID) {
List<Person> list = null;
FindPerson findperson = new FindPerson();
try {
findperson.setGlobalID(factory.createGlobalID(globalID));
findperson.setServiceUsername(factory.createServiceUsername(adProperties.getServiceUser()));
findperson.setServicePassword(factory.createServicePassword(adProperties.getServicePassword()));
FindPersonResponse response = (FindPersonResponse) sendSoapRequest(
SOAP_ACTION_FIND_PERSON, findperson);
list = response.getFindPersonResult().getValue();
} catch (Exception ex) {
log.error("could not find Person: ", ex);
}
return null;
}
private Object sendSoapRequest(final String soapAction, Object payLoad) {
Object response = null;
try {
Credentials auth = new NTCredentials(adProperties.getAuthUser(),
adProperties.getAuthPassword(), null, adProperties.getAuthDomain());
HttpClientBuilder clientBuilder = HttpClientBuilder.create();
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY, auth);
clientBuilder.setDefaultCredentialsProvider(credsProvider);
RemoveSoapHeadersInterceptor interceptor = new RemoveSoapHeadersInterceptor();
clientBuilder.addInterceptorFirst(interceptor);
HttpClient httpClient = clientBuilder.build();
HttpComponentsMessageSender messageSender = new HttpComponentsMessageSender();
messageSender.setHttpClient(httpClient);
messageSender.setCredentials(auth);
messageSender.afterPropertiesSet();
getWebServiceTemplate().setMessageSender(messageSender);
SaajSoapMessageFactory messageFactory = new SaajSoapMessageFactory(
MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL));
getWebServiceTemplate().setMessageFactory(messageFactory);
response = getWebServiceTemplate().marshalSendAndReceive(
adProperties.getServiceEndpoint(), payLoad, new SoapActionCallback(soapAction) {
public void doWithMessage(WebServiceMessage message) {
try {
SaajSoapMessage soapMessage = (SaajSoapMessage) message;
SOAPMessage saajMessage = soapMessage.getSaajMessage();
SOAPEnvelope envelope = saajMessage.getSOAPPart().getEnvelope();
SOAPHeader header = envelope.getHeader();
QName wsaToQName = new QName(WS_ADDRESSING_URI, TO_TAG, WSA_PREFIX);
SOAPHeaderElement wsaTo = header.addHeaderElement(wsaToQName);
wsaTo.setTextContent(adProperties.getServiceEndpoint());
QName wsaActionQName = new QName(WS_ADDRESSING_URI, ACTION_TAG,
WSA_PREFIX);
SOAPHeaderElement wsaAction = header
.addHeaderElement(wsaActionQName);
wsaAction.setTextContent(soapAction);
} catch (Exception e) {
log.error("", e);
}
}
});
} catch (Exception ex) {
log.error(ex);
}
return response;
}
}
Configuration:
#Configuration
public class MyPartnersServiceConfiguration {
#Bean
public Jaxb2Marshaller marshaller() {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setPackagesToScan("com.test.adminUI.myPartners.wsdl");
return marshaller;
}
#Bean
public IFXPartnersServiceClient iFXPartnersServiceClient(Jaxb2Marshaller marshaller) {
IFXPartnersServiceClient client = new IFXPartnersServiceClient();
client.setDefaultUri("http://test.idms.partnersservice");
client.setMarshaller(marshaller);
client.setUnmarshaller(marshaller);
return client;
}
}
Does anybody know what i have to do?
Thanks in advance!
UPDATE
I forgot to mention, that I also get a warning in my console:
o.a.http.impl.auth.HttpAuthenticator: NEGOTIATE authentication error: No valid credentials provided (Mechanism level: No valid credentials provided (Mechanism level: Failed to find any Kerberos tgt))
Is this the problem? What do I have to do in this case?
#Bean
public IFXPartnersServiceClient iFXPartnersServiceClient(Jaxb2Marshaller marshaller) {
IFXPartnersServiceClient client = new IFXPartnersServiceClient();
client.setDefaultUri("http://test.idms.partnersservice");
client.setMarshaller(marshaller);
client.setUnmarshaller(marshaller);
//Set messageSender to client
client.setMessageSender(httpComponentsMessageSender());
return client;
}