Search in sources :

Example 1 with UnauthorizedException

use of com.b2international.commons.exceptions.UnauthorizedException in project snow-owl by b2ihealthcare.

the class AuthorizedRequest method execute.

@Override
public R execute(ServiceProvider context) {
    final RequestHeaders requestHeaders = context.service(RequestHeaders.class);
    final String authorizationToken = requestHeaders.header(AUTHORIZATION_HEADER);
    final IdentityProvider identityProvider = context.service(IdentityProvider.class);
    final Collection<Request<?, ?>> requests = getNestedRequests();
    final User user;
    // if there is no authentication configured
    if (IdentityProvider.NOOP == identityProvider) {
        // allow execution as SYSTEM user
        user = User.SYSTEM;
    } else if (Strings.isNullOrEmpty(authorizationToken)) {
        // allow login requests in
        if (requests.stream().allMatch(req -> req.getClass().isAnnotationPresent(Unprotected.class))) {
            user = User.SYSTEM;
        } else {
            // if there is authentication configured, but no authorization token found prevent execution and throw UnauthorizedException
            if (PlatformUtil.isDevVersion()) {
                Request<?, ?> request = Iterables.getFirst(requests, null);
                System.err.println(request);
            }
            throw new UnauthorizedException("Missing authorization token");
        }
    } else {
        // verify authorization header value
        user = context.service(AuthorizationHeaderVerifier.class).auth(authorizationToken);
        if (user == null) {
            throw new UnauthorizedException("Incorrect authorization token");
        }
    }
    ServiceProvider userContext = context.inject().bind(User.class, user).bind(IEventBus.class, new AuthorizedEventBus(context.service(IEventBus.class), requestHeaders.headers())).build();
    if (!User.SYSTEM.equals(user) && !user.isAdministrator()) {
        // authorize user whether it is permitted to execute the request(s) or not
        requests.stream().filter(AccessControl.class::isInstance).map(AccessControl.class::cast).flatMap(ac -> {
            List<Permission> permissions = ac.getPermissions(userContext, next());
            if (permissions.isEmpty()) {
                context.log().warn("No permissions required to execute request '{}'.", MonitoredRequest.toJson(context, next(), Map.of()));
            }
            return permissions.stream();
        }).forEach(permissionRequirement -> {
            if (!user.hasPermission(permissionRequirement)) {
                throw new ForbiddenException("Operation not permitted. '%s' permission is required. User has '%s'.", permissionRequirement.getPermission(), user.getPermissions());
            }
        });
    }
    return next(userContext);
}
Also used : ForbiddenException(com.b2international.commons.exceptions.ForbiddenException) IdentityProvider(com.b2international.snowowl.core.identity.IdentityProvider) RequestHeaders(com.b2international.snowowl.core.events.util.RequestHeaders) Iterables(com.google.common.collect.Iterables) UnauthorizedException(com.b2international.commons.exceptions.UnauthorizedException) Collection(java.util.Collection) Request(com.b2international.snowowl.core.events.Request) IEventBus(com.b2international.snowowl.eventbus.IEventBus) Strings(com.google.common.base.Strings) List(java.util.List) AuthorizationHeaderVerifier(com.b2international.snowowl.core.identity.AuthorizationHeaderVerifier) PlatformUtil(com.b2international.snowowl.core.util.PlatformUtil) Map(java.util.Map) ServiceProvider(com.b2international.snowowl.core.ServiceProvider) DelegatingRequest(com.b2international.snowowl.core.events.DelegatingRequest) Permission(com.b2international.snowowl.core.identity.Permission) User(com.b2international.snowowl.core.identity.User) MonitoredRequest(com.b2international.snowowl.core.monitoring.MonitoredRequest) ForbiddenException(com.b2international.commons.exceptions.ForbiddenException) User(com.b2international.snowowl.core.identity.User) AuthorizationHeaderVerifier(com.b2international.snowowl.core.identity.AuthorizationHeaderVerifier) Request(com.b2international.snowowl.core.events.Request) DelegatingRequest(com.b2international.snowowl.core.events.DelegatingRequest) MonitoredRequest(com.b2international.snowowl.core.monitoring.MonitoredRequest) IdentityProvider(com.b2international.snowowl.core.identity.IdentityProvider) ServiceProvider(com.b2international.snowowl.core.ServiceProvider) UnauthorizedException(com.b2international.commons.exceptions.UnauthorizedException) List(java.util.List) RequestHeaders(com.b2international.snowowl.core.events.util.RequestHeaders) IEventBus(com.b2international.snowowl.eventbus.IEventBus)

Example 2 with UnauthorizedException

use of com.b2international.commons.exceptions.UnauthorizedException in project snow-owl by b2ihealthcare.

the class TransportClient method connect.

