Howto secure webservices on GlassFish 2?

2019-01-19 08:59发布

问题:

We have some staleless EJBs (EJB3) deployed on a GlassFish 2 server that expose some of their methods as webservices via the @Webmethod annotation.

Now we want to secure these webservice methods so that only authenticated clients can call it. What would be a good way to achieve this?

回答1:

Like the good reverend said. Example below uses a file realm for authentication.

@Stateless
@WebService(name = "MyAppServices")
@RolesAllowed({"user"})
public class ItemEJB {
    ...
}

You will also need sun-ejb-jar.xml e.g.

<sun-ejb-jar>
<security-role-mapping>
            <!-- as defined in @RolesAllowed -->
    <role-name>user</role-name>
            <!-- glassfish group created in file realm -->
    <group-name>user</group-name>
</security-role-mapping>
<enterprise-beans>
    <ejb>
        <ejb-name>ItemEJB</ejb-name>
        <webservice-endpoint>
            <!-- equivalent to name attribute of @WebService -->
            <port-component-name>MyAppServices</port-component-name>
            <login-config>
                <auth-method>BASIC</auth-method>
                <realm>file</realm>
            </login-config>
        </webservice-endpoint>
    </ejb>
</enterprise-beans>

Creation of a group in the file realm in glassfish is trivial (admin console). you can however create your own custom realm and login module



回答2:

You can authorize a list of roles to access a method or an entire bean using security annotations:

E.g.

@Stateless
@RolesAllowed({"user", "employee", "admin"})
public class ItemEJB {
    ...
}

See the link below for more information:

http://java.sun.com/developer/technicalArticles/J2EE/security_annotation/



回答3:

Now we want to secure these webservice methods so that only authenticated clients can call it.

I assume that this is not related to ssl. So:
1) The client logs-in giving username and password
2) If username and password are correct (stored in DB) then the user is considered as logged-in and in the reply a unique session token (somehow related to username and password) is generated by the web service and is send back in the reply.
This token is stored along with timestamp info and username and password.
3) Each time a request is send by the client, the token is send back along with the other parameters. If the token is valid then this means that the request comes from an authenticated client.
4) All requests should be expected to have the session token with the rest of parameters.
So an unathenticated client, will have no token to send.