Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8768137
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T16:59:44+00:00 2026-06-13T16:59:44+00:00

Java Security is my main topic for the last couple of weeks and I

  • 0

Java Security is my main topic for the last couple of weeks and I archive the following:

  • Custom Valve Authentificator (extends AuthenticatorBase)
  • Custom Login Module for jBoss (extends UsernamePasswordLoginModule)
  • Secured Endpoint (JAX-RS)

My major problem is, that my endpoint works only with the annotation @DeclareRoles, if I don’t use it I cant get through authentication. In detail the method AuthenticatorBase.invoke (from org.apache.catalina.authenticator) calls the method RealmBase.hasResourcePermission and there the roles will be checked.

Since I don’t use any predefined roles the check will fail.

My question: Is there any way to use code like that:

@Path("/secure")
@Stateless
public class SecuredRestEndpoint {  

    @Resource
    SessionContext ctx;

    @GET
    public Response performLogging() {

        // Receive user information
        Principal callerPrincipal = ctx.getCallerPrincipal();
        String userId = callerPrincipal.getName();

        if (ctx.isCallerInRole("ADMIN")) {
            // return 200 if ok
            return Response.status(Status.OK).entity(userId).build();
        }
    ...
    }
}

Some additional background: There is the requirement to use a reverse proxy for authentication just the username gets forwarded (X-FORWARD-USER). Thats why I use my own Authenticator class and the custom Login module (I dont have any password credentials). But I think the problem also occurs with standard authentication methods from application server itself

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T16:59:45+00:00Added an answer on June 13, 2026 at 4:59 pm

    Since your code is static (meaning you have a static set of resources that can be secured), I do not understand your requirement for adding security roles aside from increasing access granularity. I could see this requirement in a modular environment, where the code is not static, in which case you would need to support the additional security roles declared by later deployments.

    That said, I had to implement something similar, a security system that supports:

    • adding (declaring) / removing roles without redeployment;
    • associating users to those roles.

    I’ll describe on a high level of abstraction what I did and hopefully it will give you some useful ideas.

    First off, implement an @EJB, something like this:

    @Singleton
    @LocalBean
    public class MySecurityDataManager {
    
        public void declareRole(String roleName) {
            ...
        }
    
        public void removeRole(String roleName) {
            ...
        }
    
        /**
         * Here, I do not know what your incoming user data looks like such as:
         * do they have groups, attributes? In my case I could determine user's groups
         * and then assign them to roles based on those. You may have some sort of
         * other attribute or just plain username to security role association.
         */
        public void associate(Object userAttribute, String roleName) {
            ...
        }
    
        public void disassociate(Object userAttribute, String roleName) {
            ...
        }
    
        /**
         * Here basically you inspect whatever persistence method you chose and examine
         * your existing associations to build a set of assigned security roles for a
         * user based on the given attribute(s).
         */
        public Set<String> determineSecurityRoles(Object userAttribute) {
            ...
        }
    }
    

    Then you implement a custom javax.security.auth.spi.LoginModule. I’d recommend implementing it from scratch, unless you know the container provided abstract implementation will work for you, it didn’t for me. Also, I suggest you get familiar with the following, if you aren’t, to better understand what I’m getting to:

    • http://docs.jboss.org/jbossas/docs/Server_Configuration_Guide/4/html/Defining_Security_Domains-Writing_Custom_Login_Modules.html
    • http://docs.oracle.com/javase/7/docs/api/javax/security/auth/spi/LoginModule.html
    • http://docs.oracle.com/javase/7/docs/api/java/security/acl/Group.html

    public class MyLoginModule implements LoginModule {
    
        private MySecurityDataManager srm;
    
        @Override
        public void initialize(Subject subject, CallbackHandler callbackHandler,
                Map<String, ?> sharedState, Map<String, ?> options) {
            // make sure to save subject, callbackHandler, etc.
            try {
                InitialContext ctx = new InitialContext();
                this.srm = (MySecurityDataManager) ctx.lookup("java:global/${your specific module names go here}/MySecurityDataManager");
            } catch (NamingException e) {
                // error logic
            }
        }
    
        @Override
        public boolean login() throws LoginException {
            // authenticate your user, see links above
        }
    
        @Override
        public boolean commit() throws LoginException {
            // here is where user roles get assigned to the subject
            Object userAttribute = yourLogicMethod();
            Set<String> roles = srm.determineSecurityRoles(userAttribute);
            // implement this, it's easy, just make sure to include proper equals() and hashCode(), or just use the Jboss provided implementation.
            Group rolesGroup = new SimpleGroup("Roles", roles);
            // assuming you saved the subject
            this.subject.getPrincipals().add(rolesGroup);
        }
    
        @Override
        public boolean abort() throws LoginException {
            // see links above
        }
    
        @Override
        public boolean logout() throws LoginException {
            // see links above
        }
    
    }
    

    In order to allow dynamic configuration (i.e. declaring roles, associating users), build a UI that uses that same @EJB MySecurityDataManager to CRUD your security settings that the login module will use to determine security roles.

    Now, you can package these the way you want, just make sure that the MyLoginModule can look up the MySecurityDataManager and that you deploy them to the container. I worked on JBoss, and you mentioned JBoss, so this should work for you as well. A more robust implementation would include the lookup string in the LoginModule’s configuration, which you then can read at runtime from the options map in the initialize() method. Here’s an example configuration for JBoss:

    <security-domain name="mydomain" cache-type="default">
        <authentication>
            <login-module flag="required"
                          code="my.package.MyLoginModule"
                          module="deployment.${your deployment specific info goes here}">
                <module-option name="my.package.MySecurityDataManager"
                               value="java:global/${your deployment specific info goes here}/MySecurityDataManager"/>
            </login-module>
        </authentication>
    </security-domain>
    

    At this point you can use this security domain mydomain to manage the security of any other deployments in the container.

    Here are a couple usage scenarios:

    1. Deploy a new .war and assign it to the mydomain security domain. The .war comes with predefined security annotations throughout its code. Your security realm doesn’t have them initially, so no user can log in. But after deployment, since the security roles are well documented, you open the mydomains configuration interface you wrote and declare those roles, then assign users to them. Now they can log in.
    2. After a few months of deployment, you no longer want users to have access to specific par of the war. Remove the security roles pertinent to that portion of the .war from your mydomain and no one will be able to use it.

    The best part, especially about #2 is no redeployment. Also, no editing XML to override the default security settings declared with annotations (That is assuming your interface is better than that).

    Cheers!
    I’ll be happy to provide more specifics, but for now, this should at least tell you if you would need them.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I need to make a java program with a security and a login system
I'm getting the following error message : Exception in thread main java.lang.NoClassDefFoundError: LU62XnsCvr (wrong
I use the following code to test the BouncyCastle crypto library: import java.security.Security; public
When I run the java program it gives following error: Exception in thread main
I got the following code: import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class Sha1{ private static
I have the following Exception: Exception in thread main java.lang.SecurityException: no manifiest section for
I run the following command: C:\Projects\java -cp ./dependency.jar -jar ./dist/main.jar Exception in thread main
I am learning Java Security JCE/JAAS. I am not able to get a example
How does one create a java.security.cert.X509Certificate instance from a PEM-formatted String? The PEM-formatted String
How to get back from encoded byte[] to java.security.Key? import java.security.Key; import javax.crypto.SecretKey; import

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.