Search in sources :

Example 1 with HttpRequest

use of io.micronaut.http.HttpRequest in project micronaut-security by micronaut-projects.

the class InterceptUrlMapRule method check.

/**
 * If no configured pattern matches the request, return {@link SecurityRuleResult#UNKNOWN}.
 * Reads the rules in order. The first matched rule will be used for determining authorization.
 *
 * @param request The current request
 * @param routeMatch The matched route
 * @param authentication The user authentication. Null if not authenticated
 * @return The result
 */
@Override
public Publisher<SecurityRuleResult> check(HttpRequest<?> request, @Nullable RouteMatch<?> routeMatch, @Nullable Authentication authentication) {
    final String path = request.getUri().getPath();
    final HttpMethod httpMethod = request.getMethod();
    Predicate<InterceptUrlMapPattern> exactMatch = p -> pathMatcher.matches(p.getPattern(), path) && p.getHttpMethod().isPresent() && httpMethod.equals(p.getHttpMethod().get());
    Predicate<InterceptUrlMapPattern> uriPatternMatchOnly = p -> pathMatcher.matches(p.getPattern(), path) && !p.getHttpMethod().isPresent();
    Optional<InterceptUrlMapPattern> matchedPattern = getPatternList().stream().filter(exactMatch).findFirst();
    // if we don't get an exact match try to find a match by the uri pattern
    if (!matchedPattern.isPresent()) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("No url map pattern exact match found for path [{}] and method [{}]. Searching in patterns with no defined method.", path, httpMethod);
        }
        matchedPattern = getPatternList().stream().filter(uriPatternMatchOnly).findFirst();
        if (LOG.isDebugEnabled()) {
            if (matchedPattern.isPresent()) {
                LOG.debug("Url map pattern found for path [{}]. Comparing roles.", path);
            } else {
                LOG.debug("No url map pattern match found for path [{}]. Returning unknown.", path);
            }
        }
    }
    return Mono.from(matchedPattern.map(pattern -> compareRoles(pattern.getAccess(), getRoles(authentication))).orElse(Mono.just(SecurityRuleResult.UNKNOWN)));
}
Also used : HttpMethod(io.micronaut.http.HttpMethod) Logger(org.slf4j.Logger) Predicate(java.util.function.Predicate) Publisher(org.reactivestreams.Publisher) LoggerFactory(org.slf4j.LoggerFactory) Authentication(io.micronaut.security.authentication.Authentication) PathMatcher(io.micronaut.core.util.PathMatcher) Mono(reactor.core.publisher.Mono) AntPathMatcher(io.micronaut.core.util.AntPathMatcher) InterceptUrlMapPattern(io.micronaut.security.config.InterceptUrlMapPattern) List(java.util.List) Nullable(io.micronaut.core.annotation.Nullable) RolesFinder(io.micronaut.security.token.RolesFinder) Optional(java.util.Optional) HttpRequest(io.micronaut.http.HttpRequest) RouteMatch(io.micronaut.web.router.RouteMatch) Inject(jakarta.inject.Inject) InterceptUrlMapPattern(io.micronaut.security.config.InterceptUrlMapPattern) HttpMethod(io.micronaut.http.HttpMethod)

Example 2 with HttpRequest

use of io.micronaut.http.HttpRequest in project micronaut-graphql by micronaut-projects.

the class LoginDataFetcher method get.

