1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.mycore.restapi.v1.utils;
19
20 import java.util.LinkedHashMap;
21 import java.util.Map;
22 import java.util.Optional;
23
24 import org.glassfish.jersey.server.ServerProperties;
25
26 import jakarta.ws.rs.core.Application;
27
28
29
30
31
32
33 public class MCRRestAPIUtil {
34 public static String getWWWAuthenticateHeader(String s,
35 Map<String, String> attributes, Application app) {
36 LinkedHashMap<String, String> attrMap = new LinkedHashMap<>();
37 String realm = app.getProperties()
38 .getOrDefault(ServerProperties.APPLICATION_NAME, "REST API")
39 .toString();
40 attrMap.put("realm", realm);
41 Optional.ofNullable(attributes).ifPresent(attrMap::putAll);
42 StringBuilder b = new StringBuilder();
43 attrMap.entrySet().stream()
44 .forEach(e -> appendFieldValue(b, e.getKey(), e.getValue()));
45 b.insert(0, " ");
46 return Optional.ofNullable(s).orElse("Basic") + b;
47 }
48
49 private static void appendField(StringBuilder b, String field) {
50 if (b.length() > 0) {
51 b.append(", ");
52 }
53 b.append(field);
54 }
55
56 private static void appendValue(StringBuilder b, String value) {
57 for (char c : value.toCharArray()) {
58 if ((c < 0x20) || (c == 0x22) || (c == 0x5c) || (c > 0x7e)) {
59 b.append(' ');
60 } else {
61 b.append(c);
62 }
63 }
64 }
65
66 private static void appendFieldValue(StringBuilder b, String field, String value) {
67 appendField(b, field);
68 if (value != null && !value.isEmpty()) {
69 b.append("=\"");
70 appendValue(b, value);
71 b.append('\"');
72 }
73 }
74
75 }