• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Java User类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Java中io.vertx.ext.auth.User的典型用法代码示例。如果您正苦于以下问题:Java User类的具体用法?Java User怎么用?Java User使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



User类属于io.vertx.ext.auth包,在下文中一共展示了User类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Java代码示例。

示例1: authenticate

import io.vertx.ext.auth.User; //导入依赖的package包/类
@Override
public void authenticate(JsonObject credentials, Handler<AsyncResult<User>> resultHandler) {
    String token = credentials.getString("token");

    httpClient.getAbs("https://graph.facebook.com:443/v2.4/me?access_token=" + token)
            .handler(response ->
                    response.bodyHandler(buffer -> {
                        JsonObject json = new JsonObject(buffer.toString());
                        if (response.statusCode() != 200) {
                            String message = json.getJsonObject("error").getString("message");
                            resultHandler.handle(Future.failedFuture(message));
                        } else {
                            resultHandler.handle(Future.succeededFuture(
                                    new MyUser(Long.parseLong(json.getString("id")),
                                            json.getString("name"),
                                            token)));
                        }
                    }))
            .exceptionHandler(error ->
                    resultHandler.handle(Future.failedFuture(error.getMessage())))
            .end();
}
 
开发者ID:cdelmas,项目名称:microservices-comparison,代码行数:23,代码来源:FacebookOauthTokenVerifier.java


示例2: getContextHandler

import io.vertx.ext.auth.User; //导入依赖的package包/类
private static Handler<RoutingContext> getContextHandler(ContextProvider instance) {

		return context -> {

			if (instance != null) {
				Object provided = instance.provide(context.request());

				if (provided instanceof User) {
					context.setUser((User) provided);
				}

				if (provided instanceof Session) {
					context.setSession((Session) provided);
				}

				if (provided != null) {
					context.data().put(ContextProviderFactory.getContextKey(provided), provided);
				}
			}

			context.next();
		};
	}
 
开发者ID:zandero,项目名称:rest.vertx,代码行数:24,代码来源:RestRouter.java


示例3: in

import io.vertx.ext.auth.User; //导入依赖的package包/类
public static void in(final IpcData data, final Envelop envelop) {
    if (null != envelop) {
        // User
        final User user = envelop.user();
        final JsonObject sendData = new JsonObject();
        if (null != user) {
            sendData.put("user", user.principal());
        }
        // Header
        final MultiMap headers = envelop.headers();
        if (null != headers) {
            final JsonObject headerData = new JsonObject();
            headers.forEach((entry) -> headerData.put(entry.getKey(), entry.getValue()));
            sendData.put("header", headerData);
        }
        // Data
        final Object content = envelop.data();
        sendData.put("data", content);
        sendData.put("config", data.getConfig());
        // Data Prepared finished.
        sendData.put("address", data.getAddress());
        data.setData(sendData.toBuffer());
    }
}
 
开发者ID:silentbalanceyh,项目名称:vertx-zero,代码行数:25,代码来源:DataEncap.java


示例4: authorise

import io.vertx.ext.auth.User; //导入依赖的package包/类
@Override
	protected void authorise(User user, RoutingContext context) {
//		System.out.println("authorise =>"+user.principal().toString());
		((GateUser)user).isAuthorised(authMgr.authProvider,context.request().uri(),  res -> {
	        if (res.succeeded()) {
	           if (res.result()) {
	              context.next();
	           } else {
	              context.fail(HttpStatus.Unauthorized);
	           }
	        } else {
	           context.fail(res.cause());
	        }
	    });
		
	}
 
开发者ID:troopson,项目名称:etagate,代码行数:17,代码来源:GateAuthHandler.java


示例5: fail

