io.vertx.reactivex.ext.auth.jwt.JWTAuth Java Examples

The following examples show how to use io.vertx.reactivex.ext.auth.jwt.JWTAuth. 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: WikiServer.java    From redpipe with Apache License 2.0 5 votes vote down vote up
@Override
protected AuthProvider setupAuthenticationRoutes() {
	JsonObject keycloackConfig = AppGlobals.get().getConfig().getJsonObject("keycloack");
	OAuth2Auth authWeb = KeycloakAuth.create(AppGlobals.get().getVertx(), keycloackConfig);
	OAuth2Auth authApi = KeycloakAuth.create(AppGlobals.get().getVertx(), OAuth2FlowType.PASSWORD, keycloackConfig);
	
	// FIXME: URL
	OAuth2AuthHandler authHandler = OAuth2AuthHandler.create((OAuth2Auth) authWeb, "http://localhost:9000/callback");
	Router router = AppGlobals.get().getRouter();
	// FIXME: crazy!!
	AuthProvider authProvider = AuthProvider.newInstance(authWeb.getDelegate());
	router.route().handler(UserSessionHandler.create(authProvider));

	authHandler.setupCallback(router.get("/callback"));
	
	JWTAuth jwtAuth = JWTAuth.create(AppGlobals.get().getVertx(), new JWTAuthOptions(new JsonObject()
			.put("keyStore", AppGlobals.get().getConfig().getJsonObject("keystore"))));
	AppGlobals.get().setGlobal(JWTAuth.class, jwtAuth);
	
	JWTAuthHandler jwtAuthHandler = JWTAuthHandler.create(jwtAuth, "/wiki/api/token");

	// FIXME: just use different routers
	router.route().handler(ctx -> {
		if(!ctx.request().uri().startsWith("/wiki/api/"))
			authHandler.handle(ctx);
		else
			jwtAuthHandler.handle(ctx);
	});
	
	return AuthProvider.newInstance(authApi.getDelegate());
}
 
Example #2
Source File: WikiServer.java    From redpipe with Apache License 2.0 5 votes vote down vote up
@Override
protected AuthProvider setupAuthenticationRoutes() {
	AppGlobals globals = AppGlobals.get();
	AuthProvider auth = ShiroAuth.create(globals.getVertx(), new ShiroAuthOptions()
			.setType(ShiroAuthRealmType.PROPERTIES)
			.setConfig(new JsonObject()
					.put("properties_path", globals.getConfig().getString("security_definitions"))));
	
	globals.getRouter().route().handler(UserSessionHandler.create(auth));

	
	JsonObject keyStoreOptions = new JsonObject().put("keyStore", globals.getConfig().getJsonObject("keystore"));
	
	// attempt to load a Key file
	JWTAuth jwtAuth = JWTAuth.create(globals.getVertx(), new JWTAuthOptions(keyStoreOptions));
	JWTAuthHandler jwtAuthHandler = JWTAuthHandler.create(jwtAuth);

	globals.setGlobal(JWTAuth.class, jwtAuth);
	globals.getRouter().route().handler(context -> {
		// only filter if we have a header, otherwise it will try to force auth, regardless if whether
		// we want auth
		if(context.request().getHeader(HttpHeaders.AUTHORIZATION) != null)
			jwtAuthHandler.handle(context);
		else
			context.next();
	});

	return auth;
}
 
Example #3
Source File: RxWebApiContractExamples.java    From vertx-rx with Apache License 2.0 5 votes vote down vote up
public void mainExample(Vertx vertx, Handler<RoutingContext> myValidationFailureHandler, JWTAuth jwtAuth) {
  OpenAPI3RouterFactory
    .rxCreate(vertx, "src/main/resources/petstore.yaml")
    .flatMap(routerFactory -> {
      // Spec loaded with success. router factory contains OpenAPI3RouterFactory
      // Set router factory options.
      RouterFactoryOptions options = new RouterFactoryOptions().setOperationModelKey("openapi_model");
      // Mount the options
      routerFactory.setOptions(options);
      // Add an handler with operationId
      routerFactory.addHandlerByOperationId("listPets", routingContext -> {
        // Handle listPets operation
        routingContext.response().setStatusMessage("Called listPets").end();
      });

      // Add a security handler
      routerFactory.addSecurityHandler("api_key", JWTAuthHandler.create(jwtAuth));

      // Now you have to generate the router
      Router router = routerFactory.getRouter();

      // Now you can use your Router instance
      HttpServer server = vertx.createHttpServer(new HttpServerOptions().setPort(8080).setHost("localhost"));
      return server.requestHandler(router).rxListen();
    })
    .subscribe(httpServer -> {
      // Server up and running
    }, throwable -> {
      // Error during router factory instantiation or http server start
    });
}
 
