JAX-RS authentication and authorization

This page describes how to configure a (JAX-RS application) using (custom login modules) and (authorization based annotation) on JBoss 7.

  1. JAX-RS is a language API that provides support in creating web services according to the REST architectural pattern in Java.
  2. Custom login module will act like an adapter to allow you to integrate with your authentication and authorization API’s. This will allow your applications to use existing roles defined in your organization.
  3. Authorization based annotations like (@RolesAllowed, @DenyAll, @PermitAll, and @RunAs) make it easy to specify permissions at resource level. These permissions allows developers to specify who is allowed to interact with the REST resource. This can be done at the individual method level so you can restrict HTTP methods like @GET, @PUT, @DELETE etc… to only users allowed to perform those operations.
Full downloadable source for this page is available here. Corrections and enhancements are welcome, fork, change and push back to GitHub.

Software Stack

  • Java 8
  • Jboss EAP 6.4 – should work other Jboss servers as well
  • JAVA EE 6 / JAX-RS 1.1


Most of the configuration will be done inside the WAR file however there is ONE THING that needs to be configured on the server. A new security domain needs to be defined for the custom login module. There is no way around this. This must be done.

[JBOSS BASE DIR]/standalone/configuration/standalone.xml

find the security-domains section and add the following domain.

<security-domain name="custom-auth" cache-type="default">
    <login-module code="com.test.MySimpleUsernamePasswordLoginModule" flag="required"/>

Login Module

The following is the custom login module. This is just one example on how to extend UsernamePasswordLoginModule. Other base classes are available to extend (AnonLoginModule, DatabaseServerLoginModule, LdapExtLoginModule, LdapLoginModule, SimpleServerLoginModule, UsersLoginModule, UsersRolesLoginModule, XMLLoginModule). See the JBoss documentation.


package com.test;

import java.security.acl.Group;
import java.util.Map;

import javax.security.auth.Subject;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.login.LoginException;

import org.jboss.security.SimpleGroup;
import org.jboss.security.SimplePrincipal;
import org.jboss.security.auth.spi.UsernamePasswordLoginModule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

 * The simples username and password based login module possible,
 * extending JBoss' {@link UsernamePasswordLoginModule}.
public class MySimpleUsernamePasswordLoginModule extends UsernamePasswordLoginModule {
	private static final Logger logger = LoggerFactory.getLogger(MySimpleUsernamePasswordLoginModule.class);

    public void initialize(Subject subject, CallbackHandler callbackHandler,
            Map sharedState,
            Map options) {
        super.initialize(subject, callbackHandler, sharedState, options);

     * (required) The UsernamePasswordLoginModule modules compares the result of this
     * method with the actual password.
    protected String getUsersPassword() throws LoginException {
        System.out.format("MyLoginModule: authenticating user '%s'\n", getUsername());
        // Lets pretend we got the password from somewhere and that it's, by a chance, same as the username
        String password = super.getUsername();
        // Let's also pretend that we haven't got it in plain text but encrypted
        // (the encryption being very simple, namely capitalization)
        password = password.toUpperCase();
        return password;

     * (optional) Override if you want to change how the password are compared or
     * if you need to perform some conversion on them.
    protected boolean validatePassword(String inputPassword, String expectedPassword) {
        // Let's encrypt the password typed by the user in the same way as the stored password
        // so that they can be compared for equality.
        String encryptedInputPassword = (inputPassword == null)? null : inputPassword.toUpperCase();
        System.out.format("Validating that (encrypted) input psw '%s' equals to (encrypted) '%s'\n"
                , encryptedInputPassword, expectedPassword);
        return super.validatePassword(encryptedInputPassword, expectedPassword);

     * (required) The groups of the user, there must be at least one group called
     * "Roles" (though it likely can be empty) containing the roles the user has.
    protected Group[] getRoleSets() throws LoginException {
    	String user = getIdentity().getName();
    	logger.info("getting roles for user: " + user);
        SimpleGroup group = new SimpleGroup("Roles");
        try {
            group.addMember(new SimplePrincipal("user_role"));
            	group.addMember(new SimplePrincipal("admin_role"));
        } catch (Exception e) {
            throw new LoginException("Failed to create group member for " + group);
        return new Group[] { group };


REST Resource

Each method is annotated with the roles that are allowed to execute it.


package com.test;

import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.security.RolesAllowed;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.SecurityContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CompanyResource {
	private static final Logger logger = LoggerFactory.getLogger(CompanyResource.class);

	public void postConstruct() {
	@RolesAllowed({"user_role", "admin_role"})
	public Object getCompany(@PathParam("id")  Long id) {
		logger.info("getCompany called");
		return null;

	public Object create() {
		logger.info("create called");
		return null;
	public List<Object> getAll(@Context SecurityContext sec) {
		logger.info("getAll called");		
		// the following is just a demo of a programmatic security check.
		logger.info("Id: " + sec.getUserPrincipal().getName());
		String role = "user_role";
		logger.info("User is in role "+role+" : " + sec.isUserInRole(role));
		role = "admin_role";
		logger.info("User is in role "+role+" : " + sec.isUserInRole(role));
		return null;

	public Object update(Object selectedCompany) {
		logger.info("update called");
		return null;

	public void delete(@PathParam("id")  Long id) {
		logger.info("delete called");


REST Application Config


package com.test;

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

public class WarehouseApplication extends Application {}

Configuration files


<!DOCTYPE log4j:configuration PUBLIC
  "-//APACHE//DTD LOG4J 1.2//EN" "http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/xml/doc-files/log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
	<appender name="file" class="org.apache.log4j.FileAppender">
	   <param name="maxFileSize" value="1024KB" />
	   <param name="file" value="${user.home}/logs/jboss-custom-login.log" />
	   <layout class="org.apache.log4j.PatternLayout">
		<param name="ConversionPattern" 
			value="%d %-5p %c:%L - %m%n" />
    <logger name="com.test">
        <level value="DEBUG"/>
    <logger name="com.springframework">
        <level value="INFO"/>
    <logger name="org.hibernate.SQL">
        <level value="DEBUG"/>
        <level value="ERROR"/>
        <appender-ref ref="file"/>


<?xml version="1.0" encoding="UTF-8"?>


<?xml version="1.0" encoding="UTF-8"?>
<web-app 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"
	id="WebApp_ID" version="3.0">

	<!-- The following is required to get JBOSS JAX-RS to detect and use @RolesAllowed -->	

	<security-constraint> <!-- TODO: try to specify all this via annotations.  -->
			<web-resource-name>JBoss Application</web-resource-name>
		<auth-constraint> <!-- list of roles allowed to use web application -->

	<!-- Define the Login Configuration for this Application -->
		<realm-name>JBoss Application</realm-name>

	<!-- Security roles referenced by this web application -->
		<description>The role a user needs to be allowed to log in to the application</description>
		<description>Admin Role</description>



<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <name>jboss-custom-login Maven Webapp</name>
		<pluginRepository> <!-- Ignore this repository. Its only used for document publication. -->

			<plugin> <!-- Ignore this plugin. Its only used for document publication. -->

Test the application

Install the application into JBoss and navigate to the application using a browser testing tool such as Postman:

url: http://localhost:8080/jboss-custom-login/services/companies

The application uses BASIC auth so you may specify the following ids to login:

user/user – can only use read-only methods like [getAll, getCompany]
admin/admin – can use any method

Check the log4j.xml config file to see where the logs are being written.


Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 77 other followers

March 2016
« Feb   Mar »

Blog Stats

  • 842,358 hits

%d bloggers like this: