Categories
Security

Java EE Security API integration with Octopus

Introduction

The Java EE Security API (JSR-375) goal is to enhance the security features of the Java EE platform and to make sure that no custom configuration of the application server must be updated anymore when you want to use for example hashed passwords stored in a database table.
It was released together with Java EE 8 in September 2017 and one of the main concepts which are defined is the IdentityStore which validates the user credentials (like username and password) and retrieves the groups (the authorization grants) the user has.

The Octopus framework is mainly targeted to authorization features like declarative permissions useable for JSF components (with a custom tag) or annotations (to protect EJB methods for example). There are many authentication integrations available like OAuth2, OpenId Connect, KeyCloak, CAS server and custom integrations for database usage to name a few.

Since v 0.9.7.1, released on 27 December 2017, it is possible to integrate the IdentityStores from JSR-375 within Octopus and most of all, it runs also on Java EE 7.

The demo code can be found in the Octopus demo repository.

Project setup

The JSR-375 integration is defined within a Maven artifact specifically created for this purpose,

<dependency>
    <groupId>be.c4j.ee.security.octopus.authentication</groupId>
    <artifactId>security-api</artifactId>
    <version>${octopus.version}</version>
</dependency>

Together with the dependency for JSF on a Java EE 7 server,

<dependency>
    <groupId>be.c4j.ee.security.octopus</groupId>
    <artifactId>octopus-javaee7-jsf</artifactId>
    <version>${octopus.version}</version>
</dependency>

they can be found in the Bintray repository

<repository>
    <id>Bintray_JCenter</id>
    <url>https://jcenter.bintray.com</url>
</repository>

These are the other dependencies which we need

  • Java EE 7 (Provided) all the features of the Java EE 7 platform
  • PrimeFaces (Compile) The JSF Component library
  • Deltaspike (Compile/Runtime) Required dependency of Octopus but set as provided within Octopus so it is easier to specify the version you want to use within your application
  • Soteria (Compile) JSR-375 implementation and required since we are using a Java EE 7 server.
  • H2 database (Runtime) Our database where we want to store hashed passwords.

Security config

In this example, I want to show you the usage of a JSR-375 defined IdentityStore and a custom one.

The default defined IdentityStore is the Database one which stores the passwords hashed. It can be configured by putting an annotation on a CDI bean.

@DatabaseIdentityStoreDefinition(
        dataSourceLookup = "java:global/MyDS",
        callerQuery = "select password from caller where name = ?",
        groupsQuery = "select group_name from caller_groups where caller_name = ?",
        hashAlgorithmParameters = {
                "Pbkdf2PasswordHash.Iterations=3072",
                "Pbkdf2PasswordHash.Algorithm=PBKDF2WithHmacSHA512",
                "Pbkdf2PasswordHash.SaltSizeBytes=64"

        }
)

The datasource is defined within the DatabaseSetup class, which ensures the correct tables are created and filled with a few credentials.

This @DatabaseIdentityStoreDefinition is placed in our demo on the CDI bean which defines the second IdentityStore which is consulted when the database store didn’t contain the username we specified.

This custom store is created by implementing the interface javax.security.enterprise.identitystore.IdentityStore and override the validate() method.

Here we check if it is a certain fixed user and if the correct password is supplied. If so, it returns a few groups. Of course, you can write any kind of logic in these custom stores when the default ones don’t fit your needs.

Authorization

JSR-375 and Java EE in general, expect that each user has some groups defined in the external system which are then converted in roles of your application.

Octopus can also work with roles but one should use permissions because they are far more powerful. It has very powerful permission support like named, wildcard and domain permissions.

The groups of the user are interpreted as follows:
– The group is converted to a role with the same name (for the case you want to work with roles within Octopus)
– The group is converted to a named permission.
– The group is converted to a set of permissions by a CDI bean implementing the RolePermissionResolver which needs to be supplied by the developer.

This last option is probably the best and most powerful way to convert a group to a set of permissions and thus getting the maximum out of the features of Octopus.

No full integration

The described solution here is to integrate the IdentityStores of Java EE 8 (JSR-375) into the Octopus framework. It does not use the JASPIC as the underlying mechanism as JSR-375 describes, nor is there any integration with the other security features of Java EE like @RolesAllowed.

Java EE 8

And your application, like the demo, will be ready to convert to Java EE 8 with a minimal amount of effort. The only thing you need to do is take the Java EE 8 dependency (instead of the Java EE 7 one) and remove the Soteria dependency.

There will be no other changes required to make your application run on Java EE 8 and make use of all the features in that latest release.

Conclusion

With the Octopus framework, you have today already the most powerful authorization features available. And by using you are preparing yourself for the future when Java EE also has the authorization features available which are planned within the Java EE Security API.

Have fun.

Categories
Security

Release of JSR-375 extension for JWT based authentication/authorization with JAX-RS

Introduction

Since the release of Java EE Security API (JSR-375) specification, there is an easy, uniform API to define authentication and to some extend authorization.

With this specification inplace, there will be no need anymore to change Application server specific configuration files within any Java EE 8 compliant server.

Another good thing is that Soteria, the RI of this JSR-375 specification can also be used on most of the Java EE 7 servers.

The downside is that only the ‘classic’ mechanisms using Basic, Digest and Form authentication using LDAP or Database based validation is standardized.
The reasons for this were time (specification was under time pressure since it needed to be included in Java EE 8) and usage of external libraries (and license issues)

The usage of tokens is not standardized but can be created since the API is already available within the specification.

JWT based extension

The above observations lead me to create such an extension which is able to retrieve a JWT from the header within a JAX-RS call and authenticate/authorize the ‘remote user’ using the JSR-375 defined APIs.

If you want to skip the (longer) explanation in this blog entry, you can go straight to the GitHub repository with the compact instructions to get started.

When you are not familiar with JSON Web Tokens (JWT), have a look at the site jwt.io which explains it to you very nicely.

Since the JWT specification only defines the ‘structure’, as a developer, you are free to specify the content of the JWT Payload.

This variability leads to the following implemented flow:

– Extension is responsible for retrieving the token defined with the authorization header (through a custom HttpAuthenticationMechanism)
– Control is handed over to a JWTTokenHandler which needs to be implemented by the developer to verify if the JWT is valid (signature, timings, … check) and extract authentication and authorization information.
– This information is communicated to the low-level layers of the security API so that ‘request’ is now considered as authenticated and that roles can be verified.

JWT payload structure

The JWT token is expected as part of the authorization header with the bearer marker as in the following example:

Authorization:Bearer eyJraWQiOiI3NGYyNDYxOS1kNzIwLTQ1YWQtOTk2Yy0zNWNkNzNiNDdmZmQiLCJ0eXAiOiJKV1QiLCJhbGciOiJSUzUxMiJ9.eyJzdWIiOiJTb3RlcmlhIFJJIiwicmVhbG1fYWNjZXNzIjp7InJvbGVzIjpbInVzZXIiLCJtYW5hZ2VyIl19LCJleHAiOjE1MTAzNDgxMTMsImlhdCI6MTUxMDM0ODA4M30.Bk37fPLgymuLZfLq_hdxt94PDRwNAkPkoajegaLLMrsuCCeKEb5DRXcpT9kUyrwEzSFamg_19Y7IT-0utDw4yd_rEzq7lIG8UFc8qnoYi9692Es_sqzwu64x0dM1ODOAHYEPFhIXPo2-nxquYyayMJI5PN4WlTPrRgoFCkY6saxJGzAGlfQIqH3ozaMvEJn1GK3uj1_zglv2HHK1t8lliazRkmRI-p1k9A_HCnnpChb9czpUP_wXRN4HxbADldS5sM7lgsFeLZDB4oewAh9sTXiseH7HnbPfmQKF18vb9Vejc9XzIGf0CrSOf6yVTyYDChYhI1eB5z6Wv33ofFgbPg

If you decode the payload from the above example (yes payload is unprotected but safe due to the signature) you have the following information:

{"sub":"Soteria RI",
"realm_access":{"roles":["user","manager"]},
"exp":1510348113,
"iat":1510348083
}

The sub claim defines the authentication information (who is it), the realm_access defines the groups/roles the ‘user’ has (what is he allowed) and exp and iat can be used to have a token which expires and thus replay attacks are excluded.

As I already mentioned, the payload structure is not defined by JWT, nor by Java EE Security API (as tokens are not tackled yet).

But another organization, Eclipse MicroProfile, also created their specification around authentication within micro-services. Have a look at this post which goes deeper into the subject.

So why not using their recommended claims as it will become probably the (defacto) standard.

The example in the GitHub repository implements such an MP JWT payload (also using RSA keys as mentioned within the specification).

Setup

Have a look at the readme  for all the details on how you can use the extension.

In short, this is all that you need to do

Add the dependency

You need to add the Maven dependency to include the code for the JWT extension for jsr375

<dependency>
   <groupId>be.atbash.ee.security.jsr375</groupId>
   <artifactId>soteria-jwt</artifactId>
   <version>0.9</version>
</dependency>

Implement the be.atbash.ee.security.soteria.jwt.JWTTokenHandler.

It is responsible for loading the RSA keys and verifying if the JWT is valid (Signing and time restriction for example)
The implementation is also responsible for retrieving the user name and the groups from the JWT payload and supply them to the system. They are used to construct the required principal and role info.

Conclusion

Usage of tokens, like JWT and OAuth2 tokens, is not included in the Java EE Security API specification for the moment. But the interfaces are already in place to extend to the system in any way you like. Those are used to create these extensions so that you can start using them already today, On Java EE 8 and Java EE 7!

Have fun.

Categories
Security

Session Hijacking protection with Octopus framework

Session Hijacking

What is Session Hijacking? Most Web applications store information of the user ( the classic example is the shopping basket) in the HTTP session. But also the basic user information. So, whenever someone else knows the ID of the session, he can impersonate the victim and act on behalf of him/her.

The following image shows the attack (image by A. Mitra)

Octopus protects

