我正在尝试在java RESTful Web服务中实现基于令牌的身份验证。
到目前为止,我已经做了以下事情 1)创建了NameBinding安全
@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 :(得分:1)
我已经解决了这个问题。实际上问题出在我的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>