当前位置:   article > 正文

安全认证和授权方式:嵌入式Jetty+Jersey_jetrry 身份认证 方式

jetrry 身份认证 方式

首先启动一个Server:

  1. public Server getServer() {
  2. Server server = new Server(new InetSocketAddress("localhost", 8081));
  3. ServletContextHandler jerseyHandler = getJerseyHandler();
  4. setSecurity(jerseyHandler);
  5. server.setHandler(jerseyHandler);
  6. return server;
  7. }

其中的JerseyHandler如下:

  1. public ServletContextHandler getJerseyHandler() {
  2. ServletContextHandler handler = new ServletContextHandler(ServletContextHandler.SESSIONS);
  3. handler.setContextPath("/ws/v1");
  4. //add jersey container
  5. ServletHolder jerseyServletHolder = new ServletHolder(ServletContainer.class);
  6. jerseyServletHolder.setInitParameter("com.sun.jersey.config.property.resourceConfigClass",
  7. "com.sun.jersey.api.core.PackagesResourceConfig");
  8. jerseyServletHolder.setInitParameter("com.sun.jersey.config.property.packages", "rest/resouce");
  9. handler.addServlet(jerseyServletHolder, "/*");
  10. return handler;
  11. }


这里使用的是Jetty自带的安全认证方式:SecurityHandler:

  1. private void setSecurity(ServletContextHandler handler) {
  2. ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();
  3. handler.setSecurityHandler(securityHandler);
  4. Constraint constraint = new Constraint();
  5. constraint.setName("auth");
  6. constraint.setAuthenticate(true);
  7. constraint.setRoles(new String[]{"user", "admin"});
  8. ConstraintMapping mapping = new ConstraintMapping();
  9. mapping.setPathSpec("ws/v1/*");
  10. mapping.setConstraint(constraint);
  11. securityHandler.setConstraintMappings(Collections.singletonList(mapping));
  12. securityHandler.setAuthenticator(new FormAuthenticator());
  13. securityHandler.setLoginService(new HashLoginService("MyRealm","realm.properties"));
  14. }

其中的realm.properties的内容如下,其格式为:用户名 : 密码 : 角色1:角色2......

jetty: MD5:164c88b302622e17050af52c89945d44,user
admin: CRYPT:adpexzg3FUZAk,server-administrator,content-administrator,admin,user
other: OBF:1xmk1w261u9r1w1c1xmq,user
plain: plain,user
user: password,user

运行如下:

  1. public void run() {
  2. Server server = getServer();
  3. try {
  4. server.start();
  5. server.join();
  6. } catch (Exception e) {
  7. e.printStackTrace();
  8. }
  9. }

上述代码包装过的ServletContextHandler后的情况下,ws/v1/*的所有路径都必须先经过认证之后才能访问。


下面是web页面的Jetty嵌入式代码:

  1. public HandlerWrapper getWebHandler() {
  2. WebAppContext context = new WebAppContext();
  3. context.setContextPath("/");
  4. context.setDescriptor("hugetable-core/src/main/webapp/WEB-INF/web.xml");
  5. context.setResourceBase("hugetable-core/src/main/webapp");
  6. context.setClassLoader(Thread.currentThread().getContextClassLoader());
  7. context.setParentLoaderPriority(true);
  8. return context;
  9. }




声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/124316
推荐阅读
  

闽ICP备14008679号