import io.vertx.ext.auth.User; //导入依赖的package包/类
private void fail(Future<JsonObject> completeFuture, AsyncResult<User> ar) {
  String errorMessage = ar.cause().getMessage();
  if (errorMessage != null) {
    if (errorMessage.startsWith("Expired JWT")) {
      completeFuture.fail(SystemException.wrap(DefaultErrorCode.EXPIRE_TOKEN, ar.cause())
                                  .set("details", errorMessage));
    } else if (errorMessage.startsWith("Invalid JWT")) {
      completeFuture.fail(SystemException.wrap(DefaultErrorCode.INVALID_TOKEN, ar.cause())
                                  .set("details", errorMessage));
    } else {
      completeFuture.fail(SystemException.wrap(DefaultErrorCode.PERMISSION_DENIED, ar.cause())
                                  .set("details", ar.cause().getMessage()));
    }
  } else {
    completeFuture.fail(SystemException.wrap(DefaultErrorCode.PERMISSION_DENIED, ar.cause())
                                .set("details", ar.cause().getMessage()));
  }
}
 
开发者ID:edgar615,项目名称:direwolves,代码行数:19,代码来源:AuthenticationFilter.java


示例6: extractAuthUserFromMessage

import io.vertx.ext.auth.User; //导入依赖的package包/类
public static User extractAuthUserFromMessage(Message<?> message) {
    User user = null;
    String serializedUser = message.headers().get(SwaggerRouter.AUTH_USER_HEADER_KEY);
    if (serializedUser != null && !serializedUser.isEmpty()) {
        Buffer buffer = Buffer.buffer(serializedUser);
        UserHolder userHolder = new UserHolder();
        userHolder.readFromBuffer(0, buffer);
        user = userHolder.user;
        if (user != null) {
            String authProviderName = message.headers().get(SwaggerRouter.AUTH_PROVIDER_NAME_HEADER_KEY);
            if (authProviderName != null) {
                user.setAuthProvider(getAuthProviderFactory().getAuthProviderByName(authProviderName));
            }
        }
    }
    return user;
}
 
开发者ID:phiz71,项目名称:vertx-swagger,代码行数:18,代码来源:SwaggerRouter.java


示例7: shouldDelegateIsUserInRole

import io.vertx.ext.auth.User; //导入依赖的package包/类
@Test
public void shouldDelegateIsUserInRole() {
    User user = mock(User.class);
    doAnswer(invocation -> {
        String role = invocation.getArgumentAt(0, String.class);
        Handler<AsyncResult<Boolean>> handler = invocation.getArgumentAt(1, Handler.class);
        handler.handle(Future.succeededFuture("USER".equals(role)));
        return user;
    }).when(user).isAuthorised(isA(String.class), isA(Handler.class));
    when(user.principal())
        .thenReturn(new JsonObject().put("username", "marco"))
        .thenReturn(new JsonObject());
    when(routingContext.user()).thenReturn(null).thenReturn(user);
    assertThat(vaadinRequest.isUserInRole("USER")).isFalse();
    assertThat(vaadinRequest.isUserInRole("ADMIN")).isFalse();
    assertThat(vaadinRequest.isUserInRole("USER")).isTrue();
    //assertThat(vaadinRequest.getUserPrincipal().getName()).isNull();
}
 
开发者ID:mcollovati,项目名称:vaadin-vertx-samples,代码行数:19,代码来源:VertxVaadinRequestUT.java


示例8: testBasicAuthFailsWrongCredentials

import io.vertx.ext.auth.User; //导入依赖的package包/类
@SuppressWarnings("unchecked")
@Test
public final void testBasicAuthFailsWrongCredentials(final TestContext context) {
    final Async async = context.async();
    final String encodedUserPass = Base64.getEncoder()
            .encodeToString("[email protected]_TENANT:password123".getBytes(StandardCharsets.UTF_8));

    doAnswer(invocation -> {
        Handler<AsyncResult<User>> resultHandler = invocation.getArgumentAt(1, Handler.class);
        resultHandler.handle(Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_UNAUTHORIZED, "bad credentials")));
        return null;
    }).when(credentialsAuthProvider).authenticate(any(JsonObject.class), any(Handler.class));

    vertx.createHttpClient().put(httpAdapter.getInsecurePort(), HOST, "/somenonexistingroute")
            .putHeader("content-type", HttpUtils.CONTENT_TYPE_JSON)
            .putHeader(AUTHORIZATION_HEADER, "Basic " + encodedUserPass).handler(response -> {
        context.assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, response.statusCode());
        response.bodyHandler(totalBuffer -> {
            async.complete();
        });
    }).exceptionHandler(context::fail).end();
}
 
