Enable ContainerRequestFilter without web.xml











up vote
0
down vote

favorite












I'm trying to enable basic authentication using Filter. I likes to enable that without using web.xml file. I tried the answer in the question



Use ContainerRequestFilter in Jersey without web.xml



But I can't get clear idea over that.
How to enable filter without web.xml file?



package com.example.filter;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Base64;
import java.util.StringTokenizer;

import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.ResourceInfo;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;

import com.example.ApiService;

public class AuthFilter implements ContainerRequestFilter {

private HttpServletRequest request;
@Context
private ResourceInfo resourceInfo;
private static final String AUTHORIZATION_PROPERTY = "Authorization";
private static final String AUTHENTICATION_SCHEME = "Basic";
private static final Response ACCESS_DENIED = Response.status(Response.Status.UNAUTHORIZED)
.entity("You cannot access this resource").build();

public boolean isAuthenticated(String authCredentials) {
if (null == authCredentials)
return false;

final String encodedUserPassword = authCredentials.replaceFirst(AUTHENTICATION_SCHEME + " ", "");
String usernameAndPassword = null;
try {
byte decodedBytes = Base64.getDecoder().decode(encodedUserPassword);
usernameAndPassword = new String(decodedBytes, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
final StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":");
final String username = tokenizer.nextToken();
if (request.getSession() != null) {
String mobile_number = (String) request.getSession().getAttribute(ApiService.CONTACT_ID_KEY);
if (mobile_number != username) {
return true;
}
}
return false;
}

@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
Method method = resourceInfo.getResourceMethod();

if (!method.isAnnotationPresent(PermitAll.class)) {


// Fetch authorization header
final String authorization = requestContext.getHeaderString(AUTHORIZATION_PROPERTY);

// If no authorization information present; block access
if (authorization == null || authorization.isEmpty()) {
requestContext.abortWith(ACCESS_DENIED);
return;
}

if(!isAuthenticated(authorization)) {
requestContext.abortWith(ACCESS_DENIED);
return;

}
}

}

}


And this is my Application class



package com.example;

import java.util.HashMap;
import java.util.Map;

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;


@ApplicationPath("/rest")
public class ApiConfig extends Application {

public Map<String, Object> getProperties() {
Map<String, Object> properties = new HashMap<>();
properties.put("jersey.config.server.provider.packages", "com.example");
return properties;
}
}


Thank you.










