Skip to content
LELEU Jérôme edited this page Oct 15, 2018 · 11 revisions

Protect URLs (SecurityInterceptor)

You can protect (authentication + authorizations) the urls of your Spring application by using the SecurityInterceptor and defining the appropriate mapping. It has the following behaviour:

  1. If the HTTP request matches the matchers configuration (or no matchers are defined), the security is applied. Otherwise, the user is automatically granted access.

  2. First, if the user is not authenticated (no profile) and if some clients have been defined in the clients parameter, a login is tried for the direct clients.

  3. Then, if the user has a profile, authorizations are checked according to the authorizers configuration. If the authorizations are valid, the user is granted access. Otherwise, a 403 error page is displayed

  4. Finally, if the user is still not authenticated (no profile), he is redirected to the appropriate identity provider if the first defined client is an indirect one in the clients configuration. Otherwise, a 401 error page is displayed.

The following parameters are available:

  1. clients (optional): the list of client names (separated by commas) used for authentication:
  • in all cases, this filter requires the user to be authenticated. Thus, if the clients is blank or not defined, the user must have been previously authenticated
  • if the client_name request parameter is provided, only this client (if it exists in the clients) is selected.
  1. authorizers (optional): the list of authorizer names (separated by commas) used to check authorizations:
  • if the authorizers is blank or not defined, no authorization is checked
  • the following authorizers are available by default (without defining them in the configuration):
    • isFullyAuthenticated to check if the user is authenticated but not remembered, isRemembered for a remembered user, isAnonymous to ensure the user is not authenticated, isAuthenticated to ensure the user is authenticated (not necessary by default unless you use the AnonymousClient)
    • hsts to use the StrictTransportSecurityHeader authorizer, nosniff for XContentTypeOptionsHeader, noframe for XFrameOptionsHeader , xssprotection for XSSProtectionHeader , nocache for CacheControlHeader or securityHeaders for the five previous authorizers
    • csrfToken to use the CsrfTokenGeneratorAuthorizer with the DefaultCsrfTokenGenerator (it generates a CSRF token and saves it as the pac4jCsrfToken request attribute and in the pac4jCsrfToken cookie), csrfCheck to check that this previous token has been sent as the pac4jCsrfToken header or parameter in a POST request and csrf to use both previous authorizers.
  1. matchers (optional): the list of matcher names (separated by commas) that the request must satisfy to check authentication / authorizations

  2. multiProfile (optional): it indicates whether multiple authentications (and thus multiple profiles) must be kept at the same time (false by default).

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/*");
        ...
    }
}

Use helpers (WebSecurityHelper / RestSecurityHelper)

You can also use the spring-webmvc-pac4j helpers to get the current profile(s) or check authorizations.

First, you must register the helpers components:

@ComponentScan(basePackages = "org.pac4j.springframework.helper")

or

@Import(HelperConfig.class)

Then, for a web application, you can inject the WebSecurityHelper:

@Autowired
private WebSecurityHelper webSecurityHelper;

or for a REST API, you can inject the RestSecurityHelper:

@Autowired
private RestSecurityHelper restSecurityHelper;

With the injected helper, you can:

  • check if the user is authenticated using the isAuthenticated method
  • check if the user has the appropriate roles using either the requireAnyRole method or the requireAllRoles method
  • get the profiles of the authenticated user via the getProfile or getProfiles methods.

Use annotations (RequireAnyRole / RequireAllRoles)

You can use the spring-webmvc-pac4j annotations to check if the user has the appropriate roles.

First, you must register the annotations and helpers components:

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

or

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

Then, for a web application, you can use the org.pac4j.springframework.annotation.web.RequireAnyRole or the org.pac4j.springframework.annotation.web.RequireAllRoles annotations (web package).

Or for a REST API, you can use the org.pac4j.springframework.annotation.rest.RequireAnyRole or the org.pac4j.springframework.annotation.rest.RequireAllRoles annotations (rest package):

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