Example #4
Source File: PublicApiVerticle.java    From vertx-in-action with MIT License 4 votes vote down vote up
@Override
public Completable rxStart() {

  String publicKey;
  String privateKey;
  try {
    publicKey = CryptoHelper.publicKey();
    privateKey = CryptoHelper.privateKey();
  } catch (IOException e) {
    return Completable.error(e);
  }

  jwtAuth = JWTAuth.create(vertx, new JWTAuthOptions()
    .addPubSecKey(new PubSecKeyOptions()
      .setAlgorithm("RS256")
      .setBuffer(publicKey))
    .addPubSecKey(new PubSecKeyOptions()
      .setAlgorithm("RS256")
      .setBuffer(privateKey)));

  Router router = Router.router(vertx);

  Set<String> allowedHeaders = new HashSet<>();
  allowedHeaders.add("x-requested-with");
  allowedHeaders.add("Access-Control-Allow-Origin");
  allowedHeaders.add("origin");
  allowedHeaders.add("Content-Type");
  allowedHeaders.add("accept");
  allowedHeaders.add("Authorization");

  Set<HttpMethod> allowedMethods = new HashSet<>();
  allowedMethods.add(HttpMethod.GET);
  allowedMethods.add(HttpMethod.POST);
  allowedMethods.add(HttpMethod.OPTIONS);
  allowedMethods.add(HttpMethod.PUT);

  router.route().handler(CorsHandler
    .create("*")
    .allowedHeaders(allowedHeaders)
    .allowedMethods(allowedMethods));

  BodyHandler bodyHandler = BodyHandler.create();
  router.post().handler(bodyHandler);
  router.put().handler(bodyHandler);

  String prefix = "/api/v1";
  JWTAuthHandler jwtHandler = JWTAuthHandler.create(jwtAuth);

  // Account
  router.post(prefix + "/register").handler(this::register);
  router.post(prefix + "/token").handler(this::token);

  // Profile
  router.get(prefix + "/:username").handler(jwtHandler).handler(this::checkUser).handler(this::fetchUser);
  router.put(prefix + "/:username").handler(jwtHandler).handler(this::checkUser).handler(this::updateUser);

  // Data
  router.get(prefix + "/:username/total").handler(jwtHandler).handler(this::checkUser).handler(this::totalSteps);
  router.get(prefix + "/:username/:year/:month").handler(jwtHandler).handler(this::checkUser).handler(this::monthlySteps);
  router.get(prefix + "/:username/:year/:month/:day").handler(jwtHandler).handler(this::checkUser).handler(this::dailySteps);

  webClient = WebClient.create(vertx);

  return vertx.createHttpServer()
    .requestHandler(router)
    .rxListen(HTTP_PORT)
    .ignoreElement();
}
 
Example #5
Source File: ApiResource.java    From redpipe with Apache License 2.0 4 votes vote down vote up
@NoAuthFilter
@Produces("text/plain")
@GET
@Path("token")
public Single<Response> token(@HeaderParam("login") String username, 
		@HeaderParam("password") String password,
		@Context JWTAuth jwt,
		@Context AuthProvider auth){
	
	JsonObject creds = new JsonObject()
			.put("username", username)
			.put("password", password);
	return fiber(() -> {
		User user;
		try {
			user = await(auth.rxAuthenticate(creds));
		}catch(VertxException x) {
			return Response.status(Status.FORBIDDEN).build();
		}
		
		boolean canCreate = await(user.rxIsAuthorised("create"));
		boolean canUpdate = await(user.rxIsAuthorised("update"));
		boolean canDelete = await(user.rxIsAuthorised("delete"));
		JsonArray permissions = new JsonArray();
		if(canCreate)
			permissions.add("create");
		if(canUpdate)
			permissions.add("update");
		if(canDelete)
			permissions.add("delete");
		
        String jwtToken = jwt.generateToken(
        		new JsonObject()
        		.put("username", username)
        		.put("permissions", permissions),
                new JWTOptions()
                  .setSubject("Wiki API")
                  .setIssuer("Vert.x"));
        return Response.ok(jwtToken).build();
	});
}
 
Example #6
Source File: ApiResource.java    From redpipe with Apache License 2.0 4 votes vote down vote up
@NoAuthFilter
@Produces("text/plain")
@GET
@Path("token")
public Single<Response> token(@HeaderParam("login") String username, 
		@HeaderParam("password") String password,
		@Context JWTAuth jwt,
		@Context AuthProvider auth){
	
	JsonObject creds = new JsonObject()
			.put("username", username)
			.put("password", password);
	return fiber(() -> {
		User user;
		try {
			user = await(auth.rxAuthenticate(creds));
		}catch(VertxException x) {
			return Response.status(Status.FORBIDDEN).build();
		}
		
		boolean canCreate = await(user.rxIsAuthorised("create"));
		boolean canUpdate = await(user.rxIsAuthorised("update"));
		boolean canDelete = await(user.rxIsAuthorised("delete"));
		JsonArray permissions = new JsonArray();
		if(canCreate)
			permissions.add("create");
		if(canUpdate)
			permissions.add("update");
		if(canDelete)
			permissions.add("delete");
		
        String jwtToken = jwt.generateToken(
        		new JsonObject()
        		.put("username", username)
        		.put("permissions", permissions),
                new JWTOptions()
                  .setSubject("Wiki API")
                  .setIssuer("Vert.x"));
        return Response.ok(jwtToken).build();
	});
}