Reputation: 51
I have a Webservice that expects a soap header and return an authentication token. I have managed to post the soap header to the webservice using jquery. The problem is how do i make the browser to send the authenticated token on each request for authorization over the web service. Your help will be much appriciated. Helpful links i used are given below: Reference:
Code:
function logIn(username, password, token) {
var soapMessage =
'<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> \
<soap:Body> \
<SecuredWebServiceHeader xmlns="http://tempuri.org/"> \
<Username>' + username + '</Username> \
<Password>' + password + '</Password> \
<AuthenticatedToken>' + token + '</AuthenticatedToken> \
</SecuredWebServiceHeader> \
</soap:Body> \
</soap:Envelope>';
$.ajax({
url: "http://localhost/wstest/Service.asmx/AuthenticateUser",
type: "POST",
dataType: "xml",
data: soapMessage,
complete: endLogin,
contentType: "text/xml; charset=\"utf-8\""
});
return false;
}
function endLogin(xmlHttpRequest, status) {
alert(xmlHttpRequest.responseXML)
}
Upvotes: 5
Views: 5945
Reputation: 5319
I had the same situation, having to secure a part of my web site (web services included) with forms authentication, and having also an unprotected public part e.g. Login/Register forms, CSS files, JS files...
I solved the login problem by designating a public web service (unprotected with forms authentication) that can handle your login function.
Your login function should look like this:
[WebMethod(EnableSession=true)]
[ScriptMethod]
public ResponseBase<bool> DoLogin(LoginCredentials Credentials)
{
try
{
// Perform login with credentials
if (loginOK)
{
FormsAuthentication.SetAuthCookie(/* Your user identification here */, true);
}
return new ResponseBase<bool> { Code= true};
}
catch (Exception _ex)
{
// Save your log
return new ResponseBase<bool> { Message = "Incorrect Login" };
}
}
Your client will receive the forms authentication cookie and your response to the login. Later you can evaluate if the login was successfull by evaluating the Code attribute in the response.
The ResponseBase class looks like the following:
[Serializable]
[DataContract]
public class ResponseBase<T>
{
/// <summary>
/// Return code.
/// </summary>
[DataMember]
public T Code { get; set; }
/// <summary>
/// Message.
/// </summary>
[DataMember]
public string Message { get; set; }
}
Last, but not least, I encourage you to call your web services using JSON instead of XML because of the light weight of the message with zero changes in the server code. Plus, in the client you don't have to manually build the message, like in your example.
Upvotes: 0
Reputation: 6573
if the response provides a positive - send that token back to your server to store in a session.
Upvotes: 0