1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24 package waffle.util;
25
26 import java.util.Base64;
27 import java.util.Locale;
28
29 import javax.servlet.http.HttpServletRequest;
30
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33
34
35
36
37 public class AuthorizationHeader {
38
39
40 private static final Logger LOGGER = LoggerFactory.getLogger(AuthorizationHeader.class);
41
42
43 private final HttpServletRequest request;
44
45
46
47
48
49
50
51 public AuthorizationHeader(final HttpServletRequest httpServletRequest) {
52 this.request = httpServletRequest;
53 }
54
55
56
57
58
59
60 public String getHeader() {
61 return this.request.getHeader("Authorization");
62 }
63
64
65
66
67
68
69 public boolean isNull() {
70 return this.getHeader() == null || this.getHeader().length() == 0;
71 }
72
73
74
75
76
77
78
79
80
81
82
83
84 public String getSecurityPackage() {
85 final String header = this.getHeader();
86
87 if (header == null) {
88 throw new RuntimeException("Missing Authorization: header");
89 }
90
91 final int space = header.indexOf(' ');
92 if (space > 0) {
93 return header.substring(0, space);
94 }
95
96 throw new RuntimeException("Invalid Authorization header: " + header);
97 }
98
99 @Override
100 public String toString() {
101 return this.isNull() ? "<none>" : this.getHeader();
102 }
103
104
105
106
107
108
109 public String getToken() {
110 return this.getHeader().substring(this.getSecurityPackage().length() + 1);
111 }
112
113
114
115
116
117
118 public byte[] getTokenBytes() {
119 try {
120 return Base64.getDecoder().decode(this.getToken());
121 } catch (final IllegalArgumentException e) {
122 AuthorizationHeader.LOGGER.debug("", e);
123 throw new RuntimeException("Invalid authorization header.");
124 }
125 }
126
127
128
129
130
131
132 public boolean isNtlmType1Message() {
133 if (this.isNull()) {
134 return false;
135 }
136
137 final byte[] tokenBytes = this.getTokenBytes();
138 if (!NtlmMessage.isNtlmMessage(tokenBytes)) {
139 return false;
140 }
141
142 return 1 == NtlmMessage.getMessageType(tokenBytes);
143 }
144
145
146
147
148
149
150 public boolean isSPNegTokenInitMessage() {
151
152 if (this.isNull()) {
153 return false;
154 }
155
156 final byte[] tokenBytes = this.getTokenBytes();
157 return SPNegoMessage.isNegTokenInit(tokenBytes);
158 }
159
160
161
162
163
164
165
166
167
168 public boolean isNtlmType1PostAuthorizationHeader() {
169 if (!"POST".equals(this.request.getMethod()) && !"PUT".equals(this.request.getMethod())
170 && !"DELETE".equals(this.request.getMethod())) {
171 return false;
172 }
173
174 if (this.request.getContentLength() != 0) {
175 return false;
176 }
177
178 return this.isNtlmType1Message() || this.isSPNegTokenInitMessage();
179 }
180
181
182
183
184
185
186 public boolean isBearerAuthorizationHeader() {
187 if (this.isNull()) {
188 return false;
189 }
190
191 return this.getSecurityPackage().toUpperCase(Locale.ENGLISH).equalsIgnoreCase("BEARER");
192 }
193 }