rest - 如何使用JAX-RS进行身份验证

标签 rest jakarta-ee jersey jax-rs restful-authentication

我正在寻找有关如何保护我的剩余根资源的一些建议

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

    @GET
    @Produces("text/html")
    public String get(
        @QueryParam("name") String empname,
        @QueryParam("sn") String sn) {

         // Return a data back.
    }
}

我已经阅读了有关基本认证和OAuth的文章,我知道这个概念,但是我正在寻找有关如何在代码中实现它的方法。

谢谢

最佳答案

声明一个拦截器:

 <bean id="securityInterceptor" class="AuthenticatorInterceptor">
<property name="users">
  <map>
<entry key="someuser" value="somepassword"/>
  </map>
</property>

然后使用它:
  <jaxrs:server address="/">
      <jaxrs:inInterceptors>
          <ref bean="securityInterceptor"/>
      </jaxrs:inInterceptors>
      (etc)

然后是您的AuthenticationInterceptor,大致如下:
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<Message> {

    private Map<String,String> users;

    @Required
    public void setUsers(Map<String, String> 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");
    }
    }

}

读者可以以更方便的方式定义可接受的凭据。

关于rest - 如何使用JAX-RS进行身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4124831/

相关文章:

google-app-engine - 通过 ssh,appengine 项目通常位于服务器的文件系统中的什么位置?

spring - org.springframework.web.servlet.PageNotFound noHandlerFound未找到具有URI的HTTP请求的映射

rest - Tomcat,请求的资源不可用

Spring + Hibernate + jersey 中的 java.lang.ExceptionInInitializerError

mysql - 如何在 REST 中实现父子关系以允许 JAXRS 中的层次结构

java - JUnit 测试方法未执行

android - 使用 Apache HttpDelete 为 Rest Web 服务 Android 传递参数和 header

java - 使用 Jersey 和 @ApplicationPath 注解加载资源

rest - 如何在IIS 7上部署DataSnap/REST ISAP dll

php - 利用 cURL header 问题的 REST-ful 连接