开发者ID:eclipse,项目名称:hono,代码行数:23,代码来源:VertxBasedHttpProtocolAdapterTest.java


示例9: testBasicAuthSuccess

import io.vertx.ext.auth.User; //导入依赖的package包/类
@SuppressWarnings("unchecked")
@Test
public final void testBasicAuthSuccess(final TestContext context) throws Exception {
    final Async async = context.async();
    final String encodedUserPass = Base64.getEncoder()
            .encodeToString("[email protected]_TENANT:password123".getBytes(StandardCharsets.UTF_8));

    doAnswer(invocation -> {
        Handler<AsyncResult<User>> resultHandler = invocation.getArgumentAt(1, Handler.class);
        resultHandler.handle(Future.succeededFuture(new Device("DEFAULT_TENANT", "device_1")));
        return null;
    }).when(credentialsAuthProvider).authenticate(any(JsonObject.class), any(Handler.class));

    vertx.createHttpClient().get(httpAdapter.getInsecurePort(), HOST, "/somenonexistingroute")
            .putHeader("content-type", HttpUtils.CONTENT_TYPE_JSON)
            .putHeader(AUTHORIZATION_HEADER, "Basic " + encodedUserPass).handler(response -> {
        context.assertEquals(HttpURLConnection.HTTP_NOT_FOUND, response.statusCode());
        response.bodyHandler(totalBuffer -> {
            async.complete();
        });
    }).exceptionHandler(context::fail).end();
}
 
开发者ID:eclipse,项目名称:hono,代码行数:23,代码来源:VertxBasedHttpProtocolAdapterTest.java


示例10: authenticate

import io.vertx.ext.auth.User; //导入依赖的package包/类
@Override
public final void authenticate(final JsonObject authInfo, final Handler<AsyncResult<User>> resultHandler) {

    DeviceCredentials credentials = getCredentials(Objects.requireNonNull(authInfo));
    if (credentials == null) {
        resultHandler.handle(Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_UNAUTHORIZED, "malformed credentials")));
    } else {
        authenticate(credentials, s -> {
            if (s.succeeded()) {
                resultHandler.handle(Future.succeededFuture(s.result()));
            } else {
                resultHandler.handle(Future.failedFuture(s.cause()));
            }
        });
    }
}
 
开发者ID:eclipse,项目名称:hono,代码行数:17,代码来源:CredentialsApiAuthProvider.java


示例11: generateToken

import io.vertx.ext.auth.User; //导入依赖的package包/类
/**
 * Authenticates the user and returns a JWToken if successful.
 *
 * @param username
 *            Username
 * @param password
 *            Password
 * @param resultHandler
 *            Handler to be invoked with the created JWToken
 */
public void generateToken(String username, String password, Handler<AsyncResult<String>> resultHandler) {
	authenticate(username, password, rh -> {
		if (rh.failed()) {
			resultHandler.handle(Future.failedFuture(rh.cause()));
		} else {
			User user = rh.result().getUser();
			String uuid = null;
			if (user instanceof MeshAuthUser) {
				uuid = ((MeshAuthUser) user).getUuid();
			} else {
				uuid = user.principal().getString("uuid");
			}
			JsonObject tokenData = new JsonObject().put(USERID_FIELD_NAME, uuid);
			resultHandler.handle(Future.succeededFuture(jwtProvider.generateToken(tokenData,
					new JWTOptions().setExpiresInSeconds(Mesh.mesh().getOptions().getAuthenticationOptions().getTokenExpirationTime()))));
		}
	});
}
 
