1

I am trying to implement Token based authentication in java RESTful web service.

So far I have done following things 1) Created NameBinding secured

@NameBinding @Retention(RetentionPolicy.SOURCE) @Target({ElementType.TYPE, ElementType.METHOD}) public @interface Secured { } 

2) Created a authentication filter

@Secured @Provider @Priority(Priorities.AUTHENTICATION) public class AuthenticationFilter implements ContainerRequestFilter { @Override public void filter(ContainerRequestContext requestContext) throws IOException { // Get the HTTP Authorization header from the request String authorizationHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION); // Check if the HTTP Authorization header is present and formatted correctly if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer")) { throw new NotAuthorizedException("Authorization header must be provided"); } // Extract the token from the HTTP Authorization header String token = authorizationHeader.substring("Bearer".length()).trim(); try { // Validate the token validateToken(token); } catch (Exception e) { requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build()); } } private void validateToken(String token) throws Exception { // Check if it was issued by the server and if it's not expired // Throw an Exception if the token is invalid } 

3) Now When I am trying to put secured annotation on my service method somehow it is not working and correct json is returned.

@GET @Secured @Path("{custid}/invoices") @Produces({"application/json"}) @Consumes({"application/x-www-form-urlencoded"}) public List<Document> getCustomerInvoices( @PathParam("custid") String account, @DefaultValue("") @QueryParam("fromdate") String fromDate, @DefaultValue("") @QueryParam("todate") String toDate) throws Exception{ Date from = null; Date to = null; SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); if(!fromDate.equals("")) { from = formatter.parse(fromDate); } if(!toDate.equals("")) { to = formatter.parse(toDate); } ArrayList<Document> invoices = (ArrayList<Document>) CustomerBiz.getInvoices(documentumConfigUtil,DocumentType.TAX_INVOICE,account,from,to); return invoices; } 

Please suggest me where I am doing wrong.

Note: I have used Apache CXF and spring to create java web service.

1 Answer 1

1

I have solved this issue. Actually the problem was in my beans.xml

I used following lines to fix the problem

<jaxrs:server id="CustomerResource" address="/customers"> <jaxrs:serviceBeans> <ref bean="customerResource" /> </jaxrs:serviceBeans> <jaxrs:providers> <ref bean='jsonProvider' /> <ref bean='authenticationFilter' /> </jaxrs:providers> </jaxrs:server> 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.