Skip to content
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

Add an interceptor to support AuthenticationManagerResolver #1034

Open
wants to merge 14 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions docs/en/server/security.md
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,36 @@ GrpcAuthenticationReader authenticationReader() {

See also [Mutual Certificate Authentication](#mutual-certificate-authentication).

#### Using AuthenticationManagerResolver
You can also use the `AuthenticationManagerResolver` to dynamically determine the authentication
ST-DDT marked this conversation as resolved.
Show resolved Hide resolved
manager to use for a particular request. This can be useful for applications that support multiple authentication
mechanisms, such as OAuth and OpenID Connect, or that want to delegate authentication to external services.

To use `AuthenticationManagerResolver`, you first need to create a bean that implements
the `AuthenticationManagerResolver<GrpcServerRequest>` interface instead of `AuthenticationManager`. The `resolve()` method of this bean should
return the AuthenticationManager to use for a particular request.

````java
@Bean
AuthenticationManagerResolver<GrpcServerRequest> grpcAuthenticationManagerResolver() {
return new AuthenticationManagerResolver<GrpcServerRequest>() {
@Override
public AuthenticationManager resolve(GrpcServerRequest grpcServerRequest) {
AuthenticationManager authenticationManager = // Check the grpc request and return an authenticationManager
return authenticationManager;
}
};
ST-DDT marked this conversation as resolved.
Show resolved Hide resolved
}

@Bean
GrpcAuthenticationReader authenticationReader() {
final List<GrpcAuthenticationReader> readers = new ArrayList<>();
// The actual token class is dependent on your spring-security library (OAuth2/JWT/...)
readers.add(new BearerAuthenticationReader(accessToken -> new BearerTokenAuthenticationToken(accessToken)));
return new CompositeGrpcAuthenticationReader(readers);
}
````

### Configure Authorization

This step is very important as it actually secures your application against unwanted access. You can secure your
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;

/**
Expand Down Expand Up @@ -59,7 +62,6 @@
* @author Daniel Theuke ([email protected])
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnBean(AuthenticationManager.class)
@AutoConfigureAfter(SecurityAutoConfiguration.class)
public class GrpcServerSecurityAutoConfiguration {

Expand All @@ -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.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import static java.util.Objects.requireNonNull;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.core.annotation.Order;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AbstractAuthenticationToken;
Expand Down Expand Up @@ -58,6 +59,7 @@
* @author Daniel Theuke ([email protected])
*/
@Slf4j
@ConditionalOnBean(AuthenticationManager.class)
ST-DDT marked this conversation as resolved.
Show resolved Hide resolved
@GrpcGlobalServerInterceptor
@Order(InterceptorOrder.ORDER_SECURITY_AUTHENTICATION)
public class DefaultAuthenticatingServerInterceptor implements AuthenticatingServerInterceptor {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package net.devh.boot.grpc.server.security.interceptors;

import brave.grpc.GrpcRequest;
import io.grpc.Metadata;
import io.grpc.MethodDescriptor;
import io.grpc.ServerCall;
import io.grpc.ServerInterceptor;

/**
* Allows access gRPC specific aspects of a server request during sampling and parsing.
*
* @see GrpcRequest for a parsing example
* @since 5.12
*/
public class GrpcServerRequest {
ST-DDT marked this conversation as resolved.
Show resolved Hide resolved
final ServerCall<?, ?> call;
final Metadata headers;
ST-DDT marked this conversation as resolved.
Show resolved Hide resolved

public GrpcServerRequest(ServerCall<?, ?> call, Metadata headers) {
if (call == null) throw new NullPointerException("call == null");
if (headers == null) throw new NullPointerException("headers == null");
this.call = call;
this.headers = headers;
ST-DDT marked this conversation as resolved.
Show resolved Hide resolved
}

/**
* Returns the {@linkplain ServerCall server call} passed to {@link
* ServerInterceptor#interceptCall}.
*
* @since 5.12
ST-DDT marked this conversation as resolved.
Show resolved Hide resolved
*/
public ServerCall<?, ?> call() {
return call;
}

/**
* Returns {@linkplain ServerCall#getMethodDescriptor()}} from the {@link #call()}.
*
* @since 5.12
*/
public MethodDescriptor<?, ?> methodDescriptor() {
return call.getMethodDescriptor();
}

/**
* Returns the {@linkplain Metadata headers} passed to {@link ServerInterceptor#interceptCall}.
*
* @since 5.12
*/
public Metadata headers() {
return headers;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
/*
* 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 io.grpc.ServerCall.Listener;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.common.util.InterceptorOrder;
import net.devh.boot.grpc.server.interceptor.GrpcGlobalServerInterceptor;
import net.devh.boot.grpc.server.security.authentication.GrpcAuthenticationReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.core.annotation.Order;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
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 AuthenticationManagerResolver#resolve (Context) grpcServerRequest} them. This interceptor create new {@link DefaultAuthenticatingServerInterceptor} to 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>
*
* @author Sajad Mehrabi ([email protected])
*/
@Slf4j
@ConditionalOnBean(parameterizedContainer = AuthenticationManagerResolver.class, value = GrpcServerRequest.class)
@GrpcGlobalServerInterceptor
@Order(InterceptorOrder.ORDER_SECURITY_AUTHENTICATION)
public class ManagerResolverAuthenticatingServerInterceptor implements AuthenticatingServerInterceptor {

private final AuthenticationManagerResolver<GrpcServerRequest> authenticationManagerResolver;
private final GrpcAuthenticationReader grpcAuthenticationReader;

/**
* Creates a new ManagerResolverAuthenticatingServerInterceptor with the given authentication manager resolver and reader.
*
* @param authenticationManagerResolver The authentication manager resolver used to verify the credentials.
* @param authenticationReader The authentication reader used to extract the credentials from the call.
*/
@Autowired
public ManagerResolverAuthenticatingServerInterceptor(final AuthenticationManagerResolver<GrpcServerRequest> authenticationManagerResolver,
final GrpcAuthenticationReader authenticationReader) {
ST-DDT marked this conversation as resolved.
Show resolved Hide resolved
this.authenticationManagerResolver = requireNonNull(authenticationManagerResolver, "authenticationManagerResolver");
this.grpcAuthenticationReader = requireNonNull(authenticationReader, "authenticationReader");
}

@Override
public <ReqT, RespT> Listener<ReqT> interceptCall(final ServerCall<ReqT, RespT> call,
final Metadata headers, final ServerCallHandler<ReqT, RespT> next) {

GrpcServerRequest grpcServerRequest = new GrpcServerRequest(call, headers);
AuthenticationManager authenticationManager = this.authenticationManagerResolver.resolve(grpcServerRequest);

if (authenticationManager == null) {
log.debug("No authenticationManager found: Continuing unauthenticated");
try {
return next.startCall(call, headers);
} catch (final AccessDeniedException e) {
throw newNoAuthenticationManagerException(e);
}
ST-DDT marked this conversation as resolved.
Show resolved Hide resolved
}
DefaultAuthenticatingServerInterceptor authenticatingServerInterceptor = new DefaultAuthenticatingServerInterceptor(authenticationManager, this.grpcAuthenticationReader);
return authenticatingServerInterceptor.interceptCall(call, headers, next);
ST-DDT marked this conversation as resolved.
Show resolved Hide resolved

}


/**
* 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 newNoAuthenticationManagerException(final AccessDeniedException denied) {
return new BadCredentialsException("No credentials found in the request", denied);
}

}
Loading