share|improve this question


























    up vote
    0
    down vote

    favorite












    I'm trying to enable basic authentication using Filter. I likes to enable that without using web.xml file. I tried the answer in the question



    Use ContainerRequestFilter in Jersey without web.xml



    But I can't get clear idea over that.
    How to enable filter without web.xml file?



    package com.example.filter;

    import java.io.IOException;
    import java.lang.reflect.Method;
    import java.util.Base64;
    import java.util.StringTokenizer;

    import javax.annotation.security.PermitAll;
    import javax.servlet.http.HttpServletRequest;
    import javax.ws.rs.container.ContainerRequestContext;
    import javax.ws.rs.container.ContainerRequestFilter;
    import javax.ws.rs.container.ResourceInfo;
    import javax.ws.rs.core.Context;
    import javax.ws.rs.core.Response;

    import com.example.ApiService;

    public class AuthFilter implements ContainerRequestFilter {

    private HttpServletRequest request;
    @Context
    private ResourceInfo resourceInfo;
    private static final String AUTHORIZATION_PROPERTY = "Authorization";
    private static final String AUTHENTICATION_SCHEME = "Basic";
    private static final Response ACCESS_DENIED = Response.status(Response.Status.UNAUTHORIZED)
    .entity("You cannot access this resource").build();

    public boolean isAuthenticated(String authCredentials) {
    if (null == authCredentials)
    return false;

    final String encodedUserPassword = authCredentials.replaceFirst(AUTHENTICATION_SCHEME + " ", "");
    String usernameAndPassword = null;
    try {
    byte decodedBytes = Base64.getDecoder().decode(encodedUserPassword);
    usernameAndPassword = new String(decodedBytes, "UTF-8");
    } catch (IOException e) {
    e.printStackTrace();
    }
    final StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":");
    final String username = tokenizer.nextToken();
    if (request.getSession() != null) {
    String mobile_number = (String) request.getSession().getAttribute(ApiService.CONTACT_ID_KEY);
    if (mobile_number != username) {
    return true;
    }
    }
    return false;
    }

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
    Method method = resourceInfo.getResourceMethod();

    if (!method.isAnnotationPresent(PermitAll.class)) {


    // Fetch authorization header
    final String authorization = requestContext.getHeaderString(AUTHORIZATION_PROPERTY);

    // If no authorization information present; block access
    if (authorization == null || authorization.isEmpty()) {
    requestContext.abortWith(ACCESS_DENIED);
    return;
    }

    if(!isAuthenticated(authorization)) {
    requestContext.abortWith(ACCESS_DENIED);
    return;

    }
    }

    }

    }


    And this is my Application class



    package com.example;

    import java.util.HashMap;
    import java.util.Map;

    import javax.ws.rs.ApplicationPath;
    import javax.ws.rs.core.Application;


    @ApplicationPath("/rest")
    public class ApiConfig extends Application {

    public Map<String, Object> getProperties() {
    Map<String, Object> properties = new HashMap<>();
    properties.put("jersey.config.server.provider.packages", "com.example");
    return properties;
    }
    }


    Thank you.










    share|improve this question
























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      I'm trying to enable basic authentication using Filter. I likes to enable that without using web.xml file. I tried the answer in the question



      Use ContainerRequestFilter in Jersey without web.xml



      But I can't get clear idea over that.
      How to enable filter without web.xml file?



      package com.example.filter;

      import java.io.IOException;
      import java.lang.reflect.Method;
      import java.util.Base64;
      import java.util.StringTokenizer;

      import javax.annotation.security.PermitAll;
      import javax.servlet.http.HttpServletRequest;
      import javax.ws.rs.container.ContainerRequestContext;
      import javax.ws.rs.container.ContainerRequestFilter;
      import javax.ws.rs.container.ResourceInfo;
      import javax.ws.rs.core.Context;
      import javax.ws.rs.core.Response;

      import com.example.ApiService;

      public class AuthFilter implements ContainerRequestFilter {

      private HttpServletRequest request;
      @Context
      private ResourceInfo resourceInfo;
      private static final String AUTHORIZATION_PROPERTY = "Authorization";
      private static final String AUTHENTICATION_SCHEME = "Basic";
      private static final Response ACCESS_DENIED = Response.status(Response.Status.UNAUTHORIZED)
      .entity("You cannot access this resource").build();

      public boolean isAuthenticated(String authCredentials) {
      if (null == authCredentials)
      return false;

      final String encodedUserPassword = authCredentials.replaceFirst(AUTHENTICATION_SCHEME + " ", "");
      String usernameAndPassword = null;
      try {
      byte decodedBytes = Base64.getDecoder().decode(encodedUserPassword);
      usernameAndPassword = new String(decodedBytes, "UTF-8");
      } catch (IOException e) {
      e.printStackTrace();
      }
      final StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":");
      final String username = tokenizer.nextToken();
      if (request.getSession() != null) {
      String mobile_number = (String) request.getSession().getAttribute(ApiService.CONTACT_ID_KEY);
      if (mobile_number != username) {
      return true;
      }
      }
      return false;
      }

      @Override
      public void filter(ContainerRequestContext requestContext) throws IOException {
      Method method = resourceInfo.getResourceMethod();

      if (!method.isAnnotationPresent(PermitAll.class)) {


      // Fetch authorization header
      final String authorization = requestContext.getHeaderString(AUTHORIZATION_PROPERTY);

      // If no authorization information present; block access
      if (authorization == null || authorization.isEmpty()) {
      requestContext.abortWith(ACCESS_DENIED);
      return;
      }

      if(!isAuthenticated(authorization)) {
      requestContext.abortWith(ACCESS_DENIED);
      return;

      }
      }

      }

      }


      And this is my Application class



      package com.example;

      import java.util.HashMap;
      import java.util.Map;

      import javax.ws.rs.ApplicationPath;
      import javax.ws.rs.core.Application;


      @ApplicationPath("/rest")
      public class ApiConfig extends Application {

      public Map<String, Object> getProperties() {
      Map<String, Object> properties = new HashMap<>();
      properties.put("jersey.config.server.provider.packages", "com.example");
      return properties;
      }
      }


      Thank you.










      share|improve this question













      I'm trying to enable basic authentication using Filter. I likes to enable that without using web.xml file. I tried the answer in the question



      Use ContainerRequestFilter in Jersey without web.xml



      But I can't get clear idea over that.
      How to enable filter without web.xml file?



      package com.example.filter;

      import java.io.IOException;
      import java.lang.reflect.Method;
      import java.util.Base64;
      import java.util.StringTokenizer;

      import javax.annotation.security.PermitAll;
      import javax.servlet.http.HttpServletRequest;
      import javax.ws.rs.container.ContainerRequestContext;
      import javax.ws.rs.container.ContainerRequestFilter;
      import javax.ws.rs.container.ResourceInfo;
      import javax.ws.rs.core.Context;
      import javax.ws.rs.core.Response;

      import com.example.ApiService;

      public class AuthFilter implements ContainerRequestFilter {

      private HttpServletRequest request;
      @Context
      private ResourceInfo resourceInfo;
      private static final String AUTHORIZATION_PROPERTY = "Authorization";
      private static final String AUTHENTICATION_SCHEME = "Basic";
      private static final Response ACCESS_DENIED = Response.status(Response.Status.UNAUTHORIZED)
      .entity("You cannot access this resource").build();

      public boolean isAuthenticated(String authCredentials) {
      if (null == authCredentials)
      return false;

      final String encodedUserPassword = authCredentials.replaceFirst(AUTHENTICATION_SCHEME + " ", "");
      String usernameAndPassword = null;
      try {
      byte decodedBytes = Base64.getDecoder().decode(encodedUserPassword);
      usernameAndPassword = new String(decodedBytes, "UTF-8");
      } catch (IOException e) {
      e.printStackTrace();
      }
      final StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":");
      final String username = tokenizer.nextToken();
      if (request.getSession() != null) {
      String mobile_number = (String) request.getSession().getAttribute(ApiService.CONTACT_ID_KEY);
      if (mobile_number != username) {
      return true;
      }
      }
      return false;
      }

      @Override
      public void filter(ContainerRequestContext requestContext) throws IOException {
      Method method = resourceInfo.getResourceMethod();

      if (!method.isAnnotationPresent(PermitAll.class)) {


      // Fetch authorization header
      final String authorization = requestContext.getHeaderString(AUTHORIZATION_PROPERTY);

      // If no authorization information present; block access
      if (authorization == null || authorization.isEmpty()) {
      requestContext.abortWith(ACCESS_DENIED);
      return;
      }

      if(!isAuthenticated(authorization)) {
      requestContext.abortWith(ACCESS_DENIED);
      return;

      }
      }

      }

      }


      And this is my Application class



      package com.example;

      import java.util.HashMap;
      import java.util.Map;

      import javax.ws.rs.ApplicationPath;
      import javax.ws.rs.core.Application;


      @ApplicationPath("/rest")
      public class ApiConfig extends Application {

      public Map<String, Object> getProperties() {
      Map<String, Object> properties = new HashMap<>();
      properties.put("jersey.config.server.provider.packages", "com.example");
      return properties;
      }
      }


      Thank you.







      java jersey jax-rs tomcat8 requestfiltering






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 21 at 1:56









      Chitraveer Akhil

      13210




      13210
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          1
          down vote



          accepted










          You need to annotate it with @Provider. The scanning picks up classes that are annotated with @Provider and @Path. You also need to add @Context for the HttpServletRequest if you want it injected (you only have it on the ResourceInfo).






          share|improve this answer





















          • Thank you. It works.
            – Chitraveer Akhil
            Nov 21 at 10:02











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














           

          draft saved


          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53404287%2fenable-containerrequestfilter-without-web-xml%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          1
          down vote



          accepted










          You need to annotate it with @Provider. The scanning picks up classes that are annotated with @Provider and @Path. You also need to add @Context for the HttpServletRequest if you want it injected (you only have it on the ResourceInfo).






          share|improve this answer





















          • Thank you. It works.
            – Chitraveer Akhil
            Nov 21 at 10:02















          up vote
          1
          down vote



          accepted










          You need to annotate it with @Provider. The scanning picks up classes that are annotated with @Provider and @Path. You also need to add @Context for the HttpServletRequest if you want it injected (you only have it on the ResourceInfo).






          share|improve this answer





















          • Thank you. It works.
            – Chitraveer Akhil
            Nov 21 at 10:02













          up vote
          1
          down vote



          accepted







          up vote
          1
          down vote



          accepted






          You need to annotate it with @Provider. The scanning picks up classes that are annotated with @Provider and @Path. You also need to add @Context for the HttpServletRequest if you want it injected (you only have it on the ResourceInfo).






          share|improve this answer












          You need to annotate it with @Provider. The scanning picks up classes that are annotated with @Provider and @Path. You also need to add @Context for the HttpServletRequest if you want it injected (you only have it on the ResourceInfo).







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 21 at 3:48









          Paul Samsotha

          147k19277462




          147k19277462












          • Thank you. It works.
            – Chitraveer Akhil
            Nov 21 at 10:02


















          • Thank you. It works.
            – Chitraveer Akhil
            Nov 21 at 10:02
















          Thank you. It works.
          – Chitraveer Akhil
          Nov 21 at 10:02




          Thank you. It works.
          – Chitraveer Akhil
          Nov 21 at 10:02


















           

          draft saved


          draft discarded



















































           


          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53404287%2fenable-containerrequestfilter-without-web-xml%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Berounka

          Sphinx de Gizeh

          Different font size/position of beamer's navigation symbols template's content depending on regular/plain...