开发者ID:gentics,项目名称:mesh,代码行数:29,代码来源:MeshAuthProvider.java


示例12: authenticate

import io.vertx.ext.auth.User; //导入依赖的package包/类
@Override
public void authenticate(JsonObject authInfo, Handler<AsyncResult<User>> resultHandler) {
    String password = environment.getProperty(USERS_PREFIX_KEY + authInfo.getString("username"));

    if (password != null) {
        // Get password from incoming HTTP request
        String presentedPassword = authInfo.getString("password");

        if (password.equals(presentedPassword)) {
            resultHandler.handle(
                    Future.succeededFuture(new io.gravitee.management.services.http.auth.User()));
            return ;
        }
    }

    resultHandler.handle(Future.failedFuture("Unauthorized user"));
}
 
开发者ID:gravitee-io,项目名称:gravitee-management-rest-api,代码行数:18,代码来源:BasicAuthProvider.java


示例13: authenticate

import io.vertx.ext.auth.User; //导入依赖的package包/类
@Override
public void authenticate(JsonObject authInfo, Handler<AsyncResult<User>> resultHandler) {
    String password = environment.getProperty(USERS_PREFIX_KEY + authInfo.getString("username"));

    if (password != null) {
        // Get password from incoming HTTP request
        String presentedPassword = authInfo.getString("password");

        if (password.equals(presentedPassword)) {
            resultHandler.handle(
                    Future.succeededFuture(new io.gravitee.gateway.services.http.auth.User()));
            return ;
        }
    }

    resultHandler.handle(Future.failedFuture("Unauthorized user"));
}
 
开发者ID:gravitee-io,项目名称:gravitee-gateway,代码行数:18,代码来源:BasicAuthProvider.java


示例14: handle

import io.vertx.ext.auth.User; //导入依赖的package包/类
@Override
public void handle(RoutingContext context) {
  User user = context.user();
  if (user != null) {
    authorise(user, context);
    return;
  }
  String apiToken;
  try {
    apiToken = parseApiToken(context.request());
  } catch (BadRequestException bre) {
    context.fail(bre);
    return;
  }
  if (apiToken == null) {
    context.fail(401);
    return;
  }
  doAuth(context, apiToken);
}
 
开发者ID:aesteve,项目名称:nubes,代码行数:21,代码来源:CheckTokenHandler.java


示例15: writeToBuffer

import io.vertx.ext.auth.User; //导入依赖的package包/类
@Override
public void writeToBuffer(Buffer buffer) {
  // try to get the user from the context otherwise fall back to any cached version
  User user = context != null ? context.user() : this.user;
  if (user != null && user instanceof ClusterSerializable) {
    buffer.appendByte((byte)1);
    String className = user.getClass().getCanonicalName();
    if (className == null) {
      throw new IllegalStateException("Cannot serialize " + user.getClass().getName());
    }
    byte[] bytes = className.getBytes(StandardCharsets.UTF_8);
    buffer.appendInt(bytes.length);
    buffer.appendBytes(bytes);
    ClusterSerializable cs = (ClusterSerializable)user;
    cs.writeToBuffer(buffer);
  } else {
    buffer.appendByte((byte)0);
  }
}
 
开发者ID:vert-x3,项目名称:vertx-web,代码行数:20,代码来源:UserHolder.java


示例16: readFromBuffer

