How to do Rest Authentication with JAX-RS

前端 未结 2 1654
北荒
北荒 2021-02-08 18:16

I am looking for some pointers on how to secure my rest root resource

@Path(\"/employee\")
public class EmployeeResource {

    @GET
    @Produces(\"text/html\"         


        
2条回答
  •  情话喂你
    2021-02-08 19:02

    Declare an interceptor:

     
    
      
    
      
    
    

    Then use it:

      
          
              
          
          (etc)
    

    Then your AuthenticationInterceptor, along the lines of:

    import java.util.Map;
    
    import org.apache.cxf.message.Message;
    import org.apache.cxf.phase.PhaseInterceptor;
    import org.apache.cxf.phase.AbstractPhaseInterceptor;
    import org.apache.cxf.phase.Phase;
    import org.apache.cxf.configuration.security.AuthorizationPolicy;
    import org.apache.cxf.interceptor.Interceptor;
    
    import org.springframework.beans.factory.annotation.Required;
    
    public class AuthenticatorInterceptor extends AbstractPhaseInterceptor {
    
        private Map users;
    
        @Required
        public void setUsers(Map users) {
            this.users = users;
        }
    
        public AuthenticatorInterceptor() {
            super(Phase.RECEIVE);
        }
    
        public void handleMessage(Message message) {
    
            AuthorizationPolicy policy = message.get(AuthorizationPolicy.class);
    
        if (policy == null) {
            System.out.println("User attempted to log in with no credentials");
            throw new RuntimeException("Denied");
            }
    
        String expectedPassword = users.get(policy.getUserName());
        if (expectedPassword == null || !expectedPassword.equals(policy.getPassword())) {
            throw new RuntimeException("Denied");
        }
        }
    
    }
    

    Defining acceptable credentials in a more convenient way is left as an exercise for the reader.

提交回复
热议问题