Securing Glassfish REST Service with basic auth using annotations - rest

I have been trying to secure an application, which is deployed to glassfish 3 using annotation instead of the deployment descriptor. However, I haven't been able to get it working correctly. If I try to access the service, I end up with a server error 500, which displays this message:
type Exception report
message
descriptionThe server encountered an internal error () that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: javax.ejb.AccessLocalException: Client not authorized for this invocation
root cause
javax.ejb.AccessLocalException: Client not authorized for this invocation
The EJB looks like this:
#Path("/myresource")
#Stateless
#RolesAllowed("user-role")
public class MyResource {
#GET
#Path("/{uuid}")
public Response getData(#PathParam("uuid") final String uuid) {
....
}
}
sun-web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sun-web-app PUBLIC "-//Sun Microsystems, Inc.//DTD GlassFish Application Server 3.0 Servlet 3.0//EN"
"http://www.sun.com/software/appserver/dtds/sun-web-app_3_0-0.dtd">
<sun-web-app>
<security-role-mapping>
<role-name>user-role</role-name>
<group-name>user-group</group-name>
</security-role-mapping>
</sun-web-app>
This is the web.xml:
<web-app id="myservice" version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name>org.test.myservice</display-name>
<servlet>
<servlet-name>Jersey Web Application</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>org.test.myservice.rest</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>file</realm-name>
</login-config>
<security-role>
<role-name>user-role</role-name>
</security-role>
</web-app>
The file realm in glassfish is set up using the user and role specified in the sun-web.xml and has been working well, when setting up the application security via deployment descriptor.
If I understand this document correctly I do not have to link security role references if their names are the same. http://docs.oracle.com/javaee/5/tutorial/doc/bnbyl.html#bnbyt
Any ideas what I am missing?
Edit
Related to the problem of not being able to specify the required information with annotations, there is a another problem, which caused me to think about this issue. Maybe that will make the initial question a little clearer:
Taken above example, the resource /myresource/* is only available for users with role 'user-role'. However, if there is a second resource at path /myresource/*/thumbnail (translating to /myresource/[uuid]/thumbnail) which should be available without authentication, this is not possible by specifying security-constraints with url-mapping, since it does not seem to be possible to use the wildcard between constants. However, this would be doable by specifying the roles, that are allowed to access a method by annotions. As described above, I haven't been able to do so. How could a mapping like that be done?

You need to use the security-constraint element in web.xml descriptor in order to block specific resources and paths, and to specify the authorization constraints.
This doesn't mean that you can't add more fine-grained controls using Programmatic Security, as explained in Oracle's Java EE 6 Tutorial:
Programmatic security is embedded in an application and is used to make security decisions. Programmatic security is useful when declarative security alone is not sufficient to express the security model of an application.
As per your edited question.
I would use the security-constraint element for blocking the access to all non-registered users. This will force everybody to authenticate, so that your application knows the roles they have.
Then you can fine-grain control the access to the various resources using programmatic security.
With basic authentication I guess there are no other ways. If you want to avoid authentication for basic users, you need to go with form authentication and handle the authentication programmatically behind the scenes, authenticating them even if they aren't aware of, by using HttpServletRequest#login().
In both ways you should be able to setup rights in the way you have described. If you want to handle the unauthorized exception more smoothly, you'd better remove the #RolesAllowed annotation and instead use something like:
#GET
#Path("/{uuid}")
public Response getData(#PathParam("uuid") final String uuid, #Context SecurityContext sc) {
if (sc.isUserInRole("MyRole")) {
return result;
} else {
return notAllowedResult;
}
}

The Roles-Allowed is an EJB construct and not congruent with access to the resource, which is handled by the security constraint.
Unfortunately, the two security concepts do not mesh as well as they should, and instead of getting a 401 if you're not authorized (a web concept), you get the security exception that you are receiving (and EJB concept). In fact, I don't know what error you will receive if you annotate an EJB web service with a RolesAllowed and try to access the web service with an invalid role. I assume you'll get a SOAP fault, in that case.
The EJB security is a system that keeps unauthorized people out, but it's a last ditch effort. It assumes that any decisions to route folks to the method calls is already done up front. For example, there's no high level way to test if a method is allowed or not, rather you can only call it and catch the exception.
So the harsh truth is beyond coarse gatekeepers, you want to leverage Programmatic Security.

