It depends on how your authentication mechanism looks like.
Java EE Security
If you are relying on the standard Java EE Web application security mechanisms offered by the servlet container, the authentication can be configured via the application's web.xml
descriptor. It's very likely you will need to define a realm in your container and reference it in your web.xml
descriptor with the <real-name>
element. Something like:
<security-constraint>
<web-resource-collection>
<url-pattern>/rest/admin/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>admin</role-name>
</auth-constraint>
</security-constraint>
<security-constraint>
<web-resource-collection>
<url-pattern>/rest/orders/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>customer</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>my-default-realm</realm-name>
</login-config>
In this approach, your realm will tell the container whether a user is in a role or not.
To learn more about Java EE Security, have a look at the Java EE Tutorial.
Custom authentication
On the other hand, when you are performing a custom authentication like the one described in this answer, you could use a custom implementation of SecurityContext
. In this situation, you need to authenticate the user manually against your LDAP, database, file, etc.
For a custom authetication, you could use a ContainerRequestFilter
like the one show below:
@Provider
@Priority(Priorities.AUTHENTICATION)
public class AuthenticationFilter implements ContainerRequestFilter {
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
// Authenticate the user: How the authentications will be performed is up to you
// If the authentication failed, abort the request with a 401 status code
// If the authentication succeeded, you know who your user claims to be
final SecurityContext securityContext = requestContext.getSecurityContext();
requestContext.setSecurityContext(new SecurityContext() {
@Override
public Principal getUserPrincipal() {
return new Principal() {
@Override
public String getName() {
// Return the user name here
return null;
}
};
}
@Override
public boolean isUserInRole(String role) {
// Return if the user is in a role
return true;
}
@Override
public boolean isSecure() {
return securityContext.isSecure();
}
@Override
public String getAuthenticationScheme() {
return "Custom";
}
});
}
}
How the authentication will be performed is your business. The recommended approach for HTTP authetication is to send the credentials in the Authorization
header of the request. The ContainerRequestContext
API will give you access to details of the request.
In this approach, you need to write the code to determine whether a user is in a role or not.
Note: Mind that you won't rely on sessions. The authentication/authorization process must be performed for each request.