Bin*_*ode 9 rest restful-authentication jax-rs jersey java-ee
我正在寻找关于如何保护我的休息根资源的一些指示
@Path("/employee")
public class EmployeeResource {
@GET
@Produces("text/html")
public String get(
@QueryParam("name") String empname,
@QueryParam("sn") String sn) {
// Return a data back.
}
}
Run Code Online (Sandbox Code Playgroud)
我已阅读有关基本认证和OAuth的帖子,我知道这个概念,但我正在寻找如何在代码中实现它的方法.
谢谢
声明一个拦截器:
<bean id="securityInterceptor" class="AuthenticatorInterceptor">
<property name="users">
<map>
<entry key="someuser" value="somepassword"/>
</map>
</property>
Run Code Online (Sandbox Code Playgroud)
然后使用它:
<jaxrs:server address="/">
<jaxrs:inInterceptors>
<ref bean="securityInterceptor"/>
</jaxrs:inInterceptors>
(etc)
Run Code Online (Sandbox Code Playgroud)
然后你的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");
}
}
}
Run Code Online (Sandbox Code Playgroud)
以更方便的方式定义可接受的凭证留给读者练习.
归档时间: |
|
查看次数: |
9533 次 |
最近记录: |