public User connect(final String username, final String password) throws SnowowlServiceException {
    try {
        this.user = username;
        this.password = password;
        // initialize connectors first
        initConnection();
        // try to log in with the specified username and password using the non-authorized bus instance
        final Token token = UserRequests.prepareLogin().setUsername(username).setPassword(password).buildAsync().execute(bus).getSync();
        // if successfully logged in replace the event bus with an authorized one
        env.services().registerService(IEventBus.class, new AuthorizedEventBus(bus, ImmutableMap.of("Authorization", token.getToken())));
        env.services().registerService(TransportClient.class, this);
        return env.service(AuthorizationHeaderVerifier.class).toUser(token.getToken());
    } catch (UnauthorizedException e) {
        throw new SnowowlServiceException(e.getMessage());
    } catch (final Throwable t) {
        final Throwable rootCause = Throwables.getRootCause(t);
        final String message = Strings.nullToEmpty(StringUtils.getLine(rootCause.getMessage(), "\n", 0)).replace("\r", "");
        LOG.error("Exception caught while connecting to the server.", t);
        // FIXME: "Sentiment analysis" for exception messages
        if (message.startsWith(COULD_NOT_ACTIVATE_PREFIX)) {
            throw new SnowowlServiceException("The server could not be reached. Please verify the connection URL.");
        } else if (message.startsWith(ALREADY_LOGGED_IN_PREFIX)) {
            throw new SnowowlServiceException("Another client with the same user is already connected to the server.");
        } else if (message.startsWith(INCORRECT_USER_NAME_OR_PASSWORD)) {
            throw new SnowowlServiceException(message);
        } else if (message.startsWith(LOGIN_DISABLED)) {
            throw new SnowowlServiceException(message);
        } else if (message.startsWith(LDAP_CONNECTION_REFUSED)) {
            throw new SnowowlServiceException("The LDAP server could not be reached for authentication. Please contact the administrator.");
        } else {
            throw new SnowowlServiceException("An unexpected error occurred while connecting to the server. Please contact the administrator.");
        }
    }
}
Also used : AuthorizationHeaderVerifier(com.b2international.snowowl.core.identity.AuthorizationHeaderVerifier) UnauthorizedException(com.b2international.commons.exceptions.UnauthorizedException) AuthorizedEventBus(com.b2international.snowowl.core.authorization.AuthorizedEventBus) Token(com.b2international.snowowl.core.identity.Token) SnowowlServiceException(com.b2international.snowowl.core.api.SnowowlServiceException)

Example 3 with UnauthorizedException

use of com.b2international.commons.exceptions.UnauthorizedException in project snow-owl by b2ihealthcare.

the class CisAuthenticationService method authenticate.

@Operation(summary = "Validates a token, checking if it's assigned to a current session, and retrieves user data.")
@ApiResponses({ @ApiResponse(responseCode = "400", description = "Error"), @ApiResponse(responseCode = "401", description = "Unauthorized") })
@PostMapping(value = "/authenticate")
public UserData authenticate(@Parameter(description = "The security access token.", required = true) @RequestBody Token token) {
    String username = verify(token.getToken());
    if (Strings.isNullOrEmpty(username)) {
        throw new UnauthorizedException("Token does not validate.");
    } else {
        final UserData userData = new UserData();
        userData.setUsername(username);
        return userData;
    }
}
Also used : UserData(com.b2international.snowowl.snomed.cis.rest.model.UserData) UnauthorizedException(com.b2international.commons.exceptions.UnauthorizedException) PostMapping(org.springframework.web.bind.annotation.PostMapping) Operation(io.swagger.v3.oas.annotations.Operation) ApiResponses(io.swagger.v3.oas.annotations.responses.ApiResponses)

Aggregations

UnauthorizedException (com.b2international.commons.exceptions.UnauthorizedException)3 AuthorizationHeaderVerifier (com.b2international.snowowl.core.identity.AuthorizationHeaderVerifier)2 ForbiddenException (com.b2international.commons.exceptions.ForbiddenException)1 ServiceProvider (com.b2international.snowowl.core.ServiceProvider)1 SnowowlServiceException (com.b2international.snowowl.core.api.SnowowlServiceException)1 AuthorizedEventBus (com.b2international.snowowl.core.authorization.AuthorizedEventBus)1 DelegatingRequest (com.b2international.snowowl.core.events.DelegatingRequest)1 Request (com.b2international.snowowl.core.events.Request)1 RequestHeaders (com.b2international.snowowl.core.events.util.RequestHeaders)1 IdentityProvider (com.b2international.snowowl.core.identity.IdentityProvider)1 Permission (com.b2international.snowowl.core.identity.Permission)1 Token (com.b2international.snowowl.core.identity.Token)1 User (com.b2international.snowowl.core.identity.User)1 MonitoredRequest (com.b2international.snowowl.core.monitoring.MonitoredRequest)1 PlatformUtil (com.b2international.snowowl.core.util.PlatformUtil)1 IEventBus (com.b2international.snowowl.eventbus.IEventBus)1 UserData (com.b2international.snowowl.snomed.cis.rest.model.UserData)1 Strings (com.google.common.base.Strings)1 Iterables (com.google.common.collect.Iterables)1 Operation (io.swagger.v3.oas.annotations.Operation)1