de.pksoftware.springstrap.core.config.WebSecurityConfigBase.java Source code

Java tutorial

Introduction

Here is the source code for de.pksoftware.springstrap.core.config.WebSecurityConfigBase.java

Source

/*
 * 
 * Springstrap
 *
 * @author Jan Philipp Knller <info@pksoftware.de>
 * 
 * Homepage: http://ui5strap.com/springstrap
 *
 * Copyright (c) 2013-2014 Jan Philipp Knller <info@pksoftware.de>
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * Released under Apache2 license: http://www.apache.org/licenses/LICENSE-2.0.txt
 * 
 */

package de.pksoftware.springstrap.core.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.oauth2.client.filter.OAuth2ClientContextFilter;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter;

import de.pksoftware.springstrap.core.security.AjaxAuthenticationEntryPoint;
import de.pksoftware.springstrap.core.security.AjaxAuthenticationFailureHandler;
import de.pksoftware.springstrap.core.security.AjaxAuthenticationSuccessHandler;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public abstract class WebSecurityConfigBase extends WebSecurityConfigurerAdapter {

    protected static final Logger logger = LoggerFactory.getLogger(WebSecurityConfigBase.class);

    /**
     * Customize the Authentication Manager.
     * 
     * @param auth
     * @throws Exception
     */
    @Autowired
    public abstract void configureAuthenticationManager(AuthenticationManagerBuilder auth) throws Exception;

    /**
     * Expose the Authentication Manager as Bean. The Authentication Manager needs to be injected to other Configurations.
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    /**
     * Creates the Authentication Success Handler.
     * 
     * @return
     */
    @Bean
    protected AuthenticationSuccessHandler formLoginSuccessHandlerBean() {
        SavedRequestAwareAuthenticationSuccessHandler successHandler = new AjaxAuthenticationSuccessHandler();

        successHandler.setTargetUrlParameter(SpringstrapConfiguration.DEFAULT_FORM_LOGIN_TARGET_URL_PARAMETER);
        successHandler.setDefaultTargetUrl(SpringstrapConfiguration.DEFAULT_FORM_LOGIN_DEFAULT_TARGET_URL);

        return successHandler;
    }

    /**
     * Creates the Authentication Failure Handler.
     * 
     * @return
     */
    @Bean
    protected AuthenticationFailureHandler formLoginFailureHandlerBean() {
        return new AjaxAuthenticationFailureHandler(SpringstrapConfiguration.DEFAULT_FORM_LOGIN_ERROR_PAGE);
    }

    /**
     * Returns the URL to the login page.
     * @return
     */
    protected String getLoginPageUrl() {
        return SpringstrapConfiguration.DEFAULT_LOGIN_PAGE;
    }

    /**
     * Creates the Authentication Entry Point.
     * 
     * @return
     */
    @Bean
    protected AuthenticationEntryPoint authEntryPointBean() {
        return new AjaxAuthenticationEntryPoint(getLoginPageUrl());
    }

    protected void configureSessionManagement(HttpSecurity http) throws Exception {
        /*
         * http.sessionManagement()
         * .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED);
         */

        //http.anonymous().disable();

    }

    protected void configureAuthenticationEntryPoint(HttpSecurity http) throws Exception {
        // Register custom authentication entry point
        http.exceptionHandling().authenticationEntryPoint(authEntryPointBean());
    }

    protected void configureAuthenticationFilters(HttpSecurity http) {
        //Add a OAuth2ClientContextFilter to the filter chain.
        http.addFilterAfter(new OAuth2ClientContextFilter(), AbstractPreAuthenticatedProcessingFilter.class);
    }

    protected void configureFormLogin(HttpSecurity http) throws Exception {
        // Form Login
        http.formLogin()
                //Processing Url
                .loginProcessingUrl(SpringstrapConfiguration.DEFAULT_FORM_LOGIN_PROCESSING_URL)

                //Success and failure handlers
                .successHandler(formLoginSuccessHandlerBean()).failureHandler(formLoginFailureHandlerBean())

                //Username and password parameter
                .usernameParameter(SpringstrapConfiguration.DEFAULT_FORM_LOGIN_USERNAME_PARAMETER)
                .passwordParameter(SpringstrapConfiguration.DEFAULT_FORM_LOGIN_PASSWORD_PARAMETER)

                //Everybody can see the login page
                .permitAll(true);
    }

    /**
     * Configure XFrame Options
     * @throws Exception 
     */
    protected void configureXFrameOptions(HttpSecurity http) throws Exception {
        http.headers().frameOptions().sameOrigin();
    }

    protected void configureLogout(HttpSecurity http) throws Exception {
        // Define logout URL
        // TODO Cookie Name!
        http.logout().logoutUrl(SpringstrapConfiguration.DEFAULT_LOGIN_SIGNOUT_PAGE)
                .deleteCookies(SpringstrapConfiguration.DEFAULT_LOGIN_COOKIE_NAME);
    }

    /**
     * Configure Http Security.
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        logger.info("Configuring Springstrap Web Security...");

        configureSessionManagement(http);

        configureAuthenticationEntryPoint(http);

        configureFormLogin(http);

        configureAuthenticationFilters(http);

        configureXFrameOptions(http);

        configureLogout(http);

        // Additional Configuration Rules
        configureSecurity(http);
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        //TODO Make all api calls via /api/**
        //web.ignoring().antMatchers(new String[]{"/apps/**", "/sysapps/**", "/lib/**"});

        web.ignoring().antMatchers(new String[] { "/site/**", "/lib/**" });
    }

    /**
     * Custom Security Configuration.
     * 
     * @param http
     * @throws Exception
     */
    protected void configureSecurity(HttpSecurity http) throws Exception {
        logger.info("Customizing Springstrap Web Security...");

        //By default all requests are permitted.
        //TODO
        http.authorizeRequests().anyRequest().permitAll();
    }

    /**
     * Adds an authentication processing filter to the spring security filter chain.
     * @param http
     * @param filter
     */
    protected void addAuthenticationProcessingFilter(HttpSecurity http,
            AbstractAuthenticationProcessingFilter filter) {
        http.addFilterAfter(filter, OAuth2ClientContextFilter.class);
    }

}