I have generated a webservice client with a local wsdl using Metro 1.2 this way:
./wsimport.sh -extension -verbose -wsdllocation service.wsdl -s src -d target service.wsdl -Xendorsed
The wsdl uses SOAP 1.2 and wsHttpBinding. It's supposed to connect to a WCF server that's using NTLM as authentication method.
I have created an Authenticator to handle the NTLM authentication:
public class NtlmAuthenticator extends Authenticator
{
private String username = "";
private String password = "";
public NtlmAuthenticator(String username, String password) {
this.username = username;
this.password = password;
}
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password.toCharArray());
}
}
Which I set before each webservice method is called:
#WebEndpoint(name = "WSHttpBinding_ICustomerService")
public ICustomerService getWSHttpBindingICustomerService() {
ICustomerService service =
super.getPort(new QName("http://xmlns.example.com/services/Customer",
"WSHttpBinding_ICustomerService"), ICustomerService.class);
NtlmAuthenticator auth = new NtlmAuthenticator(username, password);
Authenticator.setDefault(auth);
return service;
}
If I use the wrong username/password, I get a 401 Unauthorized back, which is well and all, but when I use the correct username/password, the call hangs and I never get a response!
The request looks like this (captured it with netcat, so host is different, and no https):
POST / HTTP/1.1
Content-type: application/soap+xml;charset="utf-8";action="http://xmlns.example.com/services/ICustomerService/GetCustomer"
Password: [password]
Authorization: Basic [auth]
Username: [username]
Accept: application/soap+xml, multipart/related, text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
User-Agent: JAX-WS RI 2.1.7-b01-
Cache-Control: no-cache
Pragma: no-cache
Host: localhost:5500
Connection: keep-alive
Content-Length: 603
[xml follows]
I have also tried with wget 1.12 (heard that 1.11 had problem with NTLM), but it too never yields a response, just waits.
[...]
---request end---
[writing POST file customerRequest.xml ... done]
HTTP request sent, awaiting response...
I've seen that others have gotten this behaviour before, but I have not been able to find out why. Can anyone shed some light on this? JDK 1.6 on linux.
I found that I missed a line in my generated client code that enabled Addressing and pass it to the getPort super method:
WebServiceFeature wsAddressing = new AddressingFeature(true);
ICustomerService service =
super.getPort(new QName("http://xmlns.example.com/services/Customer",
"WSHttpBinding_ICustomerService"), ICustomerService.class,
wsAddressing);
Why metro didn't generate this is beyond me. The method looked like this in the end:
#WebEndpoint(name = "WSHttpBinding_ICustomerService")
public ICustomerService getWSHttpBindingICustomerService() {
WebServiceFeature wsAddressing = new AddressingFeature(true);
ICustomerService service =
super.getPort(new QName("http://xmlns.example.com/services/Customer",
"WSHttpBinding_ICustomerService"), ICustomerService.class,
wsAddressing);
NtlmAuthenticator auth = new NtlmAuthenticator(username, password);
Authenticator.setDefault(auth);
return service;
}
This in turn added a SOAP header to the message:
<S:Header>
<To xmlns="http://www.w3.org/2005/08/addressing">https://services.example.com/CustomerService.svc</To>
<Action xmlns="http://www.w3.org/2005/08/addressing">http://xmlns.example.com/services/ICustomerService/GetCustomer</Action>
<ReplyTo xmlns="http://www.w3.org/2005/08/addressing">
<Address>http://www.w3.org/2005/08/addressing/anonymous</Address>
</ReplyTo>
<MessageID xmlns="http://www.w3.org/2005/08/addressing">uuid:d33c2888-abfa-474d-8729-95d2bcd17a96</MessageID>
</S:Header>
Related
I have two sites on the same IIS instance. One uses HttpClient to request data from the other. They are both configured with Windows Authentication only. These are both ASPNET Core 3.1.
When I browse to the first site, it authenticates, but when it calls through to the other, it returns a 401. I validated that the user identity is correct.
var baseUri = new Uri(AppSettings.CurrentValue.MyBaseUrl);
var user = (WindowsIdentity)HttpContext.User.Identity;
WindowsIdentity.RunImpersonated(user.AccessToken, () =>
{
AppContext.SetSwitch("System.Net.Http.UseSocketsHttpHandler", false);
var credentialCache = new CredentialCache {{baseUri, "NTLM", CredentialCache.DefaultNetworkCredentials}};
var httpClientHandler = new HttpClientHandler {Credentials = credentialCache};
using HttpClient httpClient = new HttpClient(httpClientHandler) { BaseAddress = baseUri };
var response = httpClient.GetAsync("/home/test").Result;
var content = response.IsSuccessStatusCode
? response.Content.ReadAsStringAsync().Result
: response.StatusCode.ToString();
}
Wireshark shows the call into the first site, /home/test1, and shows the user credentials being passed correctly,
GET /home/test1 HTTP/1.1
HTTP/1.1 401 Unauthorized (text/html)
GET /home/test1 HTTP/1.1 , NTLMSSP_NEGOTIATE
HTTP/1.1 401 Unauthorized , NTLMSSP_CHALLENGE (text/html)
GET /home/test1 HTTP/1.1 , NTLMSSP_AUTH, User: COMPANY\fbloggs
The same trace shows the jump to the second site, /home/test2, and shows null domain and username,
GET /home/test2 HTTP/1.1
HTTP/1.1 401 Unauthorized (text/html)
GET /home/test2 HTTP/1.1 , NTLMSSP_NEGOTIATE
HTTP/1.1 401 Unauthorized , NTLMSSP_CHALLENGE (text/html)
GET /home/test2 HTTP/1.1 , NTLMSSP_AUTH, ** User: \ **
GET /home/test2 HTTP/1.1\r\n
[Expert Info (Chat/Sequence): GET /home/test2 HTTP/1.1\r\n]
[GET /home/test2 HTTP/1.1\r\n]
[Severity level: Chat]
[Group: Sequence]
Request Method: GET
Request URI: /home/test2
Request Version: HTTP/1.1
Connection: Keep-Alive\r\n
Request-Id: |60fb71bd-482efe66c05094ec.1.\r\n
Host: testserver\r\n
Authorization: NTLM TlRMTVNTUAADAAAAAQDADEIAAAAAAAAAcwAAAAAAAABYAAAAAAAAAFgAAAAaABoAWAAzAAAABYqIogoAY0UAAAAPvaq0nk2I7YcqJmq01EbY20IASDTATGSAGVAALQBXAEUAQgAyADEAAA==\r\n
NTLM Secure Service Provider
NTLMSSP identifier: NTLMSSP
NTLM Message Type: NTLMSSP_AUTH (0x00000003)
Lan Manager Response: 00
NTLM Response: Empty
Domain name: NULL
User name: NULL
Host name: TESTSERVER
Session Key: Empty
Negotiate Flags: 0xa2888a05, Negotiate 56, Negotiate 128, Negotiate Version, Negotiate Target Info, Negotiate Extended Security, Negotiate Always Sign, Negotiate Anonymous, Negotiate NTLM key, Request Target, Negotiate UNICODE
Version 10.0 (Build 17763); NTLM Current Revision 15
Major Version: 10
Minor Version: 0
Build Number: 17763
NTLM Current Revision: 15
MIC: bdaab49e4d88ed872a266ab4d446d8db
HTTP/1.1 401 Unauthorized (text/html)
I would like to get "access_token" and "id_token" from Token endpoint through Authorization Code flow. But, I am getting "invalid_grant" error while calling the token endpoint with following parameters on postman.
POST /connect/token HTTP/1.1
Host: localhost:2000
Content-Type: application/x-www-form-urlencoded
Cache-Control: no-cache
Postman-Token: a8a29659-0ea3-e7dc-3bd6-6e6630a7370d
client_id=client
&client_secret=client
&grant_type=authorization_code
&username=admin
&password=admin
&scope=openid+profile
Client Configuration:
new Client
{
ClientId = "client",
ClientSecrets =
{
new Secret("client".Sha256())
},
AllowedGrantTypes = new List<string> { OidcConstants.GrantTypes.AuthorizationCode },
AllowedScopes = {
StandardScopes.OpenId.Name,
StandardScopes.Profile.Name,
}
}
What is wrong in my client configuration section? and, How do i make a successful post request to Token Endpoint?
The authorization code grant type requires a code parameter to be sent during the token request (see RFC6749 section 4.1.3).
This code is issued by the authorization server after the resource owner authorized the client (see RFC6749 section 4.1.2).
I am encountering a problem when I upgraded my ServiceStack recently. I separated the different versions to find the problem started at v4.0.21. All earlier versions work and all later versions do not work. It only happens with my call to authenticate (with Basic Auth). Also, it only happens when I make the call to authenticate from our iPad app. Since we have not made any changes to our iPad app I know that something changed with ServiceStack that is causing our problem. I looked through the release notes and found there were a lot of changes to the auth capability due to the addition of a Windows Auth Provider and a couple of other new OAuth providers.
Is there some changes to the settings that I need to make that I am not seeing in the Release Notes? Has anyone else encountered this problem?
Here is our code for registering for ss-auth in global.asax.cs:
public override void Configure(Funq.Container container)
{
SetConfig(new HostConfig {
EnableFeatures = Feature.All.Remove(Feature.Metadata),
AllowJsonpRequests = false,
HandlerFactoryPath = "api"
});
var authFeature = new AuthFeature(
() => new AuthUserSession(),
new IAuthProvider[] {
new MyBasicAuthProvider() // override of BasicAuthProvider
}
);
authFeature.HtmlRedirect = null;
authFeature.IncludeAssignRoleServices = false;
Plugins.Add(authFeature);
container.Register<ICacheClient>(new AzureCacheClient("default"));
var userRepository = new InMemoryAuthRepository();
container.Register<IUserAuthRepository>(userRepository);
}
Here is the request URL:
POST https://vh.azurewebsites.net/api/auth?format=json
And here are the headers that went with the HTTP Request:
Host: vh.azurewebsites.net
Authorization: Basic dXN2dONjb3R0OnBhc3N3b3Jk
Accept-Encoding: gzip, deflate
Accept: application/json
Cookie: ss-opt=perm
Accept-Language: en;q=1, fr;q=0.9, de;q=0.8, ja;q=0.7, nl;q=0.6, it;q=0.5
Content-Length: 0
Connection: keep-alive
Proxy-Connection: keep-alive
User-Agent: mHealth/QA (iPad; iOS 7.1.1; Scale/1.00)
The auth provider was changed so that the implicit default /auth can now be used to tell if a user is authenticated which will return Session Info if a user is already authenticated or a 401 Unauthorized if they're not.
You need to call the explicit /auth/{provider} Auth Provider Route for the auth provider you wish to authenticate against which for Basic Auth is /auth/basic.
I tried to implement an OAuth client using OAuthClientRequest in Apache Oltu. And it seems to be that it is sending client credentials in the message body not in the Basic Auth headers according to the spec. I am not sure, I may have missed some thing in the code.
Code
OAuthClientRequest.tokenLocation("http://localhost:8081/token")
.setGrantType(GrantType.CLIENT_CREDENTIALS)
.setClientId(clientKey)
.setClientSecret(clientSecret)
.buildBodyMessage();
Request
POST /token HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Cache-Control: no-cache
Pragma: no-cache
User-Agent: Java/1.6.0_29
Host: 127.0.0.1:8081
Accept: text/html, image/gif, image/jpeg, *; q=.2, /; q=.2
Connection: keep-alive
Content-Length: 127
client_secret=f921854d-f70b-4180-9fdd-3a55032103cc&grant_type=client_credentials&client_id=3f3b4092-7576-4b26-8135-980db7864c2
You might want to change buildBodyMessage() with buildQueryMessage()
The OAuth2 Bearer Token specification defines three methods of sending bearer access tokens:
Authorization Request Header Field
Form-Encoded Body Parameter
URI Query Parameter
The method buildBodyMessage() will create a request with a Form-Encoded Body Parameter. You need to use buildHeaderMessage() instead, which is also the recommended method by the specification.
Recently, I've trying to find a OAuth2 java library to get "client_credential" type of accesstoken. And below is what I have for Apache Oltu, and it seems that it is working.
#Test
public void getAccessTokenViaApacheOltuOAuthClient() {
try{
OAuthClient client = new OAuthClient(new URLConnectionClient());
OAuthClientRequest request =
OAuthClientRequest.tokenLocation(TOKEN_REQUEST_URL)
.setGrantType(GrantType.CLIENT_CREDENTIALS)
.setClientId(CLIENT_ID)
.setClientSecret(CLIENT_SECRET)
.setScope(StringUtils.join(TEST_SCOPES, " ")) //if you have scope
.buildBodyMessage();
String token =
client.accessToken(request, "POST", OAuthJSONAccessTokenResponse.class)
.getAccessToken();
System.out.println(token);
assertTrue( token != null);
} catch (Exception e) {
e.printStackTrace();
}
}
have created simple Restful service for log in verification. Following are my interface and class definitions.
Interface IDemo:
public interface IDemo
{
[OperationContract]
[WebInvoke(RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "/ValidateUser?Username={UserName}&Password={Password}",
Method = "POST")]
string ValidateUser(string Username, string Password);
}
Class Demo :
public class Demo:IDemo
{
public string ValidateUser(string Username, string Password)
{
Users objUser = new Users();
objUser.UserID = Username;
objUser.Password = Password;
string Msg = LoginDataService.ValidateUser(Username, Password);
return Msg;
}
}
localhost:49922/Demo.svc/ValidateUser?Username=demo&Password=demo (with http:\)
When I try to parse the above URL under the Post Method in Fiddler2 I got Bad Request HTTP400 error.
Can anyone help me what is wrong in my code.
Thanks & Regards,
Vijay
Your URI template looks like you are sending the parameters in the URL. But when you use POST the parameters are sent in the http body.
Note you should not send the username and passord in the url as it can be logged.
For the above REST method the POST from Fiddler needs to be as shown below:
POST http://localhost/Sample/Sample.svc/ValidateUser?Username=demo&Password=demo HTTP/1.1
User-Agent: Fiddler
Content-Type: application/json
Host: rajeshwin7
Content-Length: 0
Doing so i get back a 200 OK HTTP Status as shown below:
HTTP/1.1 200 OK
Cache-Control: private
Content-Length: 44
Content-Type: application/json; charset=utf-8
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Thu, 14 Jun 2012 15:35:28 GMT
"Server returns username demo with password demo"