Example showing a very simple (and stupid) authentication filter that is executed before all other resources. When requesting the resource with e.g. http://localhost:4567/hello?user=some&password=guy the filter will stop the execution and the client will get a 401 UNAUTHORIZED with the content 'You
| 43 | * @author Per Wendel |
| 44 | */ |
| 45 | public class FilterExample { |
| 46 | |
| 47 | private static Map<String, String> usernamePasswords = new HashMap<>(); |
| 48 | |
| 49 | public static void main(String[] args) { |
| 50 | |
| 51 | usernamePasswords.put("foo", "bar"); |
| 52 | usernamePasswords.put("admin", "admin"); |
| 53 | |
| 54 | before(new Filter() { |
| 55 | @Override |
| 56 | public void handle(Request request, Response response) { |
| 57 | String user = request.queryParams("user"); |
| 58 | String password = request.queryParams("password"); |
| 59 | |
| 60 | String dbPassword = usernamePasswords.get(user); |
| 61 | if (!(password != null && password.equals(dbPassword))) { |
| 62 | halt(401, "You are not welcome here!!!"); |
| 63 | } |
| 64 | } |
| 65 | }); |
| 66 | |
| 67 | before("/hello", (request, response) -> { |
| 68 | response.header("Foo", "Set by second before filter"); |
| 69 | }); |
| 70 | |
| 71 | get("/hello", (request, response) -> { |
| 72 | return "Hello World!"; |
| 73 | }); |
| 74 | |
| 75 | after("/hello", (request, response) -> { |
| 76 | response.header("spark", "added by after-filter"); |
| 77 | }); |
| 78 | |
| 79 | } |
| 80 | } |
nothing calls this directly
no outgoing calls
no test coverage detected