I have an Spring + CXF application which consumes a Transmission API: Transmission RPC running in another server.
According to Transmission docs, you need to send a token which is generated on the first request. The server then responds with a 409 http code along with a header containing the token. This token should be sent on all subsequent calls:
2.3.1. CSRF Protection Most Transmission RPC servers require a X-Transmission-Session-Id header to be sent with requests, to prevent
CSRF attacks. When your request has the wrong id -- such as when you
send your first request, or when the server expires the CSRF token --
the Transmission RPC server will return an HTTP 409 error with the
right X-Transmission-Session-Id in its own headers. So, the correct
way to handle a 409 response is to update your
X-Transmission-Session-Id and to resend the previous request.
I was looking for solution either using a CXF filter or interceptor, that basically will handle the 409 response and retry the initial request adding the token header. I'm thinking that clients can persist this token and send it in future calls.
I'm not very familiar with cxf so I was wondering if this can be accomplish and how. Any hint would be helpful.
Thanks!
Here spring-retry can be utilized which is now an independent project and no longer part of spring-batch.
As explained here retry callback will help make another call updated with the token header.
Pseudo code / logic in this case would look something like below
RetryTemplate template = new RetryTemplate();
Foo foo = template.execute(new RetryCallback<Foo>() {
public Foo doWithRetry(RetryContext context) {
/*
* 1. Check if RetryContext contains the token via hasAttribute. If available set the header else proceed
* 2. Call the transmission API
* 3.a. If API responds with 409, read the token
* 3.a.1. Store the token in RetryContext via setAttribute method
* 3.a.2. Throw a custom exception so that retry kicks in
* 3.b. If API response is non 409 handle according to business logic
* 4. Return result
*/
}
});
Make sure to configure the RetryTemplate with reasonable retry & backoff policies so as to avoid any resource contention / surprises.
Let know in comments in case of any queries / roadblock.
N.B.: RetryContext's implementation RetryContextSupport has the hasAttribute & setAttribute method inherited from Spring core AttributeAccessor
Assuming you are using Apache CXF JAX RS Client it is easy to do by just creating a custom Runtime Exception and ResponseExceptionMapper for it. So the idea is to manually convert 409 outcomes to some exception and then handle them correctly (in your case retry the service call).
See following code snipped for fully working example.
#SpringBootApplication
#EnableJaxRsProxyClient
public class SpringBootClientApplication {
// This can e stored somewhere in db or elsewhere
private static String lastToken = "";
public static void main(String[] args) {
SpringApplication.run(SpringBootClientApplication.class, args);
}
#Bean
CommandLineRunner initWebClientRunner(final TransmissionService service) {
return new CommandLineRunner() {
#Override
public void run(String... runArgs) throws Exception {
try {
System.out.println(service.sayHello(1, lastToken));
// catch the TokenExpiredException get the new token and retry
} catch (TokenExpiredException ex) {
lastToken = ex.getNewToken();
System.out.println(service.sayHello(1, lastToken));
}
}
};
}
public static class TokenExpiredException extends RuntimeException {
private String newToken;
public TokenExpiredException(String token) {
newToken = token;
}
public String getNewToken() {
return newToken;
}
}
/**
* This is where the magic is done !!!!
*/
#Provider
public static class TokenExpiredExceptionMapper implements ResponseExceptionMapper<TokenExpiredException> {
#Override
public TokenExpiredException fromResponse(Response r) {
if (r.getStatus() == 409) {
return new TokenExpiredException(r.getHeaderString("X-Transmission-Session-Id"));
}
return null;
}
}
#Path("/post")
public interface TransmissionService {
#GET
#Path("/{a}")
#Produces(MediaType.APPLICATION_JSON_VALUE)
String sayHello(#PathParam("a") Integer a, #HeaderParam("X-Transmission-Session-Id") String sessionId)
throws TokenExpiredException;
}
}
I'm using a very simple httpServer in Java for an api rest with GET, POST, PUT and DELETE. I'm using Basic Authentication and I have a couple classes Authentication.java and Authorisation.java which I use to authenticate and check permissions for the users.
So, the thing is that I want all users (authenticated) to be able to GET information from my api rest, but only users with certain privileges to be able to POST, PUT and DELETE. So how can I do that?
This is what I got
public class Server {
private static HttpServer server;
public static void start() throws IOException {
server = HttpServer.create(new InetSocketAddress(8000), 0);
HttpContext ctx = server.createContext("/users", new UserHandler());
ctx.setAuthenticator(new ApiRestBasicAuthentication("users"));
server.start();
}
}
And this is my ApiRestBasicAuthentication
public class ApiRestBasicAuthentication extends BasicAuthenticator {
private UserAuthentication authentication = new UserAuthentication();
public ApiRestBasicAuthentication(String realm) {
super(realm);
}
#Override
public boolean checkCredentials(String user, String pwd) {
int authCode = authentication.authenticate(user, pwd);
return authCode == UserAuthentication.USER_AUTHENTICATED;
}
}
As this is now, check credentials is only checking if the user is authenticated.
But I'd like to check, if the method is POST, DELETE or PUT I should also check the specific credentials. But how can I get the method in my ApiRestBasicAuthentication? I'm doing that in my handler class
public void handle(HttpExchange httpExchange) throws IOException {
String method = httpExchange.getRequestMethod();
if ("post".equalsIgnoreCase(method)) {
createUser(httpExchange);
} else if ("get".equalsIgnoreCase(method)) {
readUsers(httpExchange);
} else if ("put".equalsIgnoreCase(method)) {
updateUser(httpExchange);
} else if ("delete".equalsIgnoreCase(method)) {
deleteUser(httpExchange);
}
}
Maybe this is supposed to be done some other way.
Any ideas?
Many thanks.
A simple way to do it would be to change your
ApiRestBasicAuthentication like:
public class ApiRestBasicAuthentication extends BasicAuthenticator {
private UserAuthentication authentication = new UserAuthentication();
public ApiRestBasicAuthentication(String realm) {
super(realm);
}
#Override
public Authenticator.Result authenticate(HttpExchange exch) {
Authenticator.Result result=super.authenticate(exch);
if(result instanceof Authenticator.Success) {
HttpPrincipal principal=((Authenticator.Success)result).getPrincipal();
String requestMethod=exch.getRequestMethod();
if( ADD SOME LOGIC HERE FOR PRINCIPAL AND REQUEST METHOD) {
return new return new Authenticator.Failure(401);
}
return result;
}
}
#Override
public boolean checkCredentials(String user, String pwd) {
int authCode = authentication.authenticate(user, pwd);
return authCode == UserAuthentication.USER_AUTHENTICATED;
}
}
And add some logic there for requests/users that you want to fail the authenticator. I have shown you here how to get the method in the authenticate method but you need to specify the types of credentials.
Another solution would be if you check the source code of BasicAuthenticator you can see how it implements authenticate method and you can create your own implementation in a similar way instead of extending BasicAuthenticator and use the get method instead of just the username and password. You can see the source code here and I am sure you will be able to find your way around ;)
Usually in enterprise application you can use some external security management system - for example if you use Spring (the de facto standard in the current java web apps) you can use spring security and do such security patterns and filters in a more declarative way
While the above answers might be valid for you, I think you should also consider using defined roles and security-constraints which can be defined in your web.xml and used in the REST Resource using #RolesAllowed annotation. This then allows you to specifically allow permissions for methods individually or at the REST resource/class level.
In web.xml, this looks something like this:-
<security-role>
<role-name>SERVERTOSERVER</role-name>
</security-role>
<security-constraint>
<web-resource-collection>
<web-resource-name>REST API description</web-resource-name>
<url-pattern>/<path name>/*</url-pattern>
<http-method>GET</http-method>
</web-resource-collection>
<auth-constraint>
<description>Only allow users
from following roles</description>
<role-name>SERVERTOSERVER</role-name>
</auth-constraint>
</security-constraint>
The following links have some examples: Purpose of roles tags in tomcat-users.xml? ,
https://www.thecoderscorner.com/team-blog/hosting-servers/17-setting-up-role-based-security-in-tomcat/
In case helpful, here is another type of solution for a Jersey based application: https://howtodoinjava.com/jersey/jersey-rest-security/
There might be many ways to solve this issue. Here is one of my proposal:
Create a User Object with fields that you want and one field called something like "role". Lets say only "admins" are allowed to do make Http requests other than "GET" while "regular" users can only do "GET". Many ways to do this but one way is to make the "role" field String and assign values to it using an ENUM, so that it's easy to change later and only specific terms are used. But you don't have to do that. Write get and set method for the fields you create and that you might need later, and definitely for role.
You need to make sure that class containing the handle(HttpExchange httpExchange) is able to see the currently logged in user, and refer to the User object associated with them. Then you need to modify the method so that
if(loggedInUser.getRole().equals("admin")){
//allow whatever method
} else {
// allow "GET" or give some denied permission error
}
Since other implementations have not been provided, I can't give a more detailed answer or be sure that this will work for you.
I think what you should create an AuthenticationInterceptor and by-pass GET the requests there and correspondingly apply authentication mechanism for rest non-GET requests.
public class AuthenticationInterceptor extends HandlerInterceptorAdapter {
#Autowired
private ApiRestBasicAuthentication apiRestBasicAuthentication;
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
switch (request.getMethod()) {
case "GET" :
// by-passing all GET requests
return true;
default :
return apiRestBasicAuthentication.checkCredentials(username, password);
}
}
}
I've created a self hosted Java applicataion and I would like to use Google sign in to log in into. I followed the follwong example:
https://developers.google.com/identity/sign-in/web/
That of course work, but now I'm getting a little confuse on how I can authorize the calls on the server. In the backend I'm using Grizzly+Jersey.
As described on the Google Sig-In documentation, you can use Google API Client Library for Java in order to check the authentication token on server side.
Client side
After a user successfully signs in, get the user's ID token:
function onSignIn(googleUser) {
var idToken = googleUser.getAuthResponse().id_token;
...
}
And send the idToken to the server in every request using the standard HTTP Authorization header.
Server side
You can use a filter to perform authentication and/or authorization.
To bind filters to your REST endpoints, JAX-RS provides the meta-annotation #NameBinding and can be used as following:
#NameBinding
#Retention(RUNTIME)
#Target({TYPE, METHOD})
public #interface Secured { }
The #Secured annotation will be used to decorate a filter class, which implements ContainerRequestFilter, allowing you to handle the request, get and validate the token.
The ContainerRequestContext helps you to extract information from the HTTP request.
The #Provider annotation marks an implementation of an extension interface that should be discoverable by JAX-RS/Jersey runtime during a provider scanning phase.
#Secured
#Provider
#Priority(Priorities.AUTHENTICATION)
public class AuthenticationFilter implements ContainerRequestFilter {
#Override
public void filter(ContainerRequestContext requestContext) throws IOException {
// Get the token header from the HTTP Authorization request header
String token =
requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);
// Check if the token is present
if (token == null || token.isEmpty()) {
throw new NotAuthorizedException("Token must be provided");
}
// Validate the token
validateToken(token);
}
private void validateToken(String token) {
GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier
.Builder(new NetHttpTransport(), new GsonFactory())
.setAudience(Arrays.asList(CLIENT_ID))
.build();
GoogleIdToken idToken = verifier.verify(token);
if (idToken != null) {
Payload payload = idToken.getPayload();
System.out.println("User ID: " + payload.getSubject());
} else {
throw new NotAuthorizedException("Invalid token.");
}
}
}
To bind the filter to your endpoints methods or classes, annotate them with the #Secured annotation created above. For the methods and/or classes which are annotated, the filter will be executed.
#Path("/example")
public class MyEndpoint {
#GET
#Path("{id}")
#Produces("application/json")
public Response myUnsecuredMethod(#PathParam("id") Long id) {
// This method is not annotated with #Secured
// The security filter won't be executed before invoking this method
...
}
#DELETE
#Secured
#Path("{id}")
#Produces("application/json")
public Response mySecuredMethod(#PathParam("id") Long id) {
// This method is annotated with #Secured
// The security filter will be executed before invoking this method
...
}
}
In the example above, the security filter will be executed only for mySecuredMethod(Long) because it's annotated with #Secured.
I'm looking for a way to enable token-based authentication in Jersey. I am trying not to use any particular framework. Is that possible?
My plan is: A user signs up for my web service, my web service generates a token, sends it to the client, and the client will retain it. Then the client, for each request, will send the token instead of username and password.
I was thinking of using a custom filter for each request and #PreAuthorize("hasRole('ROLE')"), but I just thought that this causes a lot of requests to the database to check if the token is valid.
Or not create filter and in each request put a param token? So that each API first checks the token and after executes something to retrieve resource.
How token-based authentication works
In token-based authentication, the client exchanges hard credentials (such as username and password) for a piece of data called token. For each request, instead of sending the hard credentials, the client will send the token to the server to perform authentication and then authorization.
In a few words, an authentication scheme based on tokens follow these steps:
The client sends their credentials (username and password) to the server.
The server authenticates the credentials and, if they are valid, generate a token for the user.
The server stores the previously generated token in some storage along with the user identifier and an expiration date.
The server sends the generated token to the client.
The client sends the token to the server in each request.
The server, in each request, extracts the token from the incoming request. With the token, the server looks up the user details to perform authentication.
If the token is valid, the server accepts the request.
If the token is invalid, the server refuses the request.
Once the authentication has been performed, the server performs authorization.
The server can provide an endpoint to refresh tokens.
What you can do with JAX-RS 2.0 (Jersey, RESTEasy and Apache CXF)
This solution uses only the JAX-RS 2.0 API, avoiding any vendor specific solution. So, it should work with JAX-RS 2.0 implementations, such as Jersey, RESTEasy and Apache CXF.
It is worthwhile to mention that if you are using token-based authentication, you are not relying on the standard Java EE web application security mechanisms offered by the servlet container and configurable via application's web.xml descriptor. It's a custom authentication.
Authenticating a user with their username and password and issuing a token
Create a JAX-RS resource method which receives and validates the credentials (username and password) and issue a token for the user:
#Path("/authentication")
public class AuthenticationEndpoint {
#POST
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response authenticateUser(#FormParam("username") String username,
#FormParam("password") String password) {
try {
// Authenticate the user using the credentials provided
authenticate(username, password);
// Issue a token for the user
String token = issueToken(username);
// Return the token on the response
return Response.ok(token).build();
} catch (Exception e) {
return Response.status(Response.Status.FORBIDDEN).build();
}
}
private void authenticate(String username, String password) throws Exception {
// Authenticate against a database, LDAP, file or whatever
// Throw an Exception if the credentials are invalid
}
private String issueToken(String username) {
// Issue a token (can be a random String persisted to a database or a JWT token)
// The issued token must be associated to a user
// Return the issued token
}
}
If any exceptions are thrown when validating the credentials, a response with the status 403 (Forbidden) will be returned.
If the credentials are successfully validated, a response with the status 200 (OK) will be returned and the issued token will be sent to the client in the response payload. The client must send the token to the server in every request.
When consuming application/x-www-form-urlencoded, the client must send the credentials in the following format in the request payload:
username=admin&password=123456
Instead of form params, it's possible to wrap the username and the password into a class:
public class Credentials implements Serializable {
private String username;
private String password;
// Getters and setters omitted
}
And then consume it as JSON:
#POST
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public Response authenticateUser(Credentials credentials) {
String username = credentials.getUsername();
String password = credentials.getPassword();
// Authenticate the user, issue a token and return a response
}
Using this approach, the client must to send the credentials in the following format in the payload of the request:
{
"username": "admin",
"password": "123456"
}
Extracting the token from the request and validating it
The client should send the token in the standard HTTP Authorization header of the request. For example:
Authorization: Bearer <token-goes-here>
The name of the standard HTTP header is unfortunate because it carries authentication information, not authorization. However, it's the standard HTTP header for sending credentials to the server.
JAX-RS provides #NameBinding, a meta-annotation used to create other annotations to bind filters and interceptors to resource classes and methods. Define a #Secured annotation as following:
#NameBinding
#Retention(RUNTIME)
#Target({TYPE, METHOD})
public #interface Secured { }
The above defined name-binding annotation will be used to decorate a filter class, which implements ContainerRequestFilter, allowing you to intercept the request before it be handled by a resource method. The ContainerRequestContext can be used to access the HTTP request headers and then extract the token:
#Secured
#Provider
#Priority(Priorities.AUTHENTICATION)
public class AuthenticationFilter implements ContainerRequestFilter {
private static final String REALM = "example";
private static final String AUTHENTICATION_SCHEME = "Bearer";
#Override
public void filter(ContainerRequestContext requestContext) throws IOException {
// Get the Authorization header from the request
String authorizationHeader =
requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);
// Validate the Authorization header
if (!isTokenBasedAuthentication(authorizationHeader)) {
abortWithUnauthorized(requestContext);
return;
}
// Extract the token from the Authorization header
String token = authorizationHeader
.substring(AUTHENTICATION_SCHEME.length()).trim();
try {
// Validate the token
validateToken(token);
} catch (Exception e) {
abortWithUnauthorized(requestContext);
}
}
private boolean isTokenBasedAuthentication(String authorizationHeader) {
// Check if the Authorization header is valid
// It must not be null and must be prefixed with "Bearer" plus a whitespace
// The authentication scheme comparison must be case-insensitive
return authorizationHeader != null && authorizationHeader.toLowerCase()
.startsWith(AUTHENTICATION_SCHEME.toLowerCase() + " ");
}
private void abortWithUnauthorized(ContainerRequestContext requestContext) {
// Abort the filter chain with a 401 status code response
// The WWW-Authenticate header is sent along with the response
requestContext.abortWith(
Response.status(Response.Status.UNAUTHORIZED)
.header(HttpHeaders.WWW_AUTHENTICATE,
AUTHENTICATION_SCHEME + " realm=\"" + REALM + "\"")
.build());
}
private void validateToken(String token) throws Exception {
// Check if the token was issued by the server and if it's not expired
// Throw an Exception if the token is invalid
}
}
If any problems happen during the token validation, a response with the status 401 (Unauthorized) will be returned. Otherwise the request will proceed to a resource method.
Securing your REST endpoints
To bind the authentication filter to resource methods or resource classes, annotate them with the #Secured annotation created above. For the methods and/or classes that are annotated, the filter will be executed. It means that such endpoints will only be reached if the request is performed with a valid token.
If some methods or classes do not need authentication, simply do not annotate them:
#Path("/example")
public class ExampleResource {
#GET
#Path("{id}")
#Produces(MediaType.APPLICATION_JSON)
public Response myUnsecuredMethod(#PathParam("id") Long id) {
// This method is not annotated with #Secured
// The authentication filter won't be executed before invoking this method
...
}
#DELETE
#Secured
#Path("{id}")
#Produces(MediaType.APPLICATION_JSON)
public Response mySecuredMethod(#PathParam("id") Long id) {
// This method is annotated with #Secured
// The authentication filter will be executed before invoking this method
// The HTTP request must be performed with a valid token
...
}
}
In the example shown above, the filter will be executed only for the mySecuredMethod(Long) method because it's annotated with #Secured.
Identifying the current user
It's very likely that you will need to know the user who is performing the request agains your REST API. The following approaches can be used to achieve it:
Overriding the security context of the current request
Within your ContainerRequestFilter.filter(ContainerRequestContext) method, a new SecurityContext instance can be set for the current request. Then override the SecurityContext.getUserPrincipal(), returning a Principal instance:
final SecurityContext currentSecurityContext = requestContext.getSecurityContext();
requestContext.setSecurityContext(new SecurityContext() {
#Override
public Principal getUserPrincipal() {
return () -> username;
}
#Override
public boolean isUserInRole(String role) {
return true;
}
#Override
public boolean isSecure() {
return currentSecurityContext.isSecure();
}
#Override
public String getAuthenticationScheme() {
return AUTHENTICATION_SCHEME;
}
});
Use the token to look up the user identifier (username), which will be the Principal's name.
Inject the SecurityContext in any JAX-RS resource class:
#Context
SecurityContext securityContext;
The same can be done in a JAX-RS resource method:
#GET
#Secured
#Path("{id}")
#Produces(MediaType.APPLICATION_JSON)
public Response myMethod(#PathParam("id") Long id,
#Context SecurityContext securityContext) {
...
}
And then get the Principal:
Principal principal = securityContext.getUserPrincipal();
String username = principal.getName();
Using CDI (Context and Dependency Injection)
If, for some reason, you don't want to override the SecurityContext, you can use CDI (Context and Dependency Injection), which provides useful features such as events and producers.
Create a CDI qualifier:
#Qualifier
#Retention(RUNTIME)
#Target({ METHOD, FIELD, PARAMETER })
public #interface AuthenticatedUser { }
In your AuthenticationFilter created above, inject an Event annotated with #AuthenticatedUser:
#Inject
#AuthenticatedUser
Event<String> userAuthenticatedEvent;
If the authentication succeeds, fire the event passing the username as parameter (remember, the token is issued for a user and the token will be used to look up the user identifier):
userAuthenticatedEvent.fire(username);
It's very likely that there's a class that represents a user in your application. Let's call this class User.
Create a CDI bean to handle the authentication event, find a User instance with the correspondent username and assign it to the authenticatedUser producer field:
#RequestScoped
public class AuthenticatedUserProducer {
#Produces
#RequestScoped
#AuthenticatedUser
private User authenticatedUser;
public void handleAuthenticationEvent(#Observes #AuthenticatedUser String username) {
this.authenticatedUser = findUser(username);
}
private User findUser(String username) {
// Hit the the database or a service to find a user by its username and return it
// Return the User instance
}
}
The authenticatedUser field produces a User instance that can be injected into container managed beans, such as JAX-RS services, CDI beans, servlets and EJBs. Use the following piece of code to inject a User instance (in fact, it's a CDI proxy):
#Inject
#AuthenticatedUser
User authenticatedUser;
Note that the CDI #Produces annotation is different from the JAX-RS #Produces annotation:
CDI: javax.enterprise.inject.Produces
JAX-RS: javax.ws.rs.Produces
Be sure you use the CDI #Produces annotation in your AuthenticatedUserProducer bean.
The key here is the bean annotated with #RequestScoped, allowing you to share data between filters and your beans. If you don't wan't to use events, you can modify the filter to store the authenticated user in a request scoped bean and then read it from your JAX-RS resource classes.
Compared to the approach that overrides the SecurityContext, the CDI approach allows you to get the authenticated user from beans other than JAX-RS resources and providers.
Supporting role-based authorization
Please refer to my other answer for details on how to support role-based authorization.
Issuing tokens
A token can be:
Opaque: Reveals no details other than the value itself (like a random string)
Self-contained: Contains details about the token itself (like JWT).
See details below:
Random string as token
A token can be issued by generating a random string and persisting it to a database along with the user identifier and an expiration date. A good example of how to generate a random string in Java can be seen here. You also could use:
Random random = new SecureRandom();
String token = new BigInteger(130, random).toString(32);
JWT (JSON Web Token)
JWT (JSON Web Token) is a standard method for representing claims securely between two parties and is defined by the RFC 7519.
It's a self-contained token and it enables you to store details in claims. These claims are stored in the token payload which is a JSON encoded as Base64. Here are some claims registered in the RFC 7519 and what they mean (read the full RFC for further details):
iss: Principal that issued the token.
sub: Principal that is the subject of the JWT.
exp: Expiration date for the token.
nbf: Time on which the token will start to be accepted for processing.
iat: Time on which the token was issued.
jti: Unique identifier for the token.
Be aware that you must not store sensitive data, such as passwords, in the token.
The payload can be read by the client and the integrity of the token can be easily checked by verifying its signature on the server. The signature is what prevents the token from being tampered with.
You won't need to persist JWT tokens if you don't need to track them. Althought, by persisting the tokens, you will have the possibility of invalidating and revoking the access of them. To keep the track of JWT tokens, instead of persisting the whole token on the server, you could persist the token identifier (jti claim) along with some other details such as the user you issued the token for, the expiration date, etc.
When persisting tokens, always consider removing the old ones in order to prevent your database from growing indefinitely.
Using JWT
There are a few Java libraries to issue and validate JWT tokens such as:
jjwt
java-jwt
jose4j
To find some other great resources to work with JWT, have a look at http://jwt.io.
Handling token revocation with JWT
If you want to revoke tokens, you must keep the track of them. You don't need to store the whole token on server side, store only the token identifier (that must be unique) and some metadata if you need. For the token identifier you could use UUID.
The jti claim should be used to store the token identifier on the token. When validating the token, ensure that it has not been revoked by checking the value of the jti claim against the token identifiers you have on server side.
For security purposes, revoke all the tokens for a user when they change their password.
Additional information
It doesn't matter which type of authentication you decide to use. Always do it on the top of a HTTPS connection to prevent the man-in-the-middle attack.
Take a look at this question from Information Security for more information about tokens.
In this article you will find some useful information about token-based authentication.
This answer is all about authorization and it is a complement of my previous answer about authentication
Why another answer? I attempted to expand my previous answer by adding details on how to support JSR-250 annotations. However the original answer became the way too long and exceeded the maximum length of 30,000 characters. So I moved the whole authorization details to this answer, keeping the other answer focused on performing authentication and issuing tokens.
Supporting role-based authorization with the #Secured annotation
Besides authentication flow shown in the other answer, role-based authorization can be supported in the REST endpoints.
Create an enumeration and define the roles according to your needs:
public enum Role {
ROLE_1,
ROLE_2,
ROLE_3
}
Change the #Secured name binding annotation created before to support roles:
#NameBinding
#Retention(RUNTIME)
#Target({TYPE, METHOD})
public #interface Secured {
Role[] value() default {};
}
And then annotate the resource classes and methods with #Secured to perform the authorization. The method annotations will override the class annotations:
#Path("/example")
#Secured({Role.ROLE_1})
public class ExampleResource {
#GET
#Path("{id}")
#Produces(MediaType.APPLICATION_JSON)
public Response myMethod(#PathParam("id") Long id) {
// This method is not annotated with #Secured
// But it's declared within a class annotated with #Secured({Role.ROLE_1})
// So it only can be executed by the users who have the ROLE_1 role
...
}
#DELETE
#Path("{id}")
#Produces(MediaType.APPLICATION_JSON)
#Secured({Role.ROLE_1, Role.ROLE_2})
public Response myOtherMethod(#PathParam("id") Long id) {
// This method is annotated with #Secured({Role.ROLE_1, Role.ROLE_2})
// The method annotation overrides the class annotation
// So it only can be executed by the users who have the ROLE_1 or ROLE_2 roles
...
}
}
Create a filter with the AUTHORIZATION priority, which is executed after the AUTHENTICATION priority filter defined previously.
The ResourceInfo can be used to get the resource Method and resource Class that will handle the request and then extract the #Secured annotations from them:
#Secured
#Provider
#Priority(Priorities.AUTHORIZATION)
public class AuthorizationFilter implements ContainerRequestFilter {
#Context
private ResourceInfo resourceInfo;
#Override
public void filter(ContainerRequestContext requestContext) throws IOException {
// Get the resource class which matches with the requested URL
// Extract the roles declared by it
Class<?> resourceClass = resourceInfo.getResourceClass();
List<Role> classRoles = extractRoles(resourceClass);
// Get the resource method which matches with the requested URL
// Extract the roles declared by it
Method resourceMethod = resourceInfo.getResourceMethod();
List<Role> methodRoles = extractRoles(resourceMethod);
try {
// Check if the user is allowed to execute the method
// The method annotations override the class annotations
if (methodRoles.isEmpty()) {
checkPermissions(classRoles);
} else {
checkPermissions(methodRoles);
}
} catch (Exception e) {
requestContext.abortWith(
Response.status(Response.Status.FORBIDDEN).build());
}
}
// Extract the roles from the annotated element
private List<Role> extractRoles(AnnotatedElement annotatedElement) {
if (annotatedElement == null) {
return new ArrayList<Role>();
} else {
Secured secured = annotatedElement.getAnnotation(Secured.class);
if (secured == null) {
return new ArrayList<Role>();
} else {
Role[] allowedRoles = secured.value();
return Arrays.asList(allowedRoles);
}
}
}
private void checkPermissions(List<Role> allowedRoles) throws Exception {
// Check if the user contains one of the allowed roles
// Throw an Exception if the user has not permission to execute the method
}
}
If the user has no permission to execute the operation, the request is aborted with a 403 (Forbidden).
To know the user who is performing the request, see my previous answer. You can get it from the SecurityContext (which should be already set in the ContainerRequestContext) or inject it using CDI, depending on the approach you go for.
If a #Secured annotation has no roles declared, you can assume all authenticated users can access that endpoint, disregarding the roles the users have.
Supporting role-based authorization with JSR-250 annotations
Alternatively to defining the roles in the #Secured annotation as shown above, you could consider JSR-250 annotations such as #RolesAllowed, #PermitAll and #DenyAll.
JAX-RS doesn't support such annotations out-of-the-box, but it could be achieved with a filter. Here are a few considerations to keep in mind if you want to support all of them:
#DenyAll on the method takes precedence over #RolesAllowed and #PermitAll on the class.
#RolesAllowed on the method takes precedence over #PermitAll on the class.
#PermitAll on the method takes precedence over #RolesAllowed on the class.
#DenyAll can't be attached to classes.
#RolesAllowed on the class takes precedence over #PermitAll on the class.
So an authorization filter that checks JSR-250 annotations could be like:
#Provider
#Priority(Priorities.AUTHORIZATION)
public class AuthorizationFilter implements ContainerRequestFilter {
#Context
private ResourceInfo resourceInfo;
#Override
public void filter(ContainerRequestContext requestContext) throws IOException {
Method method = resourceInfo.getResourceMethod();
// #DenyAll on the method takes precedence over #RolesAllowed and #PermitAll
if (method.isAnnotationPresent(DenyAll.class)) {
refuseRequest();
}
// #RolesAllowed on the method takes precedence over #PermitAll
RolesAllowed rolesAllowed = method.getAnnotation(RolesAllowed.class);
if (rolesAllowed != null) {
performAuthorization(rolesAllowed.value(), requestContext);
return;
}
// #PermitAll on the method takes precedence over #RolesAllowed on the class
if (method.isAnnotationPresent(PermitAll.class)) {
// Do nothing
return;
}
// #DenyAll can't be attached to classes
// #RolesAllowed on the class takes precedence over #PermitAll on the class
rolesAllowed =
resourceInfo.getResourceClass().getAnnotation(RolesAllowed.class);
if (rolesAllowed != null) {
performAuthorization(rolesAllowed.value(), requestContext);
}
// #PermitAll on the class
if (resourceInfo.getResourceClass().isAnnotationPresent(PermitAll.class)) {
// Do nothing
return;
}
// Authentication is required for non-annotated methods
if (!isAuthenticated(requestContext)) {
refuseRequest();
}
}
/**
* Perform authorization based on roles.
*
* #param rolesAllowed
* #param requestContext
*/
private void performAuthorization(String[] rolesAllowed,
ContainerRequestContext requestContext) {
if (rolesAllowed.length > 0 && !isAuthenticated(requestContext)) {
refuseRequest();
}
for (final String role : rolesAllowed) {
if (requestContext.getSecurityContext().isUserInRole(role)) {
return;
}
}
refuseRequest();
}
/**
* Check if the user is authenticated.
*
* #param requestContext
* #return
*/
private boolean isAuthenticated(final ContainerRequestContext requestContext) {
// Return true if the user is authenticated or false otherwise
// An implementation could be like:
// return requestContext.getSecurityContext().getUserPrincipal() != null;
}
/**
* Refuse the request.
*/
private void refuseRequest() {
throw new AccessDeniedException(
"You don't have permissions to perform this action.");
}
}
Note: The above implementation is based on the Jersey RolesAllowedDynamicFeature. If you use Jersey, you don't need to write your own filter, just use the existing implementation.
I am developing REST services with two types.
before login no session token will be passed to HTTP header.
after login session token will be passed in each request.
I dont want to include #HeaderParam in each and every REST method. I want to intercept it first and based on that I want to check the validity of session. Please let me know
how I can intercept based on headers in RESTEasy
How to avoid intercepting few methods
Thanks.
I solved this problem using PreProcessInterceptor
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.METHOD)
public #interface Securable {
String header() default "session-token";
}
#Provider
#ServerInterceptor
public class ValidationInterceptor implements PreProcessInterceptor, AcceptedByMethod {
#Context
private HttpServletRequest servletRequest;
#Override
public boolean accept(Class clazz, Method method) {
return method.isAnnotationPresent(Securable.class);
}
#Override
public ServerResponse preProcess(HttpRequest httpRequest, ResourceMethod resourceMethod) throws Failure,
WebApplicationException {
Securable securable = resourceMethod.getMethod().getAnnotation(Securable.class);
String headerValue = servletRequest.getHeader(securable.header());
if (headerValue == null){
return (ServerResponse)Response.status(Status.BAD_REQUEST).entity("Invalid Session").build();
}else{
// Validatation logic goes here
}
return null;
}
}
The annotation #Securable will be used on REST service which needs to be validated.
#Securable
#PUT
public Response updateUser(User user)
There are two approaches
Use JAX-RS interceptors - you have access to request object in the interceptor, so you can read headers
Use good old JavaServlet Filters - it is not a problem that you are using JAX-RS, you can filter REST requests as well. Similarly to interceptors, filters have access to request object, which has header information
In both cases you can check if HttpSession exists (request.getSession() method) and it has required attribute.
You can include/exclude requests filtered either in configuration or programatically in Java code, looking at request path.