Related

Using Keycloak adapter with Wildfly 26 does not provide "KEYCLOAK" as mechanism

I have a JAX-RS application deployed in WildFly. The application's endpoints shall be protected by Keycloak with Access Type: bearer-only. This works perfectly fine for WildFly versions up to 24.
Starting from WildFly 25 the Keycloak adapter is deprecated and one should migrate to the new Elytron subsystem. According to this WildFly issue https://issues.redhat.com/browse/WFLY-15485 however the OIDC adapter is not ready yet to work with bearer-only. But it is mentioned that it should still be possible using the Keycloak Wildfly adapter.
Also the latest Keycloak documentation and this thread in Google Groups states this.
So I installed the adapter from this location and ran the installation script:
https://github.com/keycloak/keycloak/releases/download/16.1.1/keycloak-oidc-wildfly-adapter-16.1.1.zip
./bin/jboss-cli.sh --file=bin/adapter-elytron-install-offline.cli -Dserver.config=standalone-full.xml
When deploying the application I get thte following error message:
java.lang.IllegalStateException: The required mechanism 'KEYCLOAK' is not available in mechanisms [BASIC, CLIENT_CERT, DIGEST, FORM] from the HttpAuthenticationFactory
Setup
WildFly 26 (Jakarta EE 8)
Keycloak 16.1.1
web.xml
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<!-- Security configuration -->
<security-constraint>
<web-resource-collection>
<web-resource-name>admin-api</web-resource-name>
<url-pattern>/administration/*</url-pattern>
<url-pattern>/operations/*</url-pattern>
<url-pattern>/applications/*</url-pattern>
<url-pattern>/entities/*</url-pattern>
</web-resource-collection>
</security-constraint>
<login-config>
<auth-method>KEYCLOAK</auth-method>
<realm-name>this is ignored currently</realm-name>
</login-config>
<security-role>
<role-name>*</role-name>
</security-role>
</web-app>
I managed to implement Bearer Token Authorization with Keycloak and Elytron in WildFly 26 in order to control access to RESTful Web services in a Web Module (.war) of an Enterprise Application (.ear), but the solution is not without problems. This is what I did:
Define an elytron token realm
/subsystem=elytron/token-realm=xyz2ap112-token-realm/:add(\
principal-claim=preferred_username,\
oauth2-introspection={\
client-id=xyz2ap112-web-api,\
client-secret=${env.keycloak_client_secret},\
introspection-url=${env.keycloak_introspection_url}\
}\
)
Define an elytron role decoder
/subsystem=elytron/simple-role-decoder=xyz2ap112-realm-access-roles/:add(\
attribute=realm_access_roles\
)
Warning: the default "Token Claim Name" for Keycloak realms is "realm_access.roles". For this role decoder to work, I had to change it to "realm_access_roles" (no dot). I'll mention this again when I talk about the problems with this solution.
Define an elytron security domain
/subsystem=elytron/security-domain=xyz2ap112-token-security-domain/:add(\
realms=[{realm="xyz2ap112-token-realm",role-decoder="xyz2ap112-realm-access-roles"}],\
default-realm=xyz2ap112-token-realm,\
permission-mapper=default-permission-mapper\
)
Define an elytron HTTP authentication factory
/subsystem=elytron/http-authentication-factory=xyz2ap112-web-api-authentication-factory/:add(\
security-domain=xyz2ap112-token-security-domain,\
mechanism-configurations=[{\
mechanism-name=BEARER_TOKEN,\
mechanism-realm-configurations=[realm-name=xyz2ap112-token-realm]\
}],\
http-server-mechanism-factory=global\
)
Define two application security domains
ejb3 subsystem
/subsystem=ejb3/application-security-domain=xyz2ap112-web-api-security-domain/:add(\
security-domain=xyz2ap112-token-security-domain\
)
Warning: the war that contains the web services does not contain the EJBs it needs; those are in a separate EJB Module (.jar). I guess that is why I had to define this application security domain in the ejb3 subsystem.
undertow subsystem
/subsystem=undertow/application-security-domain=xyz2ap112-web-api-security-domain/:add(\
http-authentication-factory=xyz2ap112-web-api-authentication-factory,\
override-deployment-config=true\
)
Configure application’s jboss-web.xml and web.xml
<jboss-web>
<context-root>/xyz2ap112-web-api</context-root>
<resource-ref>
<res-ref-name>jdbc/xyz2ap112</res-ref-name> <!-- Logical name only. -->
<jndi-name>java:/jdbc/xyz2ap112</jndi-name> <!-- Real JNDI name. -->
</resource-ref>
<security-domain>xyz2ap112-web-api-security-domain</security-domain>
</jboss-web>
The security-domain is the application security domain defined in the undertow subsystem.
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>xyz2ap112-web-api-security-domain</realm-name>
</login-config>
The real-name in login-config is the application security domain defined in the undertow subsystem.
PROBLEMS
As I said before, this solution is not without problems. Given that my Enterprise Application (.ear) also has another Web Module (.war), which contains the GUI components of the application and no Web Services, this solution works as long as the auth-method of that second Web Module is FORM or BASIC. And, as you might have already guessed, I want to use OIDC.
Using OIDC to control access to the application is very straightforward, as properly explained by Farah Juma in her article Securing WildFly Apps with OpenID Connect. But that works as long as the "Token Claim Name" of the Keycloak realm is "realm_access.roles" (its default value). With that name the simple-role-decoder doesn’t work. So, I guess a custom role-decoder is required. Given that my application is able to define and administer roles and role assignments on its own, instead of writing a custom role-decoder, I used a constant-role-mapper to get a single role that allows the web services to execute and check permissions using the roles defined within the application. Once again, that works as long as the auth-method of that second Web Module is FORM or BASIC; with OIDC, the web services are not executed; client gets an HTTP 500 (see below). There is no additional information in the logs of any of the running WildFly (Keycloak and application).
This is the oidc.json file of the GUI Web Module:
{
"client-id": "xyz2ap112-web",
"confidential-port": 8543,
"principal-attribute": "preferred_username",
"provider-url": "http://localhost:8180/auth/realms/jrcam",
"public-client": true,
"ssl-required": "external"
}
And this is the client exception:
Exception in thread "main" javax.ws.rs.InternalServerErrorException: HTTP 500 Internal Server Error
at org.glassfish.jersey.client.JerseyInvocation.convertToException(JerseyInvocation.java:1098)
at org.glassfish.jersey.client.JerseyInvocation.translate(JerseyInvocation.java:883)
at org.glassfish.jersey.client.JerseyInvocation.lambda$invoke$1(JerseyInvocation.java:767)
at org.glassfish.jersey.internal.Errors.process(Errors.java:316)
at org.glassfish.jersey.internal.Errors.process(Errors.java:298)
at org.glassfish.jersey.internal.Errors.process(Errors.java:229)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:414)
at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:765)
at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:428)
at org.glassfish.jersey.client.JerseyInvocation$Builder.get(JerseyInvocation.java:324)
at org.xyz.jax.rs.client.base.AbstractFacadeServiceClient.find(AbstractFacadeServiceClient.java:28)
at xyz2.BarrioFacadeClient.find(BarrioFacadeClient.java:40)
at xyz2.BarrioFacadeClient.main(BarrioFacadeClient.java:24)
If the auth-method of the Web Services Web module is OIDC, the response the client gets is html corresponding to the Keycloak login page.
<html xmlns="http://www.w3.org/1999/xhtml" class="login-pf">
...
<h1 id="kc-page-title">
Sign in to your account
</h1>
...
</html>
This is the oidc.json file of the Web Services Web Module:
{
"client-id": "xyz2ap112-web-api",
"confidential-port": 8543,
"principal-attribute": "preferred_username",
"provider-url": "http://localhost:8180/auth/realms/jrcam",
"ssl-required": "external",
"bearer-only": true,
"verify-token-audience": true,
"realm-public-key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAk3PD30r3SQBqnO15g/Jc5z3NFnt9HLA6QlQt2QLtxvGhLcerTD2rVWCst/4NSQev9dBscFnwxXyAoZAqTm7w0oPzlhw1Xbqt1dpKdNjMtbJxmpqzCRLTjmNatPmoAGx+9TWOPKw1qfEwZOy9xOqnCbBeT5eGCAXci+wvt8mpNX9lpAguFxgpFtyVc0at35Lw3BdZ13+6Ljxu6Z+mam1tQ9mwey0ubfhV3NK0eN8jruKWrCyGw6DRbmvKFTwQa5akDbMWt3H/HaSLMXBOrBKq9He6azVL3dkbdd40drgHtI8G+ANC1NhOPzjPtuifo9U2wHD6o8S03o35mm4xjJNcqQIDAQAB",
"credentials": {
"secret": "8c98045a-4640-46e7-9f68-74a289e43b7e"
}
}
I hope this partial solution will help someone and also that someone can tell me how to implement a complete solution.
I finally got it working without the Keycloak adapter, i.e. using the new built-in Elytron subsystem.
oidc.json (located in the WEB-INF directory)
{
"realm": "myrealm",
"client-id": "my-client-app",
"auth-server-url": "${keycloak.url}/auth",
"provider-url": "${keycloak.url}/auth/realms/myrealm",
"bearer-only": true,
"enable-cors": true,
"ssl-required": "none"
}
web.xml
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<!-- other configuration -->
<login-config>
<auth-method>OIDC</auth-method>
</login-config>
</web-app>

HttpServletRequest.login does not keep logged in for subsequent requests

After logging in using HttpServletRequest.login(String, String), using the code below, on following requests I still get a Basic Authentication prompt. Why is the login function not working in my configuration?
My endpoint:
#POST
#Path("login")
#Consumes(MediaType.APPLICATION_JSON)
public void login(#Valid LoginRequest loginRequest) {
try {
User user = userController.findUserByUsername(loginRequest.getUsername()).orElseThrow(NotFoundException::new);
httpServletRequest.login(loginRequest.getUsername(), loginRequest.getPassword());
log.info(securityContext); // not null now!
}
catch (ServletException e) {
throw new NotAuthorizedException(e.getMessage(), e, AuthenticationHeaderFilter.CHALLENGE);
}
}
And my jboss-web.xml
<?xml version="1.0" encoding="UTF-8"?>
<jboss-web xmlns="http://www.jboss.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.jboss.com/xml/ns/javaee
http://www.jboss.org/j2ee/schema/jboss-web_5_1.xsd">
<security-domain>MyRealm</security-domain>
</jboss-web>
And my web.xml:
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>MyRealm</realm-name>
</login-config>
<security-role>
<role-name>admin</role-name>
</security-role>
<security-role>
<role-name>user</role-name>
</security-role>
<security-constraint>
<display-name>Authenticated content</display-name>
<web-resource-collection>
<web-resource-name>Authentication required</web-resource-name>
<url-pattern>/api/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>user</role-name>
</auth-constraint>
</security-constraint>
<security-constraint>
<display-name>Anonymous content</display-name>
<web-resource-collection>
<web-resource-name>Exclude from Security</web-resource-name>
<url-pattern>/api/me/login</url-pattern>
</web-resource-collection>
</security-constraint>
Actually, the contract for HttpServletRequest#login does not mandate that the authenticated identity be remembered for the duration of the HTTP session (if one already exists), and certainly not that an HTTP session should be created upon successful authentication (for if one does not exist).
Technically speaking, the HttpServletRequest#login call goes straight through to the identity store (the method's Javadoc uses the term login mechanism for that). An identity store is a kind of database that typically only performs the credential validation and does not have knowledge about its environment (i.e. doesn't know about HTTP sessions, or remote EJB context IDs, or JCA inflow security IDs of whatever).
The authentication mechanism IS aware of its environment, and this one is invoked by calling HttpServletRequest#authenticate. But, this would normally be expected to start an interaction dialog with the user when not being authenticated yet, not remember the authenticated identity in the session if the user happens to be authenticated (the fact this happens to work on JBoss seems more like a coincidence than something that is supposed to happen).
That all said, section 13.10 of the Servlet spec does allow containers to create an HTTP session:
Containers may create HTTP Session objects to track login state. If a
developer creates a session while a user is not authenticated, and the
container then authenticates the user, the session visible to
developer code after login must be the same session object that was
created prior to login occurring so that there is no loss of session
information.
(emphasis mine)
But... it's not overly clear if this text is in regard to calling the login() method or the authenticate() one.
In short, this is one of the many small gaps in the Java EE security spec; it's just not defined how to programmatically do a login with a given username/password and explicitly say if you want or do not want that to be for the current request only or for the remainder of the HTTP session.
We hope to fix issues like this in the Java EE Security API (JSR 375) for Java EE 8.
The answer is that after invoking httpServletRequest#login(String, String) you should still invoke httpSevletRequest#authenticate(HttpServletResponse). My final, working code, is:
httpServletRequest.login(loginRequest.getUsername(), loginRequest.getPassword());
httpServletRequest.authenticate(httpServletResponse);
As you want programmatic authentication, there is no need of <login-config> in web.xml

Working Java REST Client Example to access CAS REST API

I followed this tutorial to enable REST service on my local CAS server.
However there is no Java example
"Java REST Client Example
We need a real, working, example, the previous one is useless. Many people are emailing me that it is not working, and I confirm it does not work."
I was able to find this but that unfortunately did not work for me.
Any pointers/links? Much appreciated.
Got it!
Here is the complete solution on how to enable CAS REST API and be able to connect to it via JAVA REST client to benefit others
Get CAS source code.
Review this article
Add following to pom.xml like suggested by the article in #2
<dependency>
<groupId>org.jasig.cas</groupId>
<artifactId>cas-server-integration-restlet</artifactId>
<version>${cas.version}</version>
<type>jar</type>
</dependency>
Make sure to add following to pom.xml to avoid Spring jar collisions. In my case, cas-server-integration-restlet was dependent on spring-web, which used by default older version of Spring. So, I explicitly defined
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>3.1.1.RELEASE</version>
</dependency>
Compile your cas code. Should get cas.war in your target folder.
Upload it to your server, change permissions to tomcat and wait for it to get deployed
In CATALINA/conf find server.xml and uncomment 8443 port configuration so that our sever will allow SSL connections. Also, specify your certs in here.
Now navigate to exploded cas.war file and drill down to WEB-INF folder to find deployerConfigContext.xml file. Specify what CAS would use to authenticate. In my case, I used LDAP.
Add following to web.xml per article above
<servlet>
<servlet-name>restlet</servlet-name>
<servlet-class>com.noelios.restlet.ext.spring.RestletFrameworkServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>restlet</servlet-name>
<url-pattern>/v1/*</url-pattern>
</servlet-mapping>
Restart tomcat for changes to take effect.
Test that you can log in via standard CAS UI: https://server:8443/cas/login
Test that REST API was exposed via: https://server:8443/cas/v1/tickets
Now let's connect to it. I used this sample code. Make sure to give correct links and username/password
When I tried running the code as is, it complained about "Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target". Basically asking you to install certs. If you have the access to the server, just copy it over. If not, I found this code that will take care of the installation for you if you dont have access or just too lazy :)
Now, if you run the JAVA CAS Client with valid credentials you should see something like
201
https://server_name:8443/cas/v1/tickets/TGT-4-rhVWLapYuOYi4InSEcmfNcABzaLMCPJgGIzlKqU1vb50zxb6pp-server_name
Tgt is : TGT-4-rhVWLapYuOYi4InSEcmfNcABzaLMCPJgGIzlKqU1vb50zxb6pp-server_name.ndev.coic.mil
Service url is : service=https%3A%2F%2Fmyserver.com%2FtestApplication
https://server_name:8443/cas/v1/tickets/TGT-4-rhVWLapYuOYi4InSEcmfNcABzaLMCPJgGIzlKqU1vb50zxb6pp-server_name
Response code is: 200
200
ST-4-BZNVm9h6k3DAvSQe5I3C-server_name
You can see 200 code and the ticket. If you were to review logs of your cas on the server, you should see messages about successful athentication and ticket generation.
Change username/password to some dummy data and try to run the code. You will get 400 error message, which means that permission to access was denied.
Success!
For CAS 4.0 it's a little simpler (tested on apache-tomcat-7.0.55)
in your pom.xml add following dependency
<dependency>
<groupId>org.jasig.cas</groupId>
<artifactId>cas-server-integration-restlet</artifactId>
<version>4.0.0</version>
<scope>runtime</scope>
<exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</exclusion>
</exclusions>
</dependency>
Direct dependency to springframework is not necesarry because exclusions prevent from duplicated packages
In your web.xml you need to add servlet mapping for restlet (mind package has changed from com.noelios.restlet... to org.restlet...
<servlet>
<servlet-name>restlet</servlet-name>
<servlet-class>org.restlet.ext.spring.RestletFrameworkServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>restlet</servlet-name>
<url-pattern>/v1/*</url-pattern>
</servlet-mapping>
As a result of above steps in yuor WEB-INF/lib directory following new files should be added
ls target/cas/WEB-INF/lib/ | grep restlet
cas-server-integration-restlet-4.0.0.jar
org.restlet-2.1.0.jar
org.restlet.ext.servlet-2.1.0.jar
org.restlet.ext.slf4j-2.1.0.jar
org.restlet.ext.spring-2.1.0.jar
If you wish to skip cert validation add this to your Java Client
//////////////////////////////////////////////////////////////////////////////////////
// this block of code turns off the certificate validation so the client can talk to an SSL
// server that uses a self-signed certificate
//
// !!!! WARNING make sure NOT to do this against a production site
//
// this block of code owes thanks to http://www.exampledepot.com/egs/javax.net.ssl/trustall.html
//
TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType){}
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType){}
}
};
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
//
//
// end of block of code that turns off certificate validation
// ////////////////////////////////////////////////////////////////////////////////////
Usually devs are confused on how to get rest client working when accessing secured CAS web service. Most of the question out there were asking how to get restlet CAS secures a webservice and how to call those web service, because no real example were working.
Well actually there is. Groovy example is on the JASIG Cas restlet example https://wiki.jasig.org/display/casum/restful+api is clearly show how to get authenticated to call a service (its using Groovy, but converting to Java should be straight forward) . But in my opinion, it do not clearly explain that client need to authenticate to the designated web service first before accessing CAS secured web service.
For example, assume there is a JSON service that secured with CAS and build with Java and Spring. And you are using code that describe on the groovy section on https://wiki.jasig.org/display/casum/restful+api
String casUrl="https://yourcas.com/v1/tickets"
String springTicketValidation="http://yourservice.com/j_spring_cas_security_check"
String serviceToCall="http://yourservice.com/serviceToCall"
To get your service client be able to call the service, you need to follow these simple rules:
Get your ticket granting ticket from CAS
Get your Service Ticket from cas for the designated service call (service to call)
Authenticate to your service ticket validator (at this point url specified on springTicketValidation)
finally call your service
or in code perspective
String ticketGrantingTicket = getTicketGrantingTicket(casUrl, username, password)
String serviceTicket = client.getServiceTicket(casUrl, ticketGrantingTicket, serviceToCall)
// validate your ticket first to your application
getServiceCall(springTicketValidation, serviceTicket)
getServiceCall(serviceToCall, serviceTicket)
And for your note, all these operation should be done in following condition:
Your call (both restlet call and service call) should be done in the same HttpClient object. It seems that CAS put "something" in the session object that validated when you call your service. Fails this, and you will always get logon page on the HTTP result.
Your cas client should be able to recognized your CAS SSL certificate, otherwise it will throw you PKIX path building failed
This example is based on the cas secured web service that using Spring Security to secured service with CAS. I'm not sure whether other cas secured should need ticket validation on the application side or not
Hope this help

RESTLET on Camel with Jetty

As far as I understand, Camel by default uses the default RESTLET engine. How can I tell Camel to use Jetty instead?
I know there are ways to bundle your application and deploy it in Tomcat or Jetty. If I do that, however, the biggest question becomes how to integrate with RESTLET.
I did some further digging. I took one of the tomcat examples that come with the camel. Then I tried to make it RESTLET capable. It almost works. The problem now is that the parameters are not being passed to the route. I would expect that when calling this server: http://x.x.x.x:8080/rs/user/?name=Paul, I would get: Hello Paul how are you?
However, I simply get: Hello how are you?
My camel configuration is:
<camelContext xmlns="http://camel.apache.org/schema/spring">
<route>
<from uri="restlet:/user/?restletMethods=GET,POST" />
<transform>
<simple>Hello ${header.name} how are you?</simple>
</transform>
</route>
</camelContext>
<bean id="RestletComponent" class="org.restlet.Component" />
<bean id="RestletComponentService" class="org.apache.camel.component.restlet.RestletComponent">
<constructor-arg index="0">
<ref bean="RestletComponent" />
</constructor-arg>
</bean>
And my web.xml is:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:camel-config.xml</param-value>
</context-param>
<servlet>
<servlet-name>RestletServlet</servlet-name>
<servlet-class>org.restlet.ext.spring.SpringServerServlet</servlet-class>
<init-param>
<param-name>org.restlet.component</param-name>
<param-value>RestletComponent</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>RestletServlet</servlet-name>
<url-pattern>/rs/*</url-pattern>
</servlet-mapping>
I am getting a little bit closer with my investigation. It appears that ${in.body} will indeed pass the body of the request to the route. I am still trying to find out what is going on with the header. I even tried using the producer template to call the headers, still it does work. So, this somehow suggests that the way to access the header in RESTLET is different than in the pure servlet? Here is my producer template:
Map<String, Object> headers = new HashMap<String, Object>();
headers.put("name","Paul");
context.createProducerTemplate().requestBodyAndHeaders(
"restlet:http://localhost:8080/camel-example-servlet-tomcat/rs/user/?restletMethod=post", "Halleluia",headers);
Have a look at the org.apache.camel.component.restlet.DefaultRestletBinding class. By default form data is only bound when content type is "application/x-www-form-urlencoded". Also, only URI template values will be bound to headers.
To get at arbitrary query parameters you can do something like:
Request request = exchange.getIn().getHeader(RestletConstants.RESTLET_REQUEST, Request.class);
String value = request.getResourceRef().getQueryAsForm().getFirstValue("foo");
Also, the raw query string will be available in the CamelHttpQuery header.
You can supply your own class which implements RestletBinding (or extend DefaultRestletBinding) by specifying the bean ID of a RestletBinding object in the Camel Registry using the 'restletBinding' endpoint query option. If you are using Spring register a bean like this:
<bean id="myRestletBinding" class="com.example.MyRestletBinding"/>
OK. It appears I had to access the URL parameter with in.header.name instead of header.name. I have no explanation as to why header.name would work in the normal servlet. Also, I managed to get this working only with POST. With GET, the parameters are still not passed to the RESTLET engine or I do not know how to retrieve them. On the contrary, GET works fine when using pure servlet. Solution is good for me and I thus mark this as answered.
I would suggest you to use camel CXFRS component. Have a service class where all REST annotations are declared. You can have the username as path parameter or query parameter.
Syntax would be something like this :
from("cxfrs://http://localhost:9992/service?resourceClasses=com.xyz.web.resources.RESTresource")
REST resource would be your resource class. This will run a REST web service over a jetty web server.

Rest - Jersey.Client pass #SecurityContext to Server

I want to pass a security context to my rest service.
On server side I try to get this with:
public Response postObject(#Context SecurityContext security, JAXBElement<Object> object) {
System.out.println("Security Context: " + security.getUserPrincipal());
.....
But actually the Syso is null.
On Client side im just doing:
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
client.addFilter(new HTTPBasicAuthFilter("user", "password"));
So, do I have to change in addition something in my web.xml to get it working?
I hoped its working without setting up static users in the tomcat user xml. So I can compare the user/password from security context with my "persistent" user/password hashmap located server sided. But when it is not working without tomcat user xml, how can it be done to add dynamically user to that user xml? When I ve static users I cant register a new user. I dont want to use this attempt: http://objecthunter.congrace.de/tinybo/blog/articles/89 cuz I want just to work with a semi persistence like a HashMap of user/password.
Besides another question: Why does everybody refer to Apache HttpClient when it is about security in Jersey, when it is working like I wrote as well?
My attempt refers to this post:
Jersey Client API - authentication
You need to set up your application on the server so that it requires Basic authentication. I.e. include something like the following in the web.xml in your application war file - otherwise Tomcat does not perform the authentication and does not populate the security context.
<security-constraint>
<display-name>Authentication Constraint</display-name>
<web-resource-collection>
<web-resource-name>all</web-resource-name>
<description/>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<description>authentication required</description>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>realm_name</realm-name>
</login-config>