-
Notifications
You must be signed in to change notification settings - Fork 863
Add an interceptor to support AuthenticationManagerResolver #1034
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
mehrabisajad
wants to merge
14
commits into
grpc-ecosystem:master
Choose a base branch
from
mehrabisajad:support-AuthenticationManagerResolver
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 2 commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
13295e3
Add an interceptor to support AuthenticationManagerResolver
mehrabisajad 4f73dcc
Create an abstract class for AuthenticatingServerInterceptor and use …
mehrabisajad 802ad1f
Add test for ManagerResolverAuthenticatingServerInterceptor and refac…
mehrabisajad 9a39d9b
Refactor using spotlessApply and Add new autoconfiguration
mehrabisajad 276ec90
Merge branch 'master' into support-AuthenticationManagerResolver
ST-DDT 23f5fa1
Merge AutoConfig and Edit AuthenticationManagerResolver behavior
mehrabisajad 18bd3e2
Merge branch 'master' into support-AuthenticationManagerResolver
mehrabisajad a5904ab
Merge branch 'master' into support-AuthenticationManagerResolver
mehrabisajad 5c718a0
Merge branch 'master' into support-AuthenticationManagerResolver
ST-DDT 9305837
Update grpc-server-spring-boot-starter/src/main/java/net/devh/boot/gr…
ST-DDT 4a754c2
Update grpc-server-spring-boot-starter/src/main/java/net/devh/boot/gr…
ST-DDT 58b356e
Remove unnecessary Autowired annotation
mehrabisajad 5bbb550
Merge branch 'master' into support-AuthenticationManagerResolver
ST-DDT 0c863e8
Remove unused import statement
mehrabisajad File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -25,13 +25,16 @@ | |
import org.springframework.security.access.AccessDecisionManager; | ||
import org.springframework.security.access.AccessDeniedException; | ||
import org.springframework.security.authentication.AuthenticationManager; | ||
import org.springframework.security.authentication.AuthenticationManagerResolver; | ||
import org.springframework.security.core.AuthenticationException; | ||
|
||
import net.devh.boot.grpc.server.security.authentication.GrpcAuthenticationReader; | ||
import net.devh.boot.grpc.server.security.check.GrpcSecurityMetadataSource; | ||
import net.devh.boot.grpc.server.security.interceptors.AuthenticatingServerInterceptor; | ||
import net.devh.boot.grpc.server.security.interceptors.AuthorizationCheckingServerInterceptor; | ||
import net.devh.boot.grpc.server.security.interceptors.DefaultAuthenticatingServerInterceptor; | ||
import net.devh.boot.grpc.server.security.interceptors.GrpcServerRequest; | ||
import net.devh.boot.grpc.server.security.interceptors.ManagerResolverAuthenticatingServerInterceptor; | ||
import net.devh.boot.grpc.server.security.interceptors.ExceptionTranslatingServerInterceptor; | ||
|
||
/** | ||
|
@@ -59,7 +62,6 @@ | |
* @author Daniel Theuke ([email protected]) | ||
*/ | ||
@Configuration(proxyBeanMethods = false) | ||
@ConditionalOnBean(AuthenticationManager.class) | ||
@AutoConfigureAfter(SecurityAutoConfiguration.class) | ||
public class GrpcServerSecurityAutoConfiguration { | ||
|
||
|
@@ -83,13 +85,30 @@ public ExceptionTranslatingServerInterceptor exceptionTranslatingServerIntercept | |
* @return The authenticatingServerInterceptor bean. | ||
*/ | ||
@Bean | ||
@ConditionalOnBean(AuthenticationManager.class) | ||
@ConditionalOnMissingBean(AuthenticatingServerInterceptor.class) | ||
public DefaultAuthenticatingServerInterceptor authenticatingServerInterceptor( | ||
final AuthenticationManager authenticationManager, | ||
final GrpcAuthenticationReader authenticationReader) { | ||
return new DefaultAuthenticatingServerInterceptor(authenticationManager, authenticationReader); | ||
} | ||
|
||
/** | ||
* The security interceptor that handles the authentication of requests. | ||
* | ||
* @param grpcAuthenticationManagerResolver The authentication manager resolver used to verify the credentials. | ||
* @param authenticationReader The authentication reader used to extract the credentials from the call. | ||
* @return The authenticatingServerInterceptor bean. | ||
*/ | ||
@Bean | ||
@ConditionalOnBean(parameterizedContainer = AuthenticationManagerResolver.class, value = GrpcServerRequest.class) | ||
@ConditionalOnMissingBean(AuthenticatingServerInterceptor.class) | ||
public ManagerResolverAuthenticatingServerInterceptor managerResolverAuthenticatingServerInterceptor( | ||
final AuthenticationManagerResolver<GrpcServerRequest> grpcAuthenticationManagerResolver, | ||
final GrpcAuthenticationReader authenticationReader) { | ||
return new ManagerResolverAuthenticatingServerInterceptor(grpcAuthenticationManagerResolver, authenticationReader); | ||
} | ||
|
||
/** | ||
* The security interceptor that handles the authorization of requests. | ||
* | ||
|
259 changes: 259 additions & 0 deletions
259
.../devh/boot/grpc/server/security/interceptors/AbstractAuthenticatingServerInterceptor.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,259 @@ | ||
/* | ||
* Copyright (c) 2016-2023 The gRPC-Spring Authors | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
package net.devh.boot.grpc.server.security.interceptors; | ||
|
||
import io.grpc.*; | ||
import lombok.extern.slf4j.Slf4j; | ||
import net.devh.boot.grpc.server.security.authentication.GrpcAuthenticationReader; | ||
import org.springframework.beans.factory.annotation.Autowired; | ||
import org.springframework.security.access.AccessDeniedException; | ||
import org.springframework.security.authentication.*; | ||
import org.springframework.security.core.Authentication; | ||
import org.springframework.security.core.AuthenticationException; | ||
import org.springframework.security.core.context.SecurityContext; | ||
import org.springframework.security.core.context.SecurityContextHolder; | ||
|
||
import static java.util.Objects.requireNonNull; | ||
|
||
|
||
/** | ||
* A server interceptor that tries to {@link GrpcAuthenticationReader read} the credentials from the client and | ||
* {@link AuthenticationManager#authenticate(Authentication) authenticate} them. This interceptor sets the | ||
* authentication to both grpc's {@link Context} and {@link SecurityContextHolder}. | ||
* | ||
* <p> | ||
* This works similar to the {@code org.springframework.security.web.authentication.AuthenticationFilter}. | ||
* </p> | ||
* | ||
* <p> | ||
* <b>Note:</b> This interceptor works similar to | ||
* {@link Contexts#interceptCall(Context, ServerCall, Metadata, ServerCallHandler)}. | ||
* </p> | ||
* | ||
*/ | ||
@Slf4j | ||
public abstract class AbstractAuthenticatingServerInterceptor implements AuthenticatingServerInterceptor { | ||
|
||
private final GrpcAuthenticationReader grpcAuthenticationReader; | ||
|
||
/** | ||
* Creates a new DefaultAuthenticatingServerInterceptor with the given authentication manager and reader. | ||
* | ||
* @param authenticationReader The authentication reader used to extract the credentials from the call. | ||
*/ | ||
@Autowired | ||
ST-DDT marked this conversation as resolved.
Show resolved
Hide resolved
|
||
protected AbstractAuthenticatingServerInterceptor(final GrpcAuthenticationReader authenticationReader) { | ||
this.grpcAuthenticationReader = requireNonNull(authenticationReader, "authenticationReader"); | ||
} | ||
|
||
@Override | ||
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(final ServerCall<ReqT, RespT> call, | ||
final Metadata headers, final ServerCallHandler<ReqT, RespT> next) { | ||
Authentication authentication; | ||
try { | ||
authentication = this.grpcAuthenticationReader.readAuthentication(call, headers); | ||
} catch (final AuthenticationException e) { | ||
log.debug("Failed to read authentication: {}", e.getMessage()); | ||
throw e; | ||
} | ||
if (authentication == null) { | ||
log.debug("No credentials found: Continuing unauthenticated"); | ||
try { | ||
return next.startCall(call, headers); | ||
} catch (final AccessDeniedException e) { | ||
throw newNoCredentialsException(e); | ||
} | ||
} | ||
if (authentication.getDetails() == null && authentication instanceof AbstractAuthenticationToken) { | ||
// Append call attributes to the authentication request. | ||
// This gives the AuthenticationManager access to information like remote and local address. | ||
// It can then decide whether it wants to use its own user details or the attributes. | ||
((AbstractAuthenticationToken) authentication).setDetails(call.getAttributes()); | ||
} | ||
log.debug("Credentials found: Authenticating '{}'", authentication.getName()); | ||
|
||
AuthenticationManager authenticationManager = this.getAuthenticationManager(call, headers); | ||
ST-DDT marked this conversation as resolved.
Show resolved
Hide resolved
|
||
if (authenticationManager == null) { | ||
log.debug("No authentication manager found: Continuing unauthenticated"); | ||
try { | ||
return next.startCall(call, headers); | ||
} catch (final AccessDeniedException e) { | ||
throw newNoCredentialsException(e); | ||
} | ||
} | ||
ST-DDT marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
try { | ||
authentication = authenticationManager.authenticate(authentication); | ||
} catch (final AuthenticationException e) { | ||
log.debug("Authentication request failed: {}", e.getMessage()); | ||
onUnsuccessfulAuthentication(call, headers, e); | ||
throw e; | ||
} | ||
|
||
final SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); | ||
securityContext.setAuthentication(authentication); | ||
SecurityContextHolder.setContext(securityContext); | ||
@SuppressWarnings("deprecation") | ||
final Context grpcContext = Context.current().withValues( | ||
SECURITY_CONTEXT_KEY, securityContext, | ||
AUTHENTICATION_CONTEXT_KEY, authentication); | ||
final Context previousContext = grpcContext.attach(); | ||
log.debug("Authentication successful: Continuing as {} ({})", authentication.getName(), | ||
authentication.getAuthorities()); | ||
onSuccessfulAuthentication(call, headers, authentication); | ||
try { | ||
return new AuthenticatingServerCallListener<>(next.startCall(call, headers), grpcContext, securityContext); | ||
} catch (final AccessDeniedException e) { | ||
if (authentication instanceof AnonymousAuthenticationToken) { | ||
throw newNoCredentialsException(e); | ||
} else { | ||
throw e; | ||
} | ||
} finally { | ||
SecurityContextHolder.clearContext(); | ||
grpcContext.detach(previousContext); | ||
log.debug("startCall - Authentication cleared"); | ||
} | ||
} | ||
|
||
/** | ||
* Retrieves the appropriate AuthenticationManager to handle authentication for the given gRPC request. | ||
* Subclasses must implement this method to provide a mechanism for determining the appropriate AuthenticationManager | ||
* based on the specific request context. This allows for dynamic selection of authentication strategies based on | ||
* factors such as request headers, request payload, or other criteria. | ||
* | ||
* @param call The gRPC ServerCall representing the incoming request. | ||
* @param headers The metadata associated with the request, containing potentially relevant authentication information. | ||
* @return The AuthenticationManager responsible for authenticating the request. | ||
*/ | ||
protected abstract <ReqT, RespT> AuthenticationManager getAuthenticationManager(final ServerCall<ReqT, RespT> call, | ||
final Metadata headers); | ||
ST-DDT marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
/** | ||
* Hook that will be called on successful authentication. Implementations may only use the call instance in a | ||
* non-disruptive manor, that is accessing call attributes or the call descriptor. Implementations must not pollute | ||
* the current thread/context with any call-related state, including authentication, beyond the duration of the | ||
* method invocation. At the time of calling both the grpc context and the security context have been updated to | ||
* reflect the state of the authentication and thus don't have to be setup manually. | ||
* | ||
* <p> | ||
* <b>Note:</b> This method is called regardless of whether the authenticated user is authorized or not to perform | ||
* the requested action. | ||
* </p> | ||
* | ||
* <p> | ||
* By default, this method does nothing. | ||
* </p> | ||
* | ||
* @param call The call instance to receive response messages. | ||
* @param headers The headers associated with the call. | ||
* @param authentication The successful authentication instance. | ||
*/ | ||
protected void onSuccessfulAuthentication( | ||
final ServerCall<?, ?> call, | ||
final Metadata headers, | ||
final Authentication authentication) { | ||
// Overwrite to add custom behavior. | ||
} | ||
|
||
/** | ||
* Hook that will be called on unsuccessful authentication. Implementations must use the call instance only in a | ||
* non-disruptive manner, i.e. to access call attributes or the call descriptor. Implementations must not close the | ||
* call and must not pollute the current thread/context with any call-related state, including authentication, | ||
* beyond the duration of the method invocation. | ||
* | ||
* <p> | ||
* <b>Note:</b> This method is called only if the request contains an authentication but the | ||
* {@link AuthenticationManager} considers it invalid. This method is not called if an authenticated user is not | ||
* authorized to perform the requested action. | ||
* </p> | ||
* | ||
* <p> | ||
* By default, this method does nothing. | ||
* </p> | ||
* | ||
* @param call The call instance to receive response messages. | ||
* @param headers The headers associated with the call. | ||
* @param failed The exception related to the unsuccessful authentication. | ||
*/ | ||
protected void onUnsuccessfulAuthentication( | ||
final ServerCall<?, ?> call, | ||
final Metadata headers, | ||
final AuthenticationException failed) { | ||
// Overwrite to add custom behavior. | ||
} | ||
|
||
/** | ||
* Wraps the given {@link AccessDeniedException} in an {@link AuthenticationException} to reflect, that no | ||
* authentication was originally present in the request. | ||
* | ||
* @param denied The caught exception. | ||
* @return The newly created {@link AuthenticationException}. | ||
*/ | ||
private static AuthenticationException newNoCredentialsException(final AccessDeniedException denied) { | ||
return new BadCredentialsException("No credentials found in the request", denied); | ||
} | ||
|
||
/** | ||
* A call listener that will set the authentication context using {@link SecurityContextHolder} before each | ||
* invocation and clear it afterwards. | ||
* | ||
* @param <ReqT> The type of the request. | ||
*/ | ||
private static class AuthenticatingServerCallListener<ReqT> extends AbstractAuthenticatingServerCallListener<ReqT> { | ||
|
||
private final SecurityContext securityContext; | ||
|
||
/** | ||
* Creates a new AuthenticatingServerCallListener which will attach the given security context before delegating | ||
* to the given listener. | ||
* | ||
* @param delegate The listener to delegate to. | ||
* @param grpcContext The context to attach. | ||
* @param securityContext The security context instance to attach. | ||
*/ | ||
public AuthenticatingServerCallListener(final ServerCall.Listener<ReqT> delegate, final Context grpcContext, | ||
final SecurityContext securityContext) { | ||
super(delegate, grpcContext); | ||
this.securityContext = securityContext; | ||
} | ||
|
||
@Override | ||
protected void attachAuthenticationContext() { | ||
SecurityContextHolder.setContext(this.securityContext); | ||
} | ||
|
||
@Override | ||
protected void detachAuthenticationContext() { | ||
SecurityContextHolder.clearContext(); | ||
} | ||
|
||
@Override | ||
public void onHalfClose() { | ||
try { | ||
super.onHalfClose(); | ||
} catch (final AccessDeniedException e) { | ||
if (this.securityContext.getAuthentication() instanceof AnonymousAuthenticationToken) { | ||
throw newNoCredentialsException(e); | ||
} else { | ||
throw e; | ||
} | ||
} | ||
} | ||
|
||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.