But there exist a few techniques to identify if such an attack is in progress for a certain session. And this technique is implemented within the Octopus framework (from v0.9.7 on)

You don’t have to do anything specific to activate this features, it is on by default.

When such an attack is detected, the attacker gets a blank page with the message that access was denied due to a Session Hijacking attack detection. But also the actual victim can be informed of the attempt to take over his/her session.

See the following short video to see the feature in action.

Youtube video

The code used to create the video is on GitHub.

Have a look at the parameter session.hijacking.level to configure the feature in case you have issues or want to deactivate it.

Conclusion

With the Session Hijacking protection, Octopus tries to make the applications as safe as possible. It is only one of the security features it has. You saw also in the video that the session ids are changed when the user logs on and logs off, just as OWASP recommends it.

Have fun.

Categories
Security

Release Octopus v0.9.7

Introduction

I’m happy to announce the latest version of the Java EE Security framework Octopus, version 0.9.7.

After more than a year of development and testing and 2 projects where the major new features are already used, we feel it is time to release a final version of the framework.

The theme of this release is Self-Contained Systems. (Only for Java EE 7+)

  • Octopus SSO server compatible with OpenIdConnect protocol.
  • Transfer authentication and permission information within the header of JAX-RS rest calls.
  • Support of String based permissions.

But there are other important new features like

  • Support for RBAC – Role Based Access Control.
  • Implementing OWASP recommendations about Session management.
  • Support for 2-step authentication with OTP (One-time password)
  • Possibility to create a more advanced (then a custom voter) security annotation.
  • Initial support for Java SE

Self-Contained System support

Octopus SSO Server

in this announcement, I want you to tell something more about the support for Self-Contained Systems (SCS).

You can see them as a variant of microServices, the important feature about an SCS is that it is responsible for the data of a certain domain (like products or orders) and that it contains all the business logic and UI to work with the data.

Interaction, preferable asynchronously, with other SCS goes through the UI of them since Web pages and REST endpoints are both considered as UI.

The image shows these basic features of an SCS.

For an excellent introduction, I can recommend the site http://scs-architecture.org/

With this latest release of Octopus, implementing security within an SCS architecture becomes quite easy.

With the Octopus SSO server, you can turn one of the SCS in charge of the security.Based on the OpenIdConnect protocol, another SCS (clients) can delegate the authentication process to the Octopus SSO server. An additional scope, ‘Octopus’ makes it possible that the permissions of the authenticated user are transferred to the client.

Based on the OpenIdConnect protocol, another SCS (clients) can delegate the authentication process to the Octopus SSO server. An additional scope, ‘Octopus’ makes it possible that the permissions of the authenticated user are transferred to the client.

The image below gives an idea how it works (Authorisation grant flow)

The maven artefacts that one can use for this feature are
be.c4j.ee.security.octopus.sso:octopus-server and be.c4j.ee.security.octopus.sso:octopus-client

Because permissions need to be transferred from one SCS to another, it becomes easier if these permissions are just Strings. Although a more type-safe approach like enum values, here String are more pragmatic. (example further in text)

JAX-RS communication between SCS

Also, the communication with a JAX-RS endpoint can easily be secured with the SCS user modules.

The idea is that the information of the currently authenticated user is packed within a JWT and send in the header of the REST call. The server endpoint uses this info from the header, to recreate the principal and his permissions.

The normal Octopus security annotations, like @RequiredUser or @OctopusPermissions(“order:read:*”) can be used on the server side (containing the JAX-RS endpoint)
When the calling user doesn’t have the permission “order:read:*”, automatically a status 403 is returned.

On the server side, you can have something like this

@Path("/user")
public class UserController {

   @GET
   @OctopusPermissions("User:Read:*")
   public List<User> retrieveAllUsers() {
      ...
   }
}

The client side, for calling this endpoint can look like this

public class UserControl {

   @Inject
   private OctopusSCSUserRestClient restClient;

   public List<User> loadAllUsers() {
      regturn restClient.get(hostURL + "user", User[].class);
   }
}

Be aware that direct calling one SCS from another results in a tight coupling which is not suited in most situations.

The maven artifacts that one can use for this feature are be.c4j.ee.security.octopus.authentication:jwtscs-server and be.c4j.ee.security.octopus.authentication:jwtscs-client

Documentation

The user manual can be found here and example programs are created and will be available soon on GitHub.

More examples and better documentation can be expected when I migrate the Octopus framework into the Atbash organization of Github in the coming months.

Compatibility

The last section about compatibility with the current application servers. Some of the new features in this release of Octopus are only working on Java EE 7+.

Some of the new features in this release of Octopus are only working on Java EE 7+.
But in general Octopus framework can be used on any Java EE 6, Java EE 7 or Java EE 8 compliant server.

Yes, Octopus is tested with GlassFish 5 server and no issues are found. Just use the Java EE 7 version artifacts of Octopus and they will work just fine.

Later on, there will be Java EE 8 specific artifacts which use the JSONB api instead on the net.minidev:json-smart artefact.

 

This website uses cookies. By continuing to use this site, you accept our use of cookies.  Learn more