Search in sources :

Example 1 with UNAUTHORIZED

use of javax.ws.rs.core.Response.Status.UNAUTHORIZED in project codex by apycazo.

the class SecurityFilter method filter.

@Override
public void filter(ContainerRequestContext requestContext) {
    if (securityManagers.stream().noneMatch(manager -> manager.authenticate(requestContext))) {
        if (requestContext.getHeaderString(HttpHeaders.AUTHORIZATION) != null) {
            // the request tried to be authorized, but no manager could authenticate
            requestContext.abortWith(Response.status(FORBIDDEN).build());
        } else {
            // the request tried to be authorized, and no credentials where found
            requestContext.abortWith(Response.status(UNAUTHORIZED).build());
        }
    } else {
        // check role requirements (if any)
        SecurityContext securityContext = requestContext.getSecurityContext();
        Set<SecurityRole> roleSet = new HashSet<>();
        // adds class-level annotation roles
        Optional.ofNullable(resourceInfo.getResourceClass().getAnnotation(Authenticated.class)).ifPresent(annotation -> roleSet.addAll(Arrays.asList(annotation.rolesAllowed())));
        // adds method-level annotation roles
        Optional.ofNullable(resourceInfo.getResourceMethod().getAnnotation(Authenticated.class)).ifPresent(annotation -> roleSet.addAll(Arrays.asList(annotation.rolesAllowed())));
        if (!roleSet.isEmpty() && roleSet.stream().noneMatch(role -> securityContext.isUserInRole(role.name()))) {
            requestContext.abortWith(Response.status(FORBIDDEN).build());
        }
    }
}
Also used : java.util(java.util) UNAUTHORIZED(javax.ws.rs.core.Response.Status.UNAUTHORIZED) Context(javax.ws.rs.core.Context) Priorities(javax.ws.rs.Priorities) SecurityContext(javax.ws.rs.core.SecurityContext) Autowired(org.springframework.beans.factory.annotation.Autowired) FORBIDDEN(javax.ws.rs.core.Response.Status.FORBIDDEN) ContainerRequestFilter(javax.ws.rs.container.ContainerRequestFilter) ContainerRequestContext(javax.ws.rs.container.ContainerRequestContext) Priority(javax.annotation.Priority) Slf4j(lombok.extern.slf4j.Slf4j) HttpHeaders(javax.ws.rs.core.HttpHeaders) ResourceInfo(javax.ws.rs.container.ResourceInfo) Response(javax.ws.rs.core.Response) SecurityContext(javax.ws.rs.core.SecurityContext)

Example 2 with UNAUTHORIZED

use of javax.ws.rs.core.Response.Status.UNAUTHORIZED in project pay-adminusers by alphagov.

the class UserResource method activateSecondFactorOtpKey.

