0

I am registering a Servlet in an OSGi bundle using the HttpService. I have created my own HttpContext class which handles the security - BasicAuthentication and check against ActiveDirectory.

Dictionary<String, String> params = new Hashtable<String, String>();
params.put("jersey.config.server.provider.classnames", SettingsService.class.getName());
HttpContext ctx = new HttpContext()
{
    @Override
    public boolean handleSecurity(HttpServletRequest request, HttpServletResponse response) throws IOException
    {
        // validation against Active Directory here
        return ADAuth.authenticate(request, response);
    }

    @Override
    public URL getResource(String name)
    {
        return null;
    }

    @Override
    public String getMimeType(String name)
    {
        return null;
    }
};
httpService.registerServlet("/rest", new MyServlet(), params, ctx); //$NON-NLS-1$

httpService.registerResources("/web", "/web", null);

So far so good. I would now like to set roles for the logged-in used so that I can use the @RolesAllowed annotation. The roles will depend on Active Directory groups.

How do I set the roles? I have tried setting roles using

HttpSession session = request.getSession(true);
    Subject subject = (Subject) session.getAttribute("javax.security.auth.subject");

    if (subject == null) {
        subject = new Subject();
        subject.getPrincipals().add(new PlainRolePrincipal(groupName));
        session.setAttribute("javax.security.auth.subject", subject);
    }

but request.isUserInRole always returns false.

Update

When I step into request.isUserInRole I eventually get to this code:

if (_authentication instanceof Authentication.Deferred)
    setAuthentication(((Authentication.Deferred)_authentication).authenticate(this));

if (_authentication instanceof Authentication.User)
    return ((Authentication.User)_authentication).isUserInRole(_scope,role);
return false;

The _authentication value is null. When / where should this be set?

paul
  • 13,312
  • 23
  • 81
  • 144

1 Answers1

0

You only created a new Subject instance. This does not automatically update the one in the session.

Apart from that the problem in jaas is always that there is not standard for role principals. You chose to encode the Role as PlainRolePrincipal. I am not sure this is what request is checking for. You will have to look into that code to see how it determines if a principal is a role principal or not.

A typical case is that it checks for a certain class or interface name but I am not sure which in your case.

Christian Schneider
  • 19,420
  • 2
  • 39
  • 64
  • Thanks. Good catch. Unfortunately I just hadn't copied my code completely into the question. The problem still remains. – paul Mar 23 '16 at 05:59