CXF STSClient asks for user+password even though there is a SAML token in onBehalfOf - jwt

I'm using CXF's STSClient to request a JWT token on behalf of a user so I can call a REST service.
I have a valid SAML token and tried to configure the STSClient like so:
stsClient.setTokenType("urn:ietf:params:oauth:token-type:jwt");
stsClient.setKeyType("http://docs.oasis-open.org/ws-sx/ws-trust/200512/Bearer");
stsClient.setOnBehalfOf(samlToken.getToken());
stsClient.setEnableAppliesTo(true);
// Not sure about these.
stsClient.setSendRenewing(false);
stsClient.setKeySize(0);
stsClient.setRequiresEntropy(false);
final Map<String, Object> requestContext = Preconditions.checkNotNull(stsClient.getRequestContext());
requestContext.put(SecurityConstants.USERNAME, name); // Without this, I get "No username available"
SecurityToken result = stsClient.requestSecurityToken(appliesTo);
but when the method fails with:
Caused by: org.apache.cxf.interceptor.Fault: No callback handler and no password available
at org.apache.cxf.ws.security.wss4j.policyhandlers.TransportBindingHandler.handleBinding(TransportBindingHandler.java:182)
at org.apache.cxf.ws.security.wss4j.PolicyBasedWSS4JOutInterceptor$PolicyBasedWSS4JOutInterceptorInternal.handleMessageInternal(PolicyBasedWSS4JOutInterceptor.java:180)
at org.apache.cxf.ws.security.wss4j.PolicyBasedWSS4JOutInterceptor$PolicyBasedWSS4JOutInterceptorInternal.handleMessage(PolicyBasedWSS4JOutInterceptor.java:110)
at org.apache.cxf.ws.security.wss4j.PolicyBasedWSS4JOutInterceptor$PolicyBasedWSS4JOutInterceptorInternal.handleMessage(PolicyBasedWSS4JOutInterceptor.java:97)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:308)
at org.apache.cxf.endpoint.ClientImpl.doInvoke(ClientImpl.java:530)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:441)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:356)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:314)
at org.apache.cxf.ws.security.trust.AbstractSTSClient.issue(AbstractSTSClient.java:874)
at org.apache.cxf.ws.security.trust.STSClient.requestSecurityToken(STSClient.java:71)
at org.apache.cxf.ws.security.trust.STSClient.requestSecurityToken(STSClient.java:65)
at org.apache.cxf.ws.security.trust.STSClient.requestSecurityToken(STSClient.java:61)
Caused by: org.apache.cxf.ws.policy.PolicyException: No callback handler and no password available
at org.apache.cxf.ws.security.wss4j.policyhandlers.AbstractCommonBindingHandler.unassertPolicy(AbstractCommonBindingHandler.java:93)
at org.apache.cxf.ws.security.wss4j.policyhandlers.AbstractBindingBuilder.getPassword(AbstractBindingBuilder.java:1042)
at org.apache.cxf.ws.security.wss4j.policyhandlers.AbstractBindingBuilder.addUsernameToken(AbstractBindingBuilder.java:839)
at org.apache.cxf.ws.security.wss4j.policyhandlers.TransportBindingHandler.addSignedSupportingTokens(TransportBindingHandler.java:115)
at org.apache.cxf.ws.security.wss4j.policyhandlers.TransportBindingHandler.handleNonEndorsingSupportingTokens(TransportBindingHandler.java:208)
at org.apache.cxf.ws.security.wss4j.policyhandlers.TransportBindingHandler.handleBinding(TransportBindingHandler.java:167)
... 16 common frames omitted
Since I have a SAML token, I was expecting that the STSClient doesn't need the user name or password anymore.
How can I tell CXF / STSClient to skip the addUsernameToken() method call?

The problem is in the WSDL definition of the service.
Each port in the WSDL is attached to a URL and a binding. The binding has a policy. The policy in this case requests a user name with password. Look for UsernameToken in the WSDL.
What you need is a port that doesn't require this. I'm no expert in this matter but from the examples I've seen, the policy must not have a SignedSupportingTokens element in them, only Wss11 and Trust13 elements.
Without this element, CXF will take a different path in the code and the error will go away.

Related

How do I load a "user" in a micronaut backend when JWT is provided