@Path("/{userExternalId}/second-factor/activate")
@POST
@Produces(APPLICATION_JSON)
@Consumes(APPLICATION_JSON)
public Response activateSecondFactorOtpKey(@PathParam("userExternalId") String externalId, JsonNode payload) {
    LOGGER.info("User 2FA activate new OTP key request");
    return validator.validate2faActivateRequest(payload).map(errors -> Response.status(BAD_REQUEST).entity(errors).build()).orElseGet(() -> {
        int code = payload.get("code").asInt();
        SecondFactorMethod secondFactor = SecondFactorMethod.valueOf(payload.get("second_factor").asText());
        return userServices.activateNewOtpKey(externalId, secondFactor, code).map(user -> Response.status(OK).type(APPLICATION_JSON).entity(user).build()).orElseGet(() -> Response.status(UNAUTHORIZED).build());
    });
}
Also used : PATCH(io.dropwizard.jersey.PATCH) PathParam(javax.ws.rs.PathParam) Produces(javax.ws.rs.Produces) FIELD_USERNAME(uk.gov.pay.adminusers.model.User.FIELD_USERNAME) GET(javax.ws.rs.GET) CreateUserRequest(uk.gov.pay.adminusers.model.CreateUserRequest) User(uk.gov.pay.adminusers.model.User) Inject(com.google.inject.Inject) LoggerFactory(org.slf4j.LoggerFactory) Path(javax.ws.rs.Path) Valid(javax.validation.Valid) UserServices(uk.gov.pay.adminusers.service.UserServices) QueryParam(javax.ws.rs.QueryParam) ExistingUserOtpDispatcher(uk.gov.pay.adminusers.service.ExistingUserOtpDispatcher) Consumes(javax.ws.rs.Consumes) Map(java.util.Map) JsonNode(com.fasterxml.jackson.databind.JsonNode) SecondFactorMethod(uk.gov.pay.adminusers.model.SecondFactorMethod) APPLICATION_JSON(javax.ws.rs.core.MediaType.APPLICATION_JSON) Splitter(com.google.common.base.Splitter) AdminUsersExceptions.conflictingUsername(uk.gov.pay.adminusers.service.AdminUsersExceptions.conflictingUsername) BAD_REQUEST(javax.ws.rs.core.Response.Status.BAD_REQUEST) UNAUTHORIZED(javax.ws.rs.core.Response.Status.UNAUTHORIZED) Logger(org.slf4j.Logger) POST(javax.ws.rs.POST) UserServicesFactory(uk.gov.pay.adminusers.service.UserServicesFactory) OK(javax.ws.rs.core.Response.Status.OK) NOT_FOUND(javax.ws.rs.core.Response.Status.NOT_FOUND) AdminUsersExceptions.internalServerError(uk.gov.pay.adminusers.service.AdminUsersExceptions.internalServerError) PatchRequest(uk.gov.pay.adminusers.model.PatchRequest) List(java.util.List) Response(javax.ws.rs.core.Response) WebApplicationException(javax.ws.rs.WebApplicationException) Optional(java.util.Optional) PUT(javax.ws.rs.PUT) CREATED(javax.ws.rs.core.Response.Status.CREATED) SecondFactorMethod(uk.gov.pay.adminusers.model.SecondFactorMethod) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces) Consumes(javax.ws.rs.Consumes)

Example 3 with UNAUTHORIZED

use of javax.ws.rs.core.Response.Status.UNAUTHORIZED in project trino by trinodb.

the class OAuth2WebUiAuthenticationFilter method filter.

