Guest User

Untitled

a guest
Sep 26th, 2017
24
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.94 KB | None | 0 0
  1. import static spark.Spark.*;
  2.  
  3. import java.util.HashMap;
  4. import java.util.Map;
  5.  
  6. /**
  7. * Example showing a very simple (and stupid) authentication filter that is
  8. * executed before all other resources.
  9. *
  10. * When requesting the resource with e.g.
  11. * http://localhost:4567/hello?user=some&password=guy
  12. * the filter will stop the execution and the client will get a 401 UNAUTHORIZED with the content 'You are not welcome here'
  13. *
  14. * When requesting the resource with e.g.
  15. * http://localhost:4567/hello?user=foo&password=bar
  16. * the filter will accept the request and the request will continue to the /hello route.
  17. *
  18. * Note: There is a second "before filter" that adds a header to the response
  19. * Note: There is also an "after filter" that adds a header to the response
  20. */
  21. public class FilterExample {
  22.  
  23. private static Map<String, String> usernamePasswords = new HashMap<String, String>();
  24.  
  25. public static void main(String[] args) {
  26.  
  27. usernamePasswords.put("foo", "bar");
  28. usernamePasswords.put("admin", "admin");
  29.  
  30. before((request, response) -> {
  31. String user = request.queryParams("user");
  32. String password = request.queryParams("password");
  33.  
  34. String dbPassword = usernamePasswords.get(user);
  35. if (!(password != null && password.equals(dbPassword))) {
  36. halt(401, "You are not welcome here!!!");
  37. }
  38. });
  39.  
  40. before("/hello", (request, response) -> response.header("Foo", "Set by second before filter"));
  41.  
  42. get("/hello", (request, response) -> "Hello World!");
  43.  
  44. after("/hello", (request, response) -> response.header("spark", "added by after-filter"));
  45.  
  46. afterAfter("/hello", (request, response) -> response.header("finally", "executed even if exception is throw"));
  47.  
  48. afterAfter((request, response) -> response.header("finally", "executed after any route even if exception is throw"));
  49. }
  50. }
Add Comment
Please, Sign In to add comment