ArthurJS
ArthurJS

Reputation: 31

How to restrict Spartacus Authentication to certain customers?

I'm new to Spartacus storefront development but have worked in Hybris/SAP Commerce for some years,

Setting up spartacus I noticed that in the AuthenticationService, customers can log in over the REST API from any base store. The call simply goes to hybris with user e-mail/id and password, and is then authenticated to the store.

Is there possibility to restrict only users from one basestore to that specific spartacus storefront? Or groups on said user. Just something to not expose the spartacus storefront to all Customers...

Thank you

Upvotes: 2

Views: 730

Answers (1)

ArthurJS
ArthurJS

Reputation: 31

We made a RequiredRoleMatchingFilter extends AbstractUrlMatchingFilter that checks a custom role attribute (UserGroupModel) on BaseSite level

So something like this

private static final String ROLE_PREFIX = "ROLE_";
private BaseSiteService baseSiteService;

    @Override
    protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response,
                                    final FilterChain filterChain) throws ServletException, IOException {
        final Authentication auth = getAuth();
        boolean isCustomer = false;
        if (hasRole(ROLE_CUSTOMERGROUP, auth) || hasRole(ROLE_CUSTOMERMANAGERGROUP, auth)) {
            isCustomer = true;
        }

        final Optional<BaseSiteModel> currentBaseSite = Optional.ofNullable(getBaseSiteService().getCurrentBaseSite());
        if (isCustomer && currentBaseSite.isPresent() && currentBaseSite.get().getRequiredRole() != null) {
            final UserGroupModel requiredRole = currentBaseSite.get().getRequiredRole();
            final String REQUIRED_ROLE = ROLE_PREFIX + requiredRole.getUid().toUpperCase();
            if (hasRole(REQUIRED_ROLE, auth)) {
                LOG.debug("Authorized as " + requiredRole.getUid());
            } else {
                // could not match the authorized role
                throw new AccessDeniedException("Access is denied");
            }
        }

        filterChain.doFilter(request, response);
    }

Upvotes: 1

Related Questions