@Override
public void filter(ContainerRequestContext request) {
    String path = request.getUriInfo().getRequestUri().getPath();
    if (path.equals(DISABLED_LOCATION)) {
        return;
    }
    // doesn't seem very useful if you have OAuth, and would be very complex.
    if (!request.getSecurityContext().isSecure()) {
        // send 401 to REST api calls and redirect to others
        if (path.startsWith("/ui/api/")) {
            sendWwwAuthenticate(request, "Unauthorized", ImmutableSet.of(TRINO_FORM_LOGIN));
            return;
        }
        request.abortWith(Response.seeOther(DISABLED_LOCATION_URI).build());
        return;
    }
    Optional<Map<String, Object>> claims;
    try {
        claims = getAccessToken(request);
        if (claims.isEmpty()) {
            needAuthentication(request);
            return;
        }
    } catch (ChallengeFailedException e) {
        LOG.debug(e, "Invalid token: %s", e.getMessage());
        sendErrorMessage(request, UNAUTHORIZED, "Unauthorized");
        return;
    }
    try {
        Object principal = claims.get().get(principalField);
        if (!isValidPrincipal(principal)) {
            LOG.debug("Invalid principal field: %s. Expected principal to be non-empty", principalField);
            sendErrorMessage(request, UNAUTHORIZED, "Unauthorized");
            return;
        }
        String principalName = (String) principal;
        Identity.Builder builder = Identity.forUser(userMapping.mapUser(principalName));
        builder.withPrincipal(new BasicPrincipal(principalName));
        groupsField.flatMap(field -> Optional.ofNullable((List<String>) claims.get().get(field))).ifPresent(groups -> builder.withGroups(ImmutableSet.copyOf(groups)));
        setAuthenticatedIdentity(request, builder.build());
    } catch (UserMappingException e) {
        sendErrorMessage(request, UNAUTHORIZED, firstNonNull(e.getMessage(), "Unauthorized"));
    }
}
Also used : Logger(io.airlift.log.Logger) OAuth2Service(io.trino.server.security.oauth2.OAuth2Service) TRINO_FORM_LOGIN(io.trino.server.ui.FormWebUiAuthenticationFilter.TRINO_FORM_LOGIN) CALLBACK_ENDPOINT(io.trino.server.security.oauth2.OAuth2CallbackResource.CALLBACK_ENDPOINT) ServletSecurityUtils.sendWwwAuthenticate(io.trino.server.ServletSecurityUtils.sendWwwAuthenticate) ContainerRequestContext(javax.ws.rs.container.ContainerRequestContext) Inject(javax.inject.Inject) ServletSecurityUtils.sendErrorMessage(io.trino.server.ServletSecurityUtils.sendErrorMessage) ServletSecurityUtils.setAuthenticatedIdentity(io.trino.server.ServletSecurityUtils.setAuthenticatedIdentity) Identity(io.trino.spi.security.Identity) Map(java.util.Map) Objects.requireNonNull(java.util.Objects.requireNonNull) DISABLED_LOCATION(io.trino.server.ui.FormWebUiAuthenticationFilter.DISABLED_LOCATION) UserMappingException(io.trino.server.security.UserMappingException) UNAUTHORIZED(javax.ws.rs.core.Response.Status.UNAUTHORIZED) ImmutableSet(com.google.common.collect.ImmutableSet) UserMapping(io.trino.server.security.UserMapping) DISABLED_LOCATION_URI(io.trino.server.ui.FormWebUiAuthenticationFilter.DISABLED_LOCATION_URI) ChallengeFailedException(io.trino.server.security.oauth2.ChallengeFailedException) BasicPrincipal(io.trino.spi.security.BasicPrincipal) OAuth2Config(io.trino.server.security.oauth2.OAuth2Config) List(java.util.List) Response(javax.ws.rs.core.Response) OAUTH2_COOKIE(io.trino.server.ui.OAuthWebUiCookie.OAUTH2_COOKIE) Optional(java.util.Optional) JwtException(io.jsonwebtoken.JwtException) MoreObjects.firstNonNull(com.google.common.base.MoreObjects.firstNonNull) BasicPrincipal(io.trino.spi.security.BasicPrincipal) ChallengeFailedException(io.trino.server.security.oauth2.ChallengeFailedException) UserMappingException(io.trino.server.security.UserMappingException) ServletSecurityUtils.setAuthenticatedIdentity(io.trino.server.ServletSecurityUtils.setAuthenticatedIdentity) Identity(io.trino.spi.security.Identity) Map(java.util.Map)

Aggregations

Response (javax.ws.rs.core.Response)3 UNAUTHORIZED (javax.ws.rs.core.Response.Status.UNAUTHORIZED)3 List (java.util.List)2 Map (java.util.Map)2 Optional (java.util.Optional)2 JsonNode (com.fasterxml.jackson.databind.JsonNode)1 MoreObjects.firstNonNull (com.google.common.base.MoreObjects.firstNonNull)1 Splitter (com.google.common.base.Splitter)1 ImmutableSet (com.google.common.collect.ImmutableSet)1 Inject (com.google.inject.Inject)1 Logger (io.airlift.log.Logger)1 PATCH (io.dropwizard.jersey.PATCH)1 JwtException (io.jsonwebtoken.JwtException)1 ServletSecurityUtils.sendErrorMessage (io.trino.server.ServletSecurityUtils.sendErrorMessage)1 ServletSecurityUtils.sendWwwAuthenticate (io.trino.server.ServletSecurityUtils.sendWwwAuthenticate)1 ServletSecurityUtils.setAuthenticatedIdentity (io.trino.server.ServletSecurityUtils.setAuthenticatedIdentity)1 UserMapping (io.trino.server.security.UserMapping)1 UserMappingException (io.trino.server.security.UserMappingException)1 ChallengeFailedException (io.trino.server.security.oauth2.ChallengeFailedException)1 CALLBACK_ENDPOINT (io.trino.server.security.oauth2.OAuth2CallbackResource.CALLBACK_ENDPOINT)1