1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 package org.waarp.openr66.protocol.http.restv2.resthandlers;
22
23 import io.netty.channel.ChannelHandlerContext;
24 import io.netty.channel.SimpleChannelInboundHandler;
25 import io.netty.handler.codec.http.DefaultFullHttpResponse;
26 import io.netty.handler.codec.http.FullHttpRequest;
27 import io.netty.handler.codec.http.FullHttpResponse;
28 import org.waarp.common.crypto.HmacSha256;
29 import org.waarp.common.logging.WaarpLogger;
30 import org.waarp.common.logging.WaarpLoggerFactory;
31 import org.waarp.openr66.protocol.http.restv2.dbhandlers.AbstractRestDbHandler;
32
33 import static io.netty.channel.ChannelFutureListener.*;
34 import static io.netty.handler.codec.http.HttpResponseStatus.*;
35 import static io.netty.handler.codec.http.HttpVersion.*;
36 import static javax.ws.rs.core.HttpHeaders.*;
37 import static org.waarp.openr66.protocol.http.restv2.RestConstants.*;
38
39
40
41
42
43 public class RestSignatureHandler
44 extends SimpleChannelInboundHandler<FullHttpRequest> {
45
46
47
48
49 private final WaarpLogger logger = WaarpLoggerFactory.getLogger(getClass());
50
51
52
53
54 private final HmacSha256 hmac;
55
56
57
58
59
60
61 public RestSignatureHandler(final HmacSha256 hmac) {
62 this.hmac = hmac;
63 }
64
65
66
67
68
69
70
71
72
73
74
75
76
77 @Override
78 protected void channelRead0(final ChannelHandlerContext ctx,
79 final FullHttpRequest request) {
80
81
82 if (!request.content().isReadable()) {
83 ctx.fireChannelRead(request.retain());
84 return;
85 }
86
87 final String authent = request.headers().get(AUTHORIZATION);
88 final String body = request.content().toString(UTF8_CHARSET);
89 final String URI = request.uri();
90 final String method = request.method().toString();
91 final String sign = request.headers().get(AUTH_SIGNATURE);
92
93 final FullHttpResponse response;
94
95 if (authent == null || sign == null) {
96 response = new DefaultFullHttpResponse(HTTP_1_1, UNAUTHORIZED);
97 ctx.channel().writeAndFlush(response).addListener(CLOSE);
98 return;
99 }
100
101 final String computedHash;
102 try {
103 computedHash = hmac.cryptToHex(authent + body + URI + method);
104 } catch (final Exception e) {
105 logger.error(e);
106 response = new DefaultFullHttpResponse(HTTP_1_1, INTERNAL_SERVER_ERROR);
107 ctx.channel().writeAndFlush(response).addListener(CLOSE);
108 return;
109 }
110
111 if (!computedHash.equals(sign)) {
112 response = new DefaultFullHttpResponse(HTTP_1_1, UNAUTHORIZED);
113 ctx.channel().writeAndFlush(response).addListener(CLOSE);
114 }
115
116 ctx.fireChannelRead(request.retain());
117 }
118
119 }