如何使用JAX-RS进行Rest身份验证 [英] How to do Rest Authentication with JAX-RS

查看:305
本文介绍了如何使用JAX-RS进行Rest身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找关于如何保护我的其余根资源的一些指示

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

@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的帖子,我知道这个概念,但我正在寻找如何在代码中实现它的方法。

I have read post's regarding basic authetication and OAuth, I know the concept but i am looking for ways on how to implement it in code.

谢谢

推荐答案

声明一个拦截器:

 <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,包括:

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<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");
    }
    }

}

定义可接受以更方便的方式获取凭证留给读者练习。

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

这篇关于如何使用JAX-RS进行Rest身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