I have a Micronaut microservice that handles authentication via JsonWebTokens (JWT) from this guide.
Now I'd like to extend this code. The users in my app have some extra attributes such as email, adress, teamId etc. I have all users in the database.
How do I know in the backend controller method which user corresponds to the JWT that is sent by the client?
The guide contains this example code for the Micronaut REST controller:
#Secured(SecurityRule.IS_AUTHENTICATED)
#Controller
public class HomeController {
#Produces(MediaType.TEXT_PLAIN)
#Get
public String index(Principal principal) {
return principal.getName();
}
}
I know that I can get the name of the principal, ie. the username from the HttpRequest. But how do I get my additional attributes?
(Maybe I misunderstand JWT a bit???)
Are these JWT "claims" ?
Do I need to load the corresponding user by username from my DB table?
How can I verify that the sent username is actually valid?
edit Describing my usecase in more detail:
Security requirements of my use case
Do not expose valid information to the client
Validate everything the client (a mobile app) sends via REST
Authentication Flow
default oauth2 flow with JWTs:
Precondition: User is already registerd. Username, hash(password) and furhter attributes (email, adress, teamId, ..) are known on the backend.
Client POSTs username and password to /login endpoint
Client receives JWT in return, signed with server secret
On every future request the client sends this JWT as bearer in the Http header.
Backend validates JWT <==== this is what I want to know how to do this in Micronaut.
Questions
How to validate that the JWT is valid?
How to and where in which Java class should I fetch additional information for that user (the additional attributes). What ID should I use to fetch this information. The "sub" or "name" from the decoded JWT?
How do I load a “user” in a micronaut backend when JWT is provided?
I am reading this as you plan to load some kind of User object your database and access it in the controller.
If this is the case you need to hook into the place where Authentication instance is created to read the "sub" (username) of the token and then load it from the database.
How to extend authentication attributes with more details ?
By default for JWT authentication is created using JwtAuthenticationFactory and going more concrete default implementation is DefaultJwtAuthenticationFactory. If you plan to load more claims this could be done by replacing it and creating extended JWTClaimsSet or your own implementation of Authentication interface.
How do I access jwt claims ?
You need to check SecurityService -> getAuthentication() ->getAttributes(), it returns a map of security attributes which represent your token serialised as a map.
How to validate that the JWT is valid?
There is a basic validation rules checking the token is not expired and properly signed, all the rest validations especially for custom claims and validating agains a third parties sources have to be done on your own.
If you plan to validate your custom claims, I have already open source a project in this scope, please have a look.
https://github.com/traycho/micronaut-security-attributes
How to extend existing token with extra claims during its issuing ?
It is required to create your own claims generator extending JWTClaimsSetGenerator
#Singleton
#Replaces(JWTClaimsSetGenerator)
class CustomJWTClaimsSetGenerator extends JWTClaimsSetGenerator {
CustomJWTClaimsSetGenerator(TokenConfiguration tokenConfiguration, #Nullable JwtIdGenerator jwtIdGenerator, #Nullable ClaimsAudienceProvider claimsAudienceProvider) {
super(tokenConfiguration, jwtIdGenerator, claimsAudienceProvider)
}
protected void populateWithUserDetails(JWTClaimsSet.Builder builder, UserDetails userDetails) {
super.populateWithUserDetails(builder, userDetails)
// You your custom claims here
builder.claim('email', userDetails.getAttributes().get("email"));
}
}
How do I access jwt claims ?
If you want to access them from the rest handler just add io.micronaut.security.authentication.Authentication as an additional parameter in the handling method. Example
#Get("/{fooId}")
#Secured(SecurityRule.IS_AUTHENTICATED)
public HttpResponse<Foo> getFoo(long fooId, Authentication authentication) {
...
}
I found a solution. The UserDetails.attributes are serialized into the JWT. And they can easily be set in my CustomAuthenticationProviderclass:
#Singleton
#Slf4j
public class CustomAuthenticationProvider implements AuthenticationProvider {
#Override
public Publisher<AuthenticationResponse> authenticate(
#Nullable HttpRequest<?> httpRequest,
AuthenticationRequest<?, ?> authenticationRequest)
{
// ... autenticate the request here ...
// eg. via BasicAuth or Oauth 2.0 OneTimeToken
// then if valid:
return Flowable.create(emitter -> {
UserDetails userDetails = new UserDetails("sherlock", Collections.emptyList(), "sherlock#micronaut.example");
// These attributes will be serialized as custom claims in the JWT
Map attrs = CollectionUtils.mapOf("email", email, "teamId", teamId)
userDetails.setAttributes(attrs);
emitter.onNext(userDetails);
emitter.onComplete();
}, BackpressureStrategy.ERROR);
}
}
And some more pitfalls when validating the JWT in the backend
A JWT in Micronaut MUST contain a "sub" claim. The JWT spec does not require this, but Micronaut does. The value of the "sub" claim will become the username of the created UserDetails object.
If you want to load addition attributes into these UserDetails when the JWT is validated in the backend, then you can do this by implementing a TokenValidator. But (another pitfal) then you must set its ORDER to a value larger than micronaut's JwtTokenValidator. Your order must be > 0 otherwise your TokenValidator will not be called at all.

