2017-07-26 127 views
1

我試圖在java RESTful web服務中實現基於令牌的身份驗證。基於REST令牌的身份驗證不起作用

創建NameBinding到目前爲止,我已經做以下的事情 1)固定

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

2)創建的驗證過濾器

@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)現在,當我試圖把安全註解我服務方法莫名其妙地不工作和正確的JSON返回。

@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; 
} 

請建議我在哪裏做錯了。

注意:我已經使用Apache CXF和spring創建java web服務。

回答

0

我已經解決了這個問題。其實這個問題在我的beans.xml

我用以下行來解決這個問題

<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> 
相關問題