@Override
public LoginPayload get(DataFetchingEnvironment environment) throws Exception {
    GraphQLContext graphQLContext = environment.getContext();
    if (LOGIN_RATE_LIMIT_REMAINING <= 0) {
        addRateLimitHeaders(graphQLContext);
        resetRateLimit();
        return LoginPayload.ofError("Rate Limit Exceeded");
    }
    HttpRequest httpRequest = graphQLContext.get("httpRequest");
    MutableHttpResponse<String> httpResponse = graphQLContext.get("httpResponse");
    String username = environment.getArgument("username");
    String password = environment.getArgument("password");
    UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(username, password);
    LOGIN_RATE_LIMIT_REMAINING--;
    Flux<AuthenticationResponse> authenticationResponseFlowable = Flux.from(authenticator.authenticate(httpRequest, usernamePasswordCredentials));
    return authenticationResponseFlowable.map(authenticationResponse -> {
        addRateLimitHeaders(graphQLContext);
        if (authenticationResponse.isAuthenticated()) {
            eventPublisher.publishEvent(new LoginSuccessfulEvent(authenticationResponse));
            Optional<Cookie> jwtCookie = accessTokenCookie(Authentication.build(username), httpRequest);
            jwtCookie.ifPresent(httpResponse::cookie);
            User user = userRepository.findByUsername(username).orElse(null);
            return LoginPayload.ofUser(user);
        } else {
            eventPublisher.publishEvent(new LoginFailedEvent(authenticationResponse));
            return LoginPayload.ofError(authenticationResponse.getMessage().orElse(null));
        }
    }).blockFirst();
}
Also used : HttpRequest(io.micronaut.http.HttpRequest) DataFetchingEnvironment(graphql.schema.DataFetchingEnvironment) UsernamePasswordCredentials(io.micronaut.security.authentication.UsernamePasswordCredentials) AccessRefreshToken(io.micronaut.security.token.jwt.render.AccessRefreshToken) Cookie(io.micronaut.http.cookie.Cookie) User(example.domain.User) AccessTokenConfiguration(io.micronaut.security.token.jwt.generator.AccessTokenConfiguration) ApplicationEventPublisher(io.micronaut.context.event.ApplicationEventPublisher) MutableHttpResponse(io.micronaut.http.MutableHttpResponse) Authentication(io.micronaut.security.authentication.Authentication) Singleton(jakarta.inject.Singleton) Random(java.util.Random) CookieConfiguration(io.micronaut.http.cookie.CookieConfiguration) AccessRefreshTokenGenerator(io.micronaut.security.token.jwt.generator.AccessRefreshTokenGenerator) UserRepository(example.repository.UserRepository) Authenticator(io.micronaut.security.authentication.Authenticator) Flux(reactor.core.publisher.Flux) LoginSuccessfulEvent(io.micronaut.security.event.LoginSuccessfulEvent) GraphQLContext(graphql.GraphQLContext) DataFetcher(graphql.schema.DataFetcher) TemporalAmount(java.time.temporal.TemporalAmount) Optional(java.util.Optional) HttpRequest(io.micronaut.http.HttpRequest) LoginFailedEvent(io.micronaut.security.event.LoginFailedEvent) AuthenticationResponse(io.micronaut.security.authentication.AuthenticationResponse) User(example.domain.User) Optional(java.util.Optional) GraphQLContext(graphql.GraphQLContext) LoginSuccessfulEvent(io.micronaut.security.event.LoginSuccessfulEvent) AuthenticationResponse(io.micronaut.security.authentication.AuthenticationResponse) LoginFailedEvent(io.micronaut.security.event.LoginFailedEvent) UsernamePasswordCredentials(io.micronaut.security.authentication.UsernamePasswordCredentials)

Example 3 with HttpRequest

use of io.micronaut.http.HttpRequest in project micronaut-graphql by micronaut-projects.

the class GraphQLWsMessageHandler method executeRequest.

@SuppressWarnings("rawtypes")
private Publisher<GraphQLWsResponse> executeRequest(String operationId, GraphQLRequestBody payload, WebSocketSession session) {
    GraphQLInvocationData invocationData = new GraphQLInvocationData(payload.getQuery(), payload.getOperationName(), payload.getVariables());
    HttpRequest httpRequest = session.get(HTTP_REQUEST_KEY, HttpRequest.class).orElseThrow(() -> new RuntimeException("HttpRequest could not be retrieved from websocket session"));
    Publisher<ExecutionResult> executionResult = graphQLInvocation.invoke(invocationData, httpRequest, null);
    Publisher<GraphQLResponseBody> responseBody = graphQLExecutionResultHandler.handleExecutionResult(executionResult);
    return Flux.from(responseBody).flatMap(body -> responseSender.send(operationId, body, session));
}
Also used : HttpRequest(io.micronaut.http.HttpRequest) GraphQLInvocationData(io.micronaut.configuration.graphql.GraphQLInvocationData) ExecutionResult(graphql.ExecutionResult) GraphQLResponseBody(io.micronaut.configuration.graphql.GraphQLResponseBody)

Aggregations

HttpRequest (io.micronaut.http.HttpRequest)3 Authentication (io.micronaut.security.authentication.Authentication)2 Optional (java.util.Optional)2 User (example.domain.User)1 UserRepository (example.repository.UserRepository)1 ExecutionResult (graphql.ExecutionResult)1 GraphQLContext (graphql.GraphQLContext)1 DataFetcher (graphql.schema.DataFetcher)1 DataFetchingEnvironment (graphql.schema.DataFetchingEnvironment)1 GraphQLInvocationData (io.micronaut.configuration.graphql.GraphQLInvocationData)1 GraphQLResponseBody (io.micronaut.configuration.graphql.GraphQLResponseBody)1 ApplicationEventPublisher (io.micronaut.context.event.ApplicationEventPublisher)1 Nullable (io.micronaut.core.annotation.Nullable)1 AntPathMatcher (io.micronaut.core.util.AntPathMatcher)1 PathMatcher (io.micronaut.core.util.PathMatcher)1 HttpMethod (io.micronaut.http.HttpMethod)1 MutableHttpResponse (io.micronaut.http.MutableHttpResponse)1 Cookie (io.micronaut.http.cookie.Cookie)1 CookieConfiguration (io.micronaut.http.cookie.CookieConfiguration)1 AuthenticationResponse (io.micronaut.security.authentication.AuthenticationResponse)1