Robin Wieruch
Robin Wieruch

Reputation: 15908

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

Upvotes: 0

Views: 3447

Answers (1)

Martin Matula
Martin Matula

Reputation: 7989

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>

Upvotes: 2

Related Questions