Keycloak integration to external identity provider fails when validation tokens with JWKS URL

I'm configuring an external identity provider in my Keycloak instance and trying to get it to validate the tokens using a external JWKS URL. Using the converted PEM from JWKS works fine, the using the URL is not working.
The token validation fails upon login with the following message:
[org.keycloak.broker.oidc.AbstractOAuth2IdentityProvider] (default task-4) Failed to make identity provider oauth callback: org.keycloak.broker.provider.IdentityBrokerException: token signature validation failed
I debugged the Keycloak server get more on the problem and found a "problem" in class JWKSUtils:
/**
* #author Marek Posolda
*/
public class JWKSUtils {
//...
public static Map<String, KeyWrapper> getKeyWrappersForUse(JSONWebKeySet keySet, JWK.Use requestedUse) {
Map<String, KeyWrapper> result = new HashMap<>();
for (JWK jwk : keySet.getKeys()) {
JWKParser parser = JWKParser.create(jwk);
if (jwk.getPublicKeyUse().equals(requestedUse.asString()) && parser.isKeyTypeSupported(jwk.getKeyType())) {
KeyWrapper keyWrapper = new KeyWrapper();
keyWrapper.setKid(jwk.getKeyId());
keyWrapper.setAlgorithm(jwk.getAlgorithm());
keyWrapper.setType(jwk.getKeyType());
keyWrapper.setUse(getKeyUse(jwk.getPublicKeyUse()));
keyWrapper.setVerifyKey(parser.toPublicKey());
result.put(keyWrapper.getKid(), keyWrapper);
}
}
return result;
}
//...
}
The if fails with a NullPointerException because the call jwk.getPublicKeyUse() returns null.
But I found out that it's null because the JWKS URL returns a single key without the attribute use, which is optional according to the specification. [https://www.rfc-editor.org/rfc/rfc7517#section-4.2]
Keycloak only accepts JWKS URLs that return all keys with the attribute use defined. But the IdP I'm trying to connect does not return that attribute in the key.
Given that situation, to who should I file an issue, the IdP or to Keycloak? Or is there something I'm doing wrong in the configuration?
I filed an issue with Keycloak about this exact problem in August 2019.
Their answer:
Consuming keys without validating alg and use is dangerous as such
Keycloak requires these to be present.
In my case, I contacted the IdP and they were able to populate the "use" parameter. If that is not an option, then you're pretty much stuck with your workaround.

Getting error while accessing rally using rally-rest-api-2.1.2.jar

I am getting an authentication error for API key in rally. Even api key is given full access.
java.io.IOException: HTTP/1.1 401 Full authentication is required to access this resource
at com.rallydev.rest.client.HttpClient.executeRequest(HttpClient.java:163)
at com.rallydev.rest.client.HttpClient.doRequest(HttpClient.java:145)
at com.rallydev.rest.client.ApiKeyClient.doRequest(ApiKeyClient.java:37)
at com.rallydev.rest.client.HttpClient.doGet(HttpClient.java:221)
at com.rallydev.rest.RallyRestApi.query(RallyRestApi.java:168)
This is The code :
String wsapiVersion = "v2.0";
restApi.setWsapiVersion(wsapiVersion);
restApi.setApplicationName(projectname);
QueryRequest testCaseRequest = new QueryRequest("Testsets");
if(null !=workspace && ""!=workspace)
testCaseRequest.setWorkspace(workspace);
QueryResponse testCaseQueryResponse = restApi.query(testCaseRequest);
What is wrong here ?
One of the things I would check for is whether you are inside a corporate network that uses authenticated proxy servers. Unless you configure the connection correctly, the proxy will reject your request before it even gets to Rally.
Second thing I just thought of is, whether you are setting the right field in the header to enable the use of an APIKey. The Rally servers expect the ZSESSIONID to be set to the APIKey, I believe.

