如何实现Jax-RS基本认证?

时间:2018-05-04 05:34:54

标签: java jax-rs http-basic-authentication request-headers response-headers

如何为每个请求实施JAX-RS基本身份验证和授权?我正在做以下步骤。

  1. @HeaderParam
  2. 接受用户名和密码
  3. 解码
  4. 验证后,在响应标头中设置唯一标记。 直到这一步它才能正常工作。
  5. 但是如何验证用户的新请求?对于新请求,@HeaderParam("Authorization")为空。

    我的代码是

    @GET
    @Path("/login")
    public Response login(@HeaderParam("Authorization") String authString){
        String reponseHeader="";
        String reponseHeaderValue="";
        int errorCode=0;
        try{
            if(authString!=null){
                System.out.println("#########" + authString);
                String[] authParts = authString.split("\\s+");
                String authInfo = authParts[1];
                // Decode the data back to original string
                byte[] bytes = new BASE64Decoder().decodeBuffer(authInfo);
                String decodedAuth = new String(bytes);
                System.out.println(decodedAuth);
               String[] credentials = decodedAuth.split(":");
                UserAuthentication userAuthentication = getService(UserAuthentication.class);
                if(userAuthentication == null)
                    throw new UserAuthenticationException("Unable to get UserAuthentication Service");
                String userName = credentials[0];
                String pwd =   credentials[1];
                LoginSession obj_Session = userAuthentication.authenticateUser(userName,pwd);
                sessionCount = sessionCount + 1;
                String strSessionKey = userName  + "_" + sessionCount + "";
                reponseHeaderValue="Basic "+strSessionKey;
                reponseHeader="Authorization:";
                errorCode=200;
            }else{
                reponseHeaderValue="User Visible Realm";
                reponseHeader="WWW-Authenticate: Basic realm=";
                errorCode=401;
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }
        return Response.ok().header(reponseHeader, reponseHeaderValue).status(errorCode).build();
    }
    

    这是我对用户进行身份验证的方式。一旦它被认证为下一个请求,即

    @GET
    @Path("/")
    @Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
    @Consumes(MediaType.APPLICATION_JSON + ";charset=utf-8")
    public String getProjectList(@HeaderParam("Authorization") String authString){
        System.out.println("##############"+authString);
        System.out.println("##############");
        return authString;
    }
    

    但是@HeaderParam("Authorization")为空,这就是我无法授权用户的原因。

0 个答案:

没有答案