io.vertx.ext.auth.User Java Examples
The following examples show how to use
io.vertx.ext.auth.User.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SwaggerRouter.java From vertx-swagger with Apache License 2.0 | 6 votes |
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; }
Example #2
Source File: PrivNewFilterTest.java From besu with Apache License 2.0 | 6 votes |
@Test public void multiTenancyCheckFailure() { final User user = mock(User.class); final FilterParameter filterParameter = mock(FilterParameter.class); when(enclavePublicKeyProvider.getEnclaveKey(any())).thenReturn(ENCLAVE_KEY); doThrow(new MultiTenancyValidationException("msg")) .when(privacyController) .verifyPrivacyGroupContainsEnclavePublicKey(eq(PRIVACY_GROUP_ID), eq(ENCLAVE_KEY)); final JsonRpcRequestContext request = privNewFilterRequestWithUser(PRIVACY_GROUP_ID, filterParameter, user); assertThatThrownBy(() -> method.response(request)) .isInstanceOf(MultiTenancyValidationException.class) .hasMessageContaining("msg"); }
Example #3
Source File: OAuth2KeycloakIT.java From vertx-auth with Apache License 2.0 | 6 votes |
@Test public void shouldReloadJWK(TestContext should) { final Async test = should.async(); keycloak.jWKSet(load -> { should.assertTrue(load.succeeded()); keycloak.authenticate(new JsonObject().put("username", "test-user").put("password", "tiger"), authn -> { should.assertTrue(authn.succeeded()); should.assertNotNull(authn.result()); // generate a access token from the user User token = authn.result(); should.assertNotNull(token.attributes().getJsonObject("accessToken")); test.complete(); }); }); }
Example #4
Source File: OAuth2AccessTokenTest.java From vertx-auth with Apache License 2.0 | 6 votes |
@Test public void tokenShouldBeExpiredWhenExpirationDateIsInThePast() { config = oauthConfig; oauth2.authenticate(tokenConfig, res -> { if (res.failed()) { fail(res.cause().getMessage()); } else { User token = res.result(); // hack the token to set the exp (to yesterday) token.principal().put("exp", System.currentTimeMillis() / 1000 - 24 * 60 * 60); assertTrue(token.expired()); testComplete(); } }); await(); }
Example #5
Source File: PrivGetFilterChangesTest.java From besu with Apache License 2.0 | 6 votes |
@Test public void multiTenancyCheckFailure() { final User user = mock(User.class); when(enclavePublicKeyProvider.getEnclaveKey(any())).thenReturn(ENCLAVE_KEY); doThrow(new MultiTenancyValidationException("msg")) .when(privacyController) .verifyPrivacyGroupContainsEnclavePublicKey(eq(PRIVACY_GROUP_ID), eq(ENCLAVE_KEY)); final JsonRpcRequestContext request = privGetFilterChangesRequestWithUser(PRIVACY_GROUP_ID, FILTER_ID, user); assertThatThrownBy(() -> method.response(request)) .isInstanceOf(MultiTenancyValidationException.class) .hasMessageContaining("msg"); }
Example #6
Source File: MongoAuthImpl.java From vertx-auth with Apache License 2.0 | 6 votes |
@Override public void insertUser(String username, String password, List<String> roles, List<String> permissions, Handler<AsyncResult<String>> resultHandler) { JsonObject principal = new JsonObject(); principal.put(getUsernameField(), username); if (roles != null) { principal.put(mongoAuthorizationOptions.getRoleField(), new JsonArray(roles)); } if (permissions != null) { principal.put(mongoAuthorizationOptions.getPermissionField(), new JsonArray(permissions)); } if (getHashStrategy().getSaltStyle() == HashSaltStyle.COLUMN) { principal.put(getSaltField(), DefaultHashStrategy.generateSalt()); } User user = createUser(principal); String cryptPassword = getHashStrategy().computeHash(password, user); principal.put(getPasswordField(), cryptPassword); mongoClient.save(getCollectionName(), user.principal(), resultHandler); }
Example #7
Source File: CustomAuthHandlerTest.java From vertx-web with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") @Test public void testCredentialsValidationErrorPropagation() throws Exception { Handler<RoutingContext> handler = rc -> { fail("should not get here"); rc.response().end("Welcome to the protected resource!"); }; Throwable rootCause = new IllegalArgumentException("validation of credentials failed"); AuthenticationProvider authProvider = mock(AuthenticationProvider.class); doAnswer(invocation -> { final Handler<AsyncResult<User>> resultHandler = invocation.getArgument(1); resultHandler.handle(Future.failedFuture(rootCause)); return null; }).when(authProvider).authenticate(any(Credentials.class), any(Handler.class)); router.route("/protected/*").handler(newAuthHandler(authProvider, exception -> { assertTrue(exception instanceof HttpStatusException); assertEquals(rootCause, exception.getCause()); })); router.route("/protected/somepage").handler(handler); testRequest(HttpMethod.GET, "/protected/somepage", 401, "Unauthorized"); }
Example #8
Source File: OAuth2AuthJWTTest.java From vertx-auth with Apache License 2.0 | 6 votes |
@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()); } else { User token = res.result(); assertNotNull(token); assertNotNull(token.principal()); testComplete(); } }); await(); }
Example #9
Source File: ClientVerticle.java From VX-API-Gateway with MIT License | 6 votes |
/** * 权限认证 * * @param rct */ public void staticAuth(RoutingContext rct) { User user = rct.user(); if (user == null) { rct.response().end(ResultFormat.formatAsZero(HTTPStatusCodeMsgEnum.C401)); } else { user.isAuthorized(VxApiRolesConstant.READ, res -> { if (res.succeeded()) { if (res.result()) { rct.next(); } else { rct.response().end(ResultFormat.formatAsZero(HTTPStatusCodeMsgEnum.C401)); } } else { rct.response().end(ResultFormat.format(HTTPStatusCodeMsgEnum.C500, res.cause().getMessage())); } }); } }
Example #10
Source File: MySQLTest.java From vertx-auth with Apache License 2.0 | 6 votes |
@Test public void testAuthoriseHasRole(TestContext should) { final Async test = should.async(); JsonObject authInfo = new JsonObject(); authInfo.put("username", "lopus").put("password", "secret"); AuthenticationProvider authn = SqlAuthentication.create(mysql); authn.authenticate(authInfo, authenticate -> { should.assertTrue(authenticate.succeeded()); final User user = authenticate.result(); should.assertNotNull(user); AuthorizationProvider authz = SqlAuthorization.create(mysql); authz.getAuthorizations(user, getAuthorizations -> { should.assertTrue(getAuthorizations.succeeded()); // attest should.assertTrue(RoleBasedAuthorization.create("dev").match(user)); test.complete(); }); }); }
Example #11
Source File: Oauth2TokenScopeTest.java From vertx-auth with Apache License 2.0 | 6 votes |
/** * Token scopes are checked and must be valid. * Scopes are retrieved from the JWT itself. * JWT generated in HS256 with vertx as shared secret. */ @Test public void tokenIsValid() { config = new JsonObject() .put("token_type", "Bearer") .put("access_token", JWT) .put("token", JWT); oauthConfig .addPubSecKey(new PubSecKeyOptions().setAlgorithm("HS256").setBuffer("vertx").setSymmetric(true)) .setJWTOptions(new JWTOptions().addScope("scopeA").addScope("scopeB")); oauth2 = OAuth2Auth.create(vertx, oauthConfig); oauth2.authenticate(config, res -> { if (res.failed()) { fail(res.cause()); } else { User token = res.result(); assertFalse(token.expired()); testComplete(); } }); await(); }
Example #12
Source File: OAuth2AccessTokenTest.java From vertx-auth with Apache License 2.0 | 6 votes |
@Test public void shouldRevokeAToken() { config = oauthConfig; oauth2.authenticate(tokenConfig, res -> { if (res.failed()) { fail(res.cause().getMessage()); } else { User token = res.result(); // refresh the token config = revokeConfig; oauth2.revoke(token, "refresh_token", v -> { if (v.failed()) { fail(v.cause().getMessage()); } else { testComplete(); } }); } }); await(); }
Example #13
Source File: VertxBasedHttpProtocolAdapterTest.java From hono with Eclipse Public License 2.0 | 6 votes |
/** * Verifies that a request to upload telemetry data using POST fails * with a 503 status code if the credentials on record cannot be retrieved. * * @param ctx The vert.x test context. */ @SuppressWarnings("unchecked") @Test public void testPostTelemetryFailsForUnreachableCredentialsService(final VertxTestContext ctx) { doAnswer(invocation -> { final Handler<AsyncResult<User>> resultHandler = invocation.getArgument(1); resultHandler.handle(Future.failedFuture(new ServerErrorException(HttpURLConnection.HTTP_UNAVAILABLE, "service down"))); return null; }).when(usernamePasswordAuthProvider).authenticate(any(JsonObject.class), any(Handler.class)); httpClient.post("/telemetry") .putHeader(HttpHeaders.CONTENT_TYPE.toString(), HttpUtils.CONTENT_TYPE_JSON) .basicAuthentication("testuser@DEFAULT_TENANT", "password123") .expect(ResponsePredicate.status(HttpURLConnection.HTTP_UNAVAILABLE)) .sendJsonObject(new JsonObject(), ctx.completing()); }
Example #14
Source File: UserHolder.java From vertx-web with Apache License 2.0 | 5 votes |
@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); if (!ClusterSerializable.class.isAssignableFrom(clazz)) { throw new ClassCastException(className + " is not ClusterSerializable"); } ClusterSerializable obj = (ClusterSerializable) clazz.getDeclaredConstructor().newInstance(); pos = obj.readFromBuffer(pos, buffer); synchronized (this) { user = (User) obj; context = null; } } catch (Exception e) { throw new VertxException(e); } } else { synchronized (this) { user = null; context = null; } } return pos; }
Example #15
Source File: JsonRpcHttpServiceLoginTest.java From besu with Apache License 2.0 | 5 votes |
@Test public void loginWithGoodCredentials() throws IOException { final RequestBody body = RequestBody.create(JSON, "{\"username\":\"user\",\"password\":\"pegasys\"}"); final Request request = new Request.Builder().post(body).url(baseUrl + "/login").build(); try (final Response resp = client.newCall(request).execute()) { assertThat(resp.code()).isEqualTo(200); assertThat(resp.message()).isEqualTo("OK"); assertThat(resp.body().contentType()).isNotNull(); assertThat(resp.body().contentType().type()).isEqualTo("application"); assertThat(resp.body().contentType().subtype()).isEqualTo("json"); final String bodyString = resp.body().string(); assertThat(bodyString).isNotNull(); assertThat(bodyString).isNotBlank(); final JsonObject respBody = new JsonObject(bodyString); final String token = respBody.getString("token"); assertThat(token).isNotNull(); jwtAuth.authenticate( new JsonObject().put("jwt", token), (r) -> { assertThat(r.succeeded()).isTrue(); final User user = r.result(); user.isAuthorized( "noauths", (authed) -> { assertThat(authed.succeeded()).isTrue(); assertThat(authed.result()).isFalse(); }); }); } }
Example #16
Source File: AuthMongoExamples.java From vertx-auth with Apache License 2.0 | 5 votes |
public void example3(User user, MongoAuthorization mongoAuthZ) { mongoAuthZ.getAuthorizations(user) .onSuccess(v -> { if (PermissionBasedAuthorization.create("commit_code").match(user)) { // Has permission! } }); }
Example #17
Source File: WebSocketRequestHandler.java From besu with Apache License 2.0 | 5 votes |
public void handle( final Optional<AuthenticationService> authenticationService, final String id, final String payload, final Optional<User> user) { vertx.executeBlocking( executeHandler(authenticationService, id, payload, user), false, resultHandler(id)); }
Example #18
Source File: OAuth2PasswordTest.java From vertx-auth with Apache License 2.0 | 5 votes |
@Test public void getToken() { config = oauthConfig; oauth2.authenticate(tokenConfig, res -> { if (res.failed()) { fail(res.cause().getMessage()); } else { User token = res.result(); assertNotNull(token); assertNotNull(token.principal()); testComplete(); } }); await(); }
Example #19
Source File: UserAuthProviderImpl.java From graviteeio-access-management with Apache License 2.0 | 5 votes |
@Override public void authenticate(RoutingContext context, JsonObject authInfo, Handler<AsyncResult<User>> handler) { String username = authInfo.getString(USERNAME_PARAMETER); String password = authInfo.getString(PASSWORD_PARAMETER); String clientId = authInfo.getString(Parameters.CLIENT_ID); String ipAddress = authInfo.getString(Claims.ip_address); String userAgent = authInfo.getString(Claims.user_agent); parseClient(clientId, parseClientHandler -> { if (parseClientHandler.failed()) { logger.error("Authentication failure: unable to retrieve client " + clientId, parseClientHandler.cause()); handler.handle(Future.failedFuture(parseClientHandler.cause())); return; } // retrieve the client (application) final Client client = parseClientHandler.result(); // end user authentication SimpleAuthenticationContext authenticationContext = new SimpleAuthenticationContext(new VertxHttpServerRequest(context.request())); final Authentication authentication = new EndUserAuthentication(username, password, authenticationContext); authenticationContext.set(Claims.ip_address, ipAddress); authenticationContext.set(Claims.user_agent, userAgent); authenticationContext.set(Claims.domain, client.getDomain()); userAuthenticationManager.authenticate(client, authentication) .subscribe( user -> handler.handle(Future.succeededFuture(new io.gravitee.am.gateway.handler.common.vertx.web.auth.user.User(user))), error -> handler.handle(Future.failedFuture(error)) ); }); }
Example #20
Source File: DefaultHashStrategy.java From vertx-auth with Apache License 2.0 | 5 votes |
@Override public String computeHash(String password, User user) { switch (saltStyle) { case NO_SALT: return password; case COLUMN: case EXTERNAL: String salt = getSalt(user); return computeHash(password, salt); default: throw new UnsupportedOperationException("Not existing, saltstyle " + saltStyle); } }
Example #21
Source File: SockJSSocketBase.java From vertx-web with Apache License 2.0 | 5 votes |
protected SockJSSocketBase(Vertx vertx, Session webSession, User webUser) { this.vertx = vertx; this.webSession = webSession; this.webUser = webUser; Handler<Message<Buffer>> writeHandler = buff -> write(buff.body()); this.writeHandlerID = UUID.randomUUID().toString(); this.registration = vertx.eventBus().<Buffer>consumer(writeHandlerID).handler(writeHandler); }
Example #22
Source File: ClientVerticle.java From VX-API-Gateway with MIT License | 5 votes |
/** * 删除应用程序 * * @param rct */ public void delAPP(RoutingContext rct) { String name = rct.request().getParam("name"); HttpServerResponse response = rct.response().putHeader(CONTENT_TYPE, CONTENT_VALUE_JSON_UTF8); if (StrUtil.isNullOrEmpty(name)) { response.end(ResultFormat.formatAsZero(HTTPStatusCodeMsgEnum.C1404)); } else { User user = rct.user(); user.isAuthorized(VxApiRolesConstant.WRITE, res -> { if (res.succeeded()) { JsonObject config = new JsonObject().put("appName", name); vertx.eventBus().send(thisVertxName + VxApiEventBusAddressConstant.DEPLOY_APP_UNDEPLOY, config); if (res.result()) { // 将应用暂停 if (vertx.isClustered()) { vertx.eventBus().publish(VxApiEventBusAddressConstant.DEPLOY_APP_UNDEPLOY, config.copy().put("thisVertxName", thisVertxName)); LOG.info("执行删除应用-->广播告诉集群环境中暂停应用:" + name); } LOG.info(MessageFormat.format("[user : {0}] 执行删除应用{1}...", rct.session().<String>get("userName"), name)); vertx.eventBus().<Integer>send(thisVertxName + VxApiEventBusAddressConstant.DEL_APP, name, cres -> { if (cres.succeeded()) { response.end(ResultFormat.format(HTTPStatusCodeMsgEnum.C200, cres.result().body())); LOG.info(MessageFormat.format("[user : {0}] 执行删除应用:{2}-->结果: {1}", rct.session().<String>get("userName"), cres.result().body(), name)); } else { LOG.error(MessageFormat.format("[user : {0}] 执行删除应用:{2}-->失败:{1}", rct.session().get("userName"), cres.cause(), name)); response.end(ResultFormat.format(HTTPStatusCodeMsgEnum.C500, cres.cause().toString())); } }); } else { LOG.error(MessageFormat.format("[user : {0}] 执行删除应用:{1}-->失败:未授权或者无权限", rct.session().get("userName"), name)); response.end(ResultFormat.formatAsZero(HTTPStatusCodeMsgEnum.C401)); } } else { LOG.error(MessageFormat.format("[user : {0}] 执行删除应用:{2}-->失败:{1}", rct.session().get("userName"), res.cause(), name)); response.end(ResultFormat.format(HTTPStatusCodeMsgEnum.C500, res.cause().getMessage())); } }); } }
Example #23
Source File: VertxVaadinRequestUT.java From vertx-vaadin with MIT License | 5 votes |
@Test public void shouldDelegateGetPrincipal() { User user = mock(User.class); when(user.principal()) .thenReturn(new JsonObject().put("username", "marco")) .thenReturn(new JsonObject()); when(routingContext.user()).thenReturn(null, user); assertThat(vaadinRequest.getUserPrincipal()).isNull(); assertThat(vaadinRequest.getUserPrincipal().getName()).isEqualTo("marco"); assertThat(vaadinRequest.getUserPrincipal().getName()).isNull(); }
Example #24
Source File: ShiroAuthProviderTestBase.java From vertx-auth with Apache License 2.0 | 5 votes |
private void loginThen(Consumer<User> runner) throws Exception { JsonObject authInfo = new JsonObject().put("username", "tim").put("password", "sausages"); authProvider.authenticate(authInfo, onSuccess(user -> { assertNotNull(user); runner.accept(user); })); }
Example #25
Source File: VertxVaadinRequestUT.java From vertx-vaadin with MIT License | 5 votes |
@Test public void shouldDelegateGetPrincipal() { User user = mock(User.class); when(user.principal()) .thenReturn(new JsonObject().put("username", "marco")) .thenReturn(new JsonObject()); when(routingContext.user()).thenReturn(null).thenReturn(user); assertThat(vaadinRequest.getUserPrincipal()).isNull(); assertThat(vaadinRequest.getUserPrincipal().getName()).isEqualTo("marco"); assertThat(vaadinRequest.getUserPrincipal().getName()).isNull(); }
Example #26
Source File: AccessTokenImpl.java From vertx-auth with Apache License 2.0 | 5 votes |
@Override public AccessToken refresh(Handler<AsyncResult<Void>> callback) { oAuth2Auth.refresh(this, refresh -> { if (refresh.failed()) { callback.handle(Future.failedFuture(refresh.cause())); } else { User user = refresh.result(); // merge properties attributes().mergeIn(user.attributes()); principal().mergeIn(user.principal()); callback.handle(Future.succeededFuture()); } }); return this; }
Example #27
Source File: MicroProfileTest.java From vertx-auth with Apache License 2.0 | 5 votes |
@Test public void itShouldAssertThatTokenHasRoles(TestContext should) { final Async test = should.async(); User user = User.create(new JsonObject( "{\n" + " \"iss\": \"https://server.example.com\",\n" + " \"aud\": \"s6BhdRkqt3\",\n" + " \"jti\": \"a-123\",\n" + " \"exp\": 999999999999,\n" + " \"iat\": 1311280970,\n" + " \"sub\": \"24400320\",\n" + " \"upn\": \"[email protected]\",\n" + " \"groups\": [\"red-group\", \"green-group\", \"admin-group\", \"admin\"]\n" + "}")); // assert that the user has the following roles: final List<String> roles = Arrays.asList("red-group", "green-group", "admin-group", "admin"); MicroProfileAuthorization.create().getAuthorizations(user, call -> { should.assertTrue(call.succeeded()); for (String role : roles) { should.assertTrue(RoleBasedAuthorization.create(role).match(user)); } test.complete(); }); }
Example #28
Source File: ClientVerticle.java From VX-API-Gateway with MIT License | 5 votes |
/** * 更新一个API * * @param rct */ public void updtAPI(RoutingContext rct) { User user = rct.user(); HttpServerResponse response = rct.response().putHeader(CONTENT_TYPE, CONTENT_VALUE_JSON_UTF8); user.isAuthorized(VxApiRolesConstant.WRITE, res -> { if (res.succeeded()) { if (res.result()) { LOG.info(MessageFormat.format("[user : {0}] 执行修改应用...", rct.session().<String>get("userName"))); VxApisDTO dto = VxApisDTO.fromJson(rct.getBodyAsJson()); if (dto.getApiCreateTime() == null) { dto.setApiCreateTime(Instant.now()); } JsonObject param = new JsonObject(); param.put("apiName", dto.getApiName()); param.put("api", dto.toJson()); vertx.eventBus().<Integer>send(thisVertxName + VxApiEventBusAddressConstant.UPDT_API, param, cres -> { if (cres.succeeded()) { response.end(ResultFormat.format(HTTPStatusCodeMsgEnum.C200, cres.result().body())); LOG.info(MessageFormat.format("[user : {0}] 执行修改API:{2}-->结果: {1}", rct.session().<String>get("userName"), cres.result().body(), dto.getApiName())); } else { LOG.error(MessageFormat.format("[user : {0}] 执行修改API-->失败:{1}", rct.session().get("userName"), cres.cause())); response.end(ResultFormat.format(HTTPStatusCodeMsgEnum.C500, cres.cause().toString())); } }); } else { LOG.error(MessageFormat.format("[user : {0}] 执行修改API-->失败:未授权或者无权利", rct.session().get("userName"))); response.end(ResultFormat.formatAsZero(HTTPStatusCodeMsgEnum.C401)); } } else { LOG.error(MessageFormat.format("[user : {0}] 执行修改API-->失败:{1}", rct.session().get("userName"), res.cause())); response.end(ResultFormat.format(HTTPStatusCodeMsgEnum.C500, res.cause().getMessage())); } }); }
Example #29
Source File: AuthJWTExamples.java From vertx-auth with Apache License 2.0 | 5 votes |
public void example13(User user) { AuthorizationProvider authz = MicroProfileAuthorization.create(); authz.getAuthorizations(user) .onSuccess(v -> { // and now we can perform checks as needed if (PermissionBasedAuthorization.create("create-report").match(user)) { // Yes the user can create reports } }); }
Example #30
Source File: AuthShiroExamples.java From vertx-auth with Apache License 2.0 | 5 votes |
public void example6(User user) { user.isAuthorized("role:manager", res -> { if (res.succeeded()) { boolean hasRole = res.result(); } else { // Failed to } }); }