Correct configuration for REST endpoints in Shiro

My original post is here
I am trying to protect a set of REST endpoints with Shiro. My theory is that if I pass a JWT with my REST request, that I can use Shiro (via annotations) to secure my endpoints.
I've create my endpoints like this (for example):
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("status/{companyId}")
#RequiresAuthentication
#RequiresRoles("SomeRole")
public Response getStatus(#PathParam("companyId") int companyId){
... do stuff ...
}
I'm expecting that if I call the endpoint without authenticating, I will get a HTTP 401 error. However, the method is called successfully if the JWT is not supplied as it would be when there is no security on it at all.
I assume then that my Shiro config is incorrect. Since this is strictly a 'backend' application, I have no use for the Shiro/Stormpath configurations that apply to anything 'front-end' related (such as loginURLs, etc.)
Here is my shiro.ini :
[main]
#ERRORS IF UNCOMMENTED
#cacheManager = org.apache.shiro.cache.MemoryConstrainedCacheManager
#securityManager.cacheManager = $cacheManager
#stormpathClient.cacheManager = $cacheManager
# NOT NEEDED?
#sessionManager = org.apache.shiro.web.session.mgt.DefaultWebSessionManager
#securityManager.sessionManager = $sessionManager
#securityManager.sessionManager.sessionIdCookieEnabled = false
#securityManager.sessionManager.sessionIdUrlRewritingEnabled = false
[urls]
/** = rest
This configuration lets every request through (as described above).
If I uncomment the [main] section, I get IllegalArgumentException: Configuration error. Specified object [stormpathClient] with property [cacheManager] without first defining that object's class. Please first specify the class property first, e.g. myObject = fully_qualified_class_name and then define additional properties.
What I need to figure out is what is the correct minimum Shiro configuration for REST endpoints (and ONLY REST endpoints) so I can allow access with a JWT.
Thanks for any help.
I'm guessing the annotations are not being processed by anything at runtime. You will need to tell your JAX-RS app to process them.
I've done this with this lib in the past:
https://github.com/silb/shiro-jersey/
Specifically something like this:
https://github.com/silb/shiro-jersey/blob/master/src/main/java/org/secnod/shiro/jersey/AuthorizationFilterFeature.java
As for the second part of the problem, my only guess is Stormpath/Shiro environment is not setup correctly.
Did you put filter config in your web.xml or is all of the config loaded from the servlet fragment?

How to handle redirect by httpClient fluent?

I'm writing acceptance tests with HttpClient fluent api and have some trouble.
#When("^I submit delivery address and delivery time$")
public void I_submit_delivery_address_and_delivery_time() throws Throwable {
Response response = Request
.Post("http://localhost:9999/food2go/booking/placeOrder")
.bodyForm(
param("deliveryAddressStreet1",
deliveryAddress.getStreet1()),
param("deliveryAddressStreet2",
deliveryAddress.getStreet2()),
param("deliveryTime", deliveryTime)).execute();
content = response.returnContent();
log.debug(content.toString());
}
This code works well when I use post-forward strategy, but an exception is thrown when I use redirect instead.
org.apache.http.client.HttpResponseException: Found
What I want is getting the content of the redirected page. Any idea is appreciate, thanks in advance.
The HTTP specification requires entity enclosing methods such as POST and PUT be redirected after human intervention only. HttpClient honors this requirement by default. .
10.3 Redirection 3xx
This class of status code indicates that further action needs to be
taken by the user agent in order to fulfill the request. The action
required MAY be carried out by the user agent without interaction
with the user if and only if the method used in the second request is
GET or HEAD.
...
If the 302 status code is received in response to a request other
than GET or HEAD, the user agent MUST NOT automatically redirect the
request unless it can be confirmed by the user, since this might
change the conditions under which the request was issued.
One can use a custom redirect strategy to relax restrictions on automatic redirection if necessary.
DefaultHttpClient client = new DefaultHttpClient();
client.setRedirectStrategy(new LaxRedirectStrategy());
Executor exec = Executor.newInstance(client);
String s = exec.execute(Request
.Post("http://localhost:9999/food2go/booking/placeOrder")
.bodyForm(...)).returnContent().asString();
This is for an updated version of apache:
CloseableHttpClient httpClient =
HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy())
.build();