import io.vertx.ext.auth.User; //导入依赖的package包/类
@Override
public int readFromBuffer(int pos, Buffer buffer) {
  byte b = buffer.getByte(pos++);
  if (b == (byte)1) {
    int len = buffer.getInt(pos);
    pos += 4;
    byte[] bytes = buffer.getBytes(pos, pos + len);
    pos += len;
    String className = new String(bytes, StandardCharsets.UTF_8);
    try {
      Class clazz = Utils.getClassLoader().loadClass(className);
      ClusterSerializable obj = (ClusterSerializable) clazz.newInstance();
      pos = obj.readFromBuffer(pos, buffer);
      user = (User) obj;
    } catch (Exception e) {
      throw new VertxException(e);
    }
  } else {
    user = null;
  }
  return pos;
}
 
开发者ID:vert-x3,项目名称:vertx-web,代码行数:23,代码来源:UserHolder.java


示例17: authenticate

import io.vertx.ext.auth.User; //导入依赖的package包/类
@Override
public void authenticate(JsonObject authInfo, Handler<AsyncResult<User>> resultHandler) {
  vertx.executeBlocking(fut -> {
    SubjectContext subjectContext = new DefaultSubjectContext();
    Subject subject = securityManager.createSubject(subjectContext);
    String username = authInfo.getString("username");
    String password = authInfo.getString("password");
    AuthenticationToken token = new UsernamePasswordToken(username, password);
    try {
      subject.login(token);
    } catch (AuthenticationException e) {
      throw new VertxException(e);
    }
    fut.complete(new ShiroUser(vertx, securityManager, subject, rolePrefix));
  }, resultHandler);
}
 
开发者ID:vert-x3,项目名称:vertx-auth,代码行数:17,代码来源:ShiroAuthProviderImpl.java


示例18: example4

import io.vertx.ext.auth.User; //导入依赖的package包/类
public void example4(Vertx vertx) {

    // Set the client credentials and the OAuth2 server
    OAuth2ClientOptions credentials = new OAuth2ClientOptions()
        .setClientID("<client-id>")
        .setClientSecret("<client-secret>")
        .setSite("https://api.oauth.com");


    // Initialize the OAuth2 Library
    OAuth2Auth oauth2 = OAuth2Auth.create(vertx, OAuth2FlowType.CLIENT, credentials);

    JsonObject tokenConfig = new JsonObject();

    // Callbacks
    // Save the access token
    oauth2.authenticate(tokenConfig, res -> {
      if (res.failed()) {
        System.err.println("Access Token Error: " + res.cause().getMessage());
      } else {
        // Get the access token object (the authorization code is given from the previous step).
        User token = res.result();
      }
    });
  }
 
开发者ID:vert-x3,项目名称:vertx-auth,代码行数:26,代码来源:AuthOAuth2Examples.java


示例19: getToken

import io.vertx.ext.auth.User; //导入依赖的package包/类
@Test
public void getToken() {
  JsonObject jwt = new JsonObject()
    .put("scope", "https://www.googleapis.com/auth/devstorage.readonly");

  oauth2.authenticate(jwt, res -> {
    if (res.failed()) {
      fail(res.cause().getMessage());
    } else {
      User token = res.result();
      assertNotNull(token);
      assertNotNull(token.principal());
      testComplete();
    }
  });
  await();
}
 
开发者ID:vert-x3,项目名称:vertx-auth,代码行数:18,代码来源:OAuth2AuthJWTTest.java


示例20: example2

import io.vertx.ext.auth.User; //导入依赖的package包/类
public void example2(User user) {

    user.isAuthorised("printers:printer1234", res -> {
      if (res.succeeded()) {

        boolean hasAuthority = res.result();

        if (hasAuthority) {
          System.out.println("User has the authority");
        } else {
          System.out.println("User does not have the authority");
        }

      } else {
        res.cause().printStackTrace();
      }
    });
  }
 
开发者ID:vert-x3,项目名称:vertx-auth,代码行数:19,代码来源:AuthCommonExamples.java



注:本文中的io.vertx.ext.auth.User类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Java TemplateCompiler类代码示例发布时间:2022-05-21
下一篇:
Java Setter类代码示例发布时间:2022-05-21
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap