title: JAX-RS REST API Basic Authentication
body: <p>i am trying to implement basic authentication to somehow secure my rest api.To test, i tried below code to filter the url parameter that contains users however it is not aborting the request without authorization.  and  the most important is i need to implement it in the way that only update and delete needs to be authorized with the respective username and password. other things i just don't want to filter. i have an user class having username and password (encrypted) properties. so if the url contains PUT or delete method on users/{userID} i want it to verify with the username and password of that specific users. i have listed code of model , resources and filter class below.. i really need your help. thanks in advance.</p>
  
  <p>filter class.</p>
  
  <pre><code>package Authentication;
  
  import java.io.IOException;
  import java.util.List;
  import java.util.StringTokenizer;
  import javax.ws.rs.container.ContainerRequestContext;
  import javax.ws.rs.container.ContainerRequestFilter;
  import javax.ws.rs.core.Response;
  import javax.ws.rs.ext.Provider;
  import org.glassfish.jersey.internal.util.Base64;
  
  
  @Provider
  public class SecureFilter implements ContainerRequestFilter {
  
      private static final String Auth_Header = "Authorization";
      private static final String Auth_Header_Prefix = "Basic ";
  
      @Override
      public void filter(ContainerRequestContext requestContext) throws IOException {
          if (requestContext.getUriInfo().getPath().contains("users")) {
              List&lt;String&gt; authHeader = requestContext.getHeaders().get(Auth_Header);
              if (authHeader != null &amp;&amp; authHeader.size() &gt; 0) {
                  String authToken = authHeader.get(0);
                  authToken = authToken.replaceFirst(Auth_Header_Prefix, "");
                  String decodedString = Base64.decodeAsString(authToken);
                  StringTokenizer tokenizer = new StringTokenizer(decodedString, ":");
                  String userName = tokenizer.nextToken();
                  String password = tokenizer.nextToken();
                  if ("user".equals(userName) &amp;&amp; "password".equals(password)) {
                      return;
                  }
                  Response unauthorizedstatus = Response
                          .status(Response.Status.UNAUTHORIZED)
                          .entity("these resources needs authorization. ")
                          .build();
                  requestContext.abortWith(unauthorizedstatus);
  
              }
          }
  
      }
  
  } 
  </code></pre>
  
  <p>resource class:</p>
  
  <pre><code>import com.mycompany.samplehospital.model.Alert;
  import com.mycompany.samplehospital.model.Message;
  
  /*
   * To change this license header, choose License Headers in Project Properties.
   * To change this template file, choose Tools | Templates
   * and open the template in the editor.
   */
  
  
  import com.mycompany.samplehospital.model.User;
  
  import com.mycompany.samplehospital.Services.UserServices;
  import com.mycompany.samplehospital.exception.objectNotFound;
  import com.mycompany.samplehospital.Services.AlertServices;
  import com.mycompany.samplehospital.Services.MessageServices;
  
  import java.util.List;
  import javax.ws.rs.Consumes;
  import javax.ws.rs.DELETE;
  import javax.ws.rs.GET;
  import javax.ws.rs.POST;
  import javax.ws.rs.PUT;
  import javax.ws.rs.Path;
  import javax.ws.rs.PathParam;
  import javax.ws.rs.Produces;
  import javax.ws.rs.core.MediaType;
  
  /**
   *
   * @author sandesh poudel
   */
  @Produces(MediaType.APPLICATION_XML)
  @Path("/users")
  public class userResources {
  
  
   UserServices service ;
   public userResources() throws Exception{
       service = new UserServices();
   }
  
  
  
  
  
      @GET
      @Produces(MediaType.APPLICATION_XML)
      public List&lt;User&gt; getAllUser(){
      return UserServices.getUsers();
  
  
      }
      @Path("/{userId}")
  
      @GET
      @Produces(MediaType.APPLICATION_XML)
      public User getUser(@PathParam("userId") int ID ) throws Exception{
          User myUserList = service.getUser(ID);
          if (myUserList == null){
          throw new objectNotFound("User not Found"); 
          }else {
              return myUserList;
          }
  
      }
  
  
      @POST
      @Produces(MediaType.APPLICATION_XML)
        @Consumes(MediaType.APPLICATION_XML)
  
  
      public User addUser(User user ) throws Exception{
  
          return service.AddUser(user);
  
  
  
      }
  }
  
  
      @PUT
          @Path("/{userId}")
  
      @Produces(MediaType.APPLICATION_XML)
        @Consumes(MediaType.APPLICATION_XML)
  
  
      public User updtaeUser(User user) throws Exception{
  
      return service.updateUser(user);
  
      }
      @DELETE 
        @Path("/{userId}")
         @Produces(MediaType.APPLICATION_XML)
  
      public User delUser(@PathParam("userId") int ID) throws Exception{
  
          return service.removeUser(ID);
  
  
      }
      @Path("/{userId}/messages")
  
      @GET
      @Produces(MediaType.APPLICATION_XML)
  
      public  List&lt;Message&gt; getAllMessageByUser(@PathParam("userId") int ID) throws Exception{
          MessageServices mservice = new MessageServices();
  
          List&lt;Message&gt; messageUserList = mservice.getAllMessageByUser(ID);
          if (messageUserList == null ){
              throw new objectNotFound("messages not Found"); 
  
          } return messageUserList;
  
          }
      @GET
      @Produces(MediaType.APPLICATION_XML)
      @Path("/{userId}/alerts")
  
  
      public List&lt;Alert&gt; AlertsResources(@PathParam("userId") int userId){
          AlertServices myAlert = new AlertServices();
  
  
          List&lt;Alert&gt; newAlertUserList = myAlert.getAllAlertByUser(userId) ;
          if (newAlertUserList == null){
              throw new objectNotFound("messages not Found"); 
  
          } return newAlertUserList;
  
  
      }
  </code></pre>
  
  <p>Model class User</p>
  
  <pre><code>package com.mycompany.samplehospital.model;
  
  import java.io.Serializable;
  import java.util.Map;
  
  import javax.xml.bind.annotation.XmlElement;
  import javax.xml.bind.annotation.XmlRootElement;
  import javax.xml.bind.annotation.XmlTransient;
  import Authentication.HashPassword;
  import java.io.IOException;
  import java.util.logging.Level;
  import java.util.logging.Logger;
  
  /**
   *
   * @author sandeshpoudel
   */
  @XmlRootElement
  
  public  class User implements Serializable {
      /**
       * 
       */
  
      private static final long serialVersionUID = 1L;
      private String title;
      private int age;
      private String Sex;
      private String Address;
      private int phoneNo;
      private String fullName;
      private int id;
      private Map&lt;Integer, Message&gt; allMessage;
      private Map&lt;Integer,Alert&gt; allAlerts;
      private String userName;
      private String passWord;
      private HashPassword hs ;
  
  
  
  
  
      public User() {
      }
  
  
      public User(int id,String fullName, String Sex, Integer age, Integer  phoneNumber, String Address, String title,String userName,String password) throws Exception {
          hs = new HashPassword();
          this.id= id;
          this.fullName = fullName;
          this.title = title;
          this.age = age;
          this.Sex = Sex;
          this.Address = Address;
          this.phoneNo = phoneNumber;
           setPassWord(password);
         // setPassWord(passWord) uncomment this and remove next line to execute on encryption mode;
  
  
          this.userName= userName;
  
      }
      public void setId(int id){
          this.id= id;
      }
      public void setFullName(String fullName) {
          this.fullName = fullName;
      }
  
      public void setTitle(String title) {
          this.title = title;
      }
  
      public void setAge(int age) {
          this.age = age;
      }
  
      public void setSex(String Sex) {
          this.Sex = Sex;
      }
  
      public void setAddress(String Address) {
          this.Address = Address;
      }
  
      public void setPhoneNo(int phoneNo) {
          this.phoneNo = phoneNo;
      }
  
      public String getUserName() {
          return userName;
      }
  
      public void setUserName(String userName) {
          this.userName = userName;
      }
      @XmlElement
      public String getPassWord() {
          return passWord;
      }
  
      public  void setPassWord(String passWord) throws Exception {
  
                  hs = new HashPassword();
                  this.passWord = hs.encrypt(passWord);
  
  
        //  this.passWord = passWord;
      }
  
  
  
  
  @XmlElement
      public String getFullName() {
          return fullName;
      }
      /*
  
      */
  @XmlElement
    public int getId(){
      return id;
  }
  @XmlElement
  
      public String getTitle() {
          return title;
      }
  @XmlElement
  
      public int getAge() {
          return age;
      }
  @XmlElement
  
      public String getSex() {
          return Sex;
      }
  @XmlElement
  
      public String getAddress() {
          return Address;
      }
  @XmlElement
  
      public int getPhoneNo() {
          return phoneNo;
      }
     @XmlTransient
      public Map&lt;Integer, Message&gt; getAllMessage() {
      return allMessage;
  }
      public void setAllMessage(Map&lt;Integer, Message&gt; allMessage) {
      this.allMessage = allMessage;
  }   @XmlTransient
  
      public Map&lt;Integer, Alert&gt; getAllAlerts() {
      return allAlerts;
  }
      public void setAllAlerts(Map&lt;Integer, Alert&gt; allAlerts) {
      this.allAlerts = allAlerts;
      }
  
  
    @Override
      public String toString(){
          return (getSex() +" "+ getAddress()+" "+ getPhoneNo() +" "+ getFullName());
      }
  }
  </code></pre>