Skip to content
CAS in the cloud LELEU Jérôme edited this page Dec 9, 2022 · 11 revisions

1) Protect the URLs with the SecurityInterceptor

You can protect (authentication + authorization) the URLs of your web application/services by using the SecurityInterceptor.

>> Read the documentation to understand its behavior and the available options.

Spring context file:

<mvc:interceptors>
    <mvc:interceptor>
        <mvc:mapping path="/facebookadmin/*" />
        <bean class="org.pac4j.springframework.web.SecurityInterceptor">
            <constructor-arg name="config" ref="config" />
            <constructor-arg name="clients" value="FacebookClient" />
            <constructor-arg name="authorizers" value="admin" />
        </bean>
    </mvc:interceptor>
    ...

Spring configuration class:

@Configuration
@ComponentScan(basePackages = "org.pac4j.springframework.web")
public class SecurityConfig extends WebMvcConfigurerAdapter {

    @Autowired
    private Config config;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new SecurityInterceptor(config, "FacebookClient", "admin")).addPathPatterns("/facebookadmin/*");
        ...
    }
}

Notice that you can also use the smart builder (which accepts almost any parameter type and number): SecurityInterceptor.build(config, "FacebookClient", new CustomAuthorizer());.

2) Check the user roles via the @RequireAnyRole and the @RequireAllRoles annotations

First, you must register the annotations and the components:

@ComponentScan(basePackages = { "org.pac4j.springframework.annotation", "org.pac4j.springframework.component" })

or

@Import({ComponentConfig.class, AnnotationConfig.class})

Then, you can use the org.pac4j.springframework.annotation.RequireAnyRole or org.pac4j.springframework.annotation.RequireAllRoles annotations:

@RequestMapping("/facebookadmin/index.html")
@RequireAnyRole("ROLE_ADMIN")
public String facebookadmin(final Map<String, Object> map) {
    return protectedIndex(map);
}