我正在寻找有关如何保护我的剩余根资源的一些建议
@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/