|
26 | 26 | import org.springframework.security.core.context.SecurityContext; |
27 | 27 | import org.springframework.security.core.context.SecurityContextHolder; |
28 | 28 |
|
| 29 | +import io.grpc.ForwardingServerCallListener.SimpleForwardingServerCallListener; |
29 | 30 | import io.grpc.Metadata; |
30 | 31 | import io.grpc.ServerCall; |
31 | 32 | import io.grpc.ServerCall.Listener; |
@@ -90,7 +91,64 @@ else if (user == null || !user.isAuthenticated()) { |
90 | 91 | throw new BadCredentialsException("not authenticated"); |
91 | 92 | } |
92 | 93 |
|
93 | | - return next.startCall(call, headers); |
| 94 | + SecurityContext currentContext = SecurityContextHolder.getContext(); |
| 95 | + return new SecurityContextClearingListener<>(next.startCall(call, headers), currentContext); |
| 96 | + } |
| 97 | + |
| 98 | + static class SecurityContextClearingListener<ReqT> extends SimpleForwardingServerCallListener<ReqT> { |
| 99 | + |
| 100 | + private final SecurityContext securityContext; |
| 101 | + |
| 102 | + SecurityContextClearingListener(ServerCall.Listener<ReqT> delegate, SecurityContext securityContext) { |
| 103 | + super(delegate); |
| 104 | + this.securityContext = securityContext; |
| 105 | + } |
| 106 | + |
| 107 | + @Override |
| 108 | + public void onMessage(ReqT message) { |
| 109 | + SecurityContextHolder.setContext(this.securityContext); |
| 110 | + try { |
| 111 | + super.onMessage(message); |
| 112 | + } |
| 113 | + finally { |
| 114 | + SecurityContextHolder.clearContext(); |
| 115 | + } |
| 116 | + } |
| 117 | + |
| 118 | + @Override |
| 119 | + public void onHalfClose() { |
| 120 | + SecurityContextHolder.setContext(this.securityContext); |
| 121 | + try { |
| 122 | + super.onHalfClose(); |
| 123 | + } |
| 124 | + finally { |
| 125 | + SecurityContextHolder.clearContext(); |
| 126 | + } |
| 127 | + } |
| 128 | + |
| 129 | + @Override |
| 130 | + public void onReady() { |
| 131 | + SecurityContextHolder.setContext(this.securityContext); |
| 132 | + try { |
| 133 | + super.onReady(); |
| 134 | + } |
| 135 | + finally { |
| 136 | + SecurityContextHolder.clearContext(); |
| 137 | + } |
| 138 | + } |
| 139 | + |
| 140 | + @Override |
| 141 | + public void onCancel() { |
| 142 | + super.onCancel(); |
| 143 | + SecurityContextHolder.clearContext(); |
| 144 | + } |
| 145 | + |
| 146 | + @Override |
| 147 | + public void onComplete() { |
| 148 | + super.onComplete(); |
| 149 | + SecurityContextHolder.clearContext(); |
| 150 | + } |
| 151 | + |
94 | 152 | } |
95 | 153 |
|
96 | 154 | } |
0 commit comments