【发布时间】:2018-01-01 08:33:48
【问题描述】:
我正在尝试在 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 服务。
【问题讨论】:
标签: java web-services rest annotations restful-authentication