Java JAX-RS REST 服务如何通过注释处理身份验证?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9690574/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can a JAX-RS REST service have authentication handled by annotations?
提问by Daenyth
I have a REST api written with JAX-RS, and I need to add authentication to it. So far all the information I've been able to find about it has suggestions for doing it via spring, which I'm not using. Is there something already existing, or would it be easy to write, something that will let me annotate either a method, or the entire class which would force auth headers to be present?
我有一个用 JAX-RS 编写的 REST api,我需要向它添加身份验证。到目前为止,我能找到的所有关于它的信息都有通过 spring来做的建议,我没有使用。是否有一些已经存在的东西,或者它是否容易编写,让我注释一个方法或整个类,这将强制出现身份验证标头?
I'm using tomcat6 and jersey, if that matters.
如果重要的话,我正在使用 tomcat6 和 jersey。
Something like:
就像是:
@Path("api")
public class Api {
@GET
@AuthenticationRequired
public Response getInfo(...) {...}
}
采纳答案by derdc
I think you want import javax.annotation.Security.RolesAllowed;
我想你想要 import javax.annotation.Security.RolesAllowed;
The annotation itself looks like this
注释本身看起来像这样
@Path("/helloworld")
@RolesAllowed({"ADMIN", "ORG1"})
public class helloWorld {
@GET
@Path("sayHello")
@Produces("text/plain")
@RolesAllowed("ADMIN")
public String sayHello() {
return "Hello World!";
}
}
回答by paulsm4
I would manage security at the container level. Here's a good writeup if you happen to be using Apache CXF:
我会在容器级别管理安全性。如果您碰巧使用 Apache CXF,这里有一篇很好的文章:
http://cxf.apache.org/docs/secure-jax-rs-services.html
http://cxf.apache.org/docs/secure-jax-rs-services.html
And here's an example for Glassfish:
这是 Glassfish 的示例:
http://www.butonic.de/2010/06/18/a-simple-jax-rs-security-context-example-in-glassfish/
http://www.butonic.de/2010/06/18/a-simple-jax-rs-security-context-example-in-glassfish/
Here's one more link, which discusses JSR 250 annotations (e.g. @RolesAllowed):
这里还有一个链接,它讨论了 JSR 250 注释(例如 @RolesAllowed):