如何在 JAX-RS 服务中读取授权标头

2022-09-03 06:22:00

我是授权标头的新手,尝试使用 JAX-RS 服务创建授权(和认证)

我在javascript上的片段看起来像这样:

            sUrl = getURL() + "/com.cabRoutePlanner.Login/Login";  
            var oHeaders = {};
            oHeaders['Authorization'] = "Basic " + btoa(getUserName() + ":" + getPassword());

            var request = {
                headers : oHeaders,
                requestUri : sUrl,
                data: connectionData,
                method : "POST"
            };
            OData.request(request, onSuccessForRegister, onRegError);

现在,我想在 JAX-RS 服务中读取此授权标头,即在我的 Java Rest 服务中返回用户名和密码,并检查我的 db。我感到困惑的是,我不知道如何使用这个授权标头。如果有人能向我展示 REST 服务中函数的声明,并访问我的用户名和 passwrd,那就太好了。

我以某种方式编写了代码,并得到了Eclipse的一点直觉和很大的帮助。

@Path("/Log")
@POST
@Produces(MediaType.APPLICATION_JSON)
public Response log(HttpServletRequest req)throws JSONException
{
    JSONObject returnObject = new JSONObject();
    String authorization = req.getHeader("Authorization");
    if (authorization != null && authorization.startsWith("Basic")) 
    {
        //byte[] message = authorization.substring("Basic".length()).trim().getBytes();
        String credentials = authorization.substring("Basic".length()).trim();
        byte[] decoded = DatatypeConverter.parseBase64Binary(credentials);
        String decodedString = new String(decoded);
        String[] actualCredentials = decodedString.split(":");
        String ID = actualCredentials[0];
        String Password = actualCredentials[1];
        String Result = actualLog(ID, Password);
        if(Result.equals("ID Does not exist"))
        {
            returnObject.put("Result", "ID Does not exist");
            return Response.status(401).entity(returnObject).build();

        }
        else if(Result.equals("Password incorrect for given User"))
        {
            returnObject.put("Result", "Password incorrect for given User");
            return Response.status(401).entity(returnObject).build();
        }
        else
        {
            returnObject.put("Result", Result);
            return Response.status(200).entity(returnObject).build();
        }
    }
    else
    {
        returnObject.put("Result", "Authorization header wrong");
        return Response.status(401).entity(returnObject).build();
    }
}

现在,这是我得到的当前异常,我无法理解它:

 Oct 06, 2014 4:13:59 PM com.sun.jersey.spi.container.ContainerRequest getEntity
 SEVERE: A message body reader for Java class javax.servlet.http.HttpServletRequest, and Java type interface javax.servlet.http.HttpServletRequest, and MIME media type application/octet-stream was not found.
 The registered message body readers compatible with the MIME media type are:
 application/octet-stream ->
 com.sun.jersey.core.impl.provider.entity.ByteArrayProvider
 com.sun.jersey.core.impl.provider.entity.FileProvider
 com.sun.jersey.core.impl.provider.entity.InputStreamProvider
 com.sun.jersey.core.impl.provider.entity.DataSourceProvider
 com.sun.jersey.core.impl.provider.entity.RenderedImageProvider
 */* ->
 com.sun.jersey.core.impl.provider.entity.FormProvider
 com.sun.jersey.core.impl.provider.entity.MimeMultipartProvider
 com.sun.jersey.core.impl.provider.entity.StringProvider
 com.sun.jersey.core.impl.provider.entity.ByteArrayProvider
 com.sun.jersey.core.impl.provider.entity.FileProvider
 com.sun.jersey.core.impl.provider.entity.InputStreamProvider
 com.sun.jersey.core.impl.provider.entity.DataSourceProvider
 com.sun.jersey.core.impl.provider.entity.XMLJAXBElementProvider$General
 com.sun.jersey.core.impl.provider.entity.ReaderProvider
 com.sun.jersey.core.impl.provider.entity.DocumentProvider
 com.sun.jersey.core.impl.provider.entity.SourceProvider$StreamSourceReader
 com.sun.jersey.core.impl.provider.entity.SourceProvider$SAXSourceReader
 com.sun.jersey.core.impl.provider.entity.SourceProvider$DOMSourceReader
 com.sun.jersey.json.impl.provider.entity.JSONJAXBElementProvider$General
 com.sun.jersey.json.impl.provider.entity.JSONArrayProvider$General
 com.sun.jersey.json.impl.provider.entity.JSONObjectProvider$General
 com.sun.jersey.core.impl.provider.entity.XMLRootElementProvider$General
 com.sun.jersey.core.impl.provider.entity.XMLListElementProvider$General
 com.sun.jersey.core.impl.provider.entity.XMLRootObjectProvider$General
 com.sun.jersey.core.impl.provider.entity.EntityHolderReader
 com.sun.jersey.json.impl.provider.entity.JSONRootElementProvider$General
 com.sun.jersey.json.impl.provider.entity.JSONListElementProvider$General
 com.sun.jersey.json.impl.provider.entity.JacksonProviderProxy

答案 1

您应该在方法中使用注入请求,如下所示:@Context HttpServletRequest request

public Response log(@Context HttpServletRequest req) throws JSONException

可以使用注入的其他有用对象包括(有关详细信息,请参阅 JAX-RS 规范):@Context

  • Application
  • UriInfo,HttpHeaders
  • SecurityContext,
  • Providers,Request
  • ServletConfigServletContextHttpServletRequestHttpServletResponse

因此,在您的情况下,您也可以使用,然后@Context HttpHeaders headers

List<String> authHeaders = headers.getRequestHeader(HttpHeaders.AUTHORIZATION);

答案 2