com.wiiyaya.consumer.web.initializer.config.SecurityConfig.java Source code

Java tutorial

Introduction

Here is the source code for com.wiiyaya.consumer.web.initializer.config.SecurityConfig.java

Source

/*
 * Copyright 2016-2017 the original author or authors.
 *
 * 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.
 */
package com.wiiyaya.consumer.web.initializer.config;

import com.wiiyaya.consumer.web.login.constant.ConfigURIResource;
import com.wiiyaya.consumer.web.main.constant.MainURIResource;
import com.wiiyaya.provider.main.service.ResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.concurrent.ConcurrentMapCache;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
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.core.Authentication;
import org.springframework.security.core.userdetails.UserCache;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.cache.SpringCacheBasedUserCache;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.security.web.util.matcher.AnyRequestMatcher;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 
 * <p>spring-security ?</p>
 *
 * <p>??</p>
 *
 * <p>?root config??</p>
 *
 * @author wiiyaya
 *
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private ResourceService resourceService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    //====????authenticationManager ?Oauth2?=====
    //   @Autowired
    //    protected AuthenticationManager authenticationManager;
    //   
    //   @Bean
    //   @Override
    //   public AuthenticationManager authenticationManagerBean() throws Exception {
    //      return super.authenticationManagerBean();
    //   }
    //====???=====

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(ConfigURIResource.PATH_STATIC_RESOURCE_REGX, ConfigURIResource.PATH_ERROR_REGX);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authenticationProvider(daoAuthenticationProvider());

        configHeaders(http);

        configCsrf(http);

        configBackendFormLogin(http);

        configResourceAuthority(http);

        configSessionManager(http);
    }

    private void configResourceAuthority(HttpSecurity http) throws Exception {
        String[] noNeedAuths = resourceService.getNoNeedAuthResources();
        http.authorizeRequests().antMatchers(noNeedAuths).permitAll();

        Map<String, String[]> needAuths = resourceService.getNeedAuthResources();
        for (Map.Entry<String, String[]> entity : needAuths.entrySet()) {
            http.authorizeRequests().antMatchers(entity.getKey()).hasAnyAuthority(entity.getValue());
        }

        http.authorizeRequests().anyRequest().authenticated();
    }

    private void configCsrf(HttpSecurity http) throws Exception {
        http.csrf().ignoringAntMatchers(ConfigURIResource.PATH_LOGIN);
    }

    private void configHeaders(HttpSecurity http) throws Exception {
        http.headers().httpStrictTransportSecurity().requestMatcher(AnyRequestMatcher.INSTANCE)
                .maxAgeInSeconds(31536000).includeSubDomains(false).and().frameOptions().sameOrigin();
    }

    private void configBackendFormLogin(HttpSecurity http) throws Exception {
        http.formLogin().loginPage(ConfigURIResource.PATH_LOGIN)
                .defaultSuccessUrl(ConfigURIResource.PATH_LOGIN_SUCCESS, true)
                //            .failureUrl(FwResource.PATH_LOGIN_FAILED)
                .permitAll().and().logout().logoutUrl(ConfigURIResource.PATH_LOGOUT)
                .addLogoutHandler(userCacheLogoutHandler())
                //            .logoutSuccessUrl(FwResource.PATH_LOGOUT_SUCCESS)
                .permitAll();
    }

    private void configSessionManager(HttpSecurity http) throws Exception {
        http.sessionManagement().maximumSessions(1).maxSessionsPreventsLogin(false)
                .expiredUrl(MainURIResource.PATH_ERROR_MAX_SESSIONS)//??URL
                .and().invalidSessionUrl(MainURIResource.PATH_ERROR_TIME_OUT);//session?URL
    }

    @Bean
    public DaoAuthenticationProvider daoAuthenticationProvider() throws Exception {
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        provider.setUserDetailsService(userDetailsService);
        provider.setUserCache(userCache());
        provider.setPasswordEncoder(passwordEncoder);
        return provider;
    }

    @Bean
    public UserCache userCache() throws Exception {
        SpringCacheBasedUserCache userCache = new SpringCacheBasedUserCache(new ConcurrentMapCache("userCache"));
        return userCache;
    }

    @Bean
    public UserCacheLogoutHandler userCacheLogoutHandler() throws Exception {
        UserCacheLogoutHandler hander = new UserCacheLogoutHandler();
        hander.setUserCache(userCache());
        return hander;
    }

    class UserCacheLogoutHandler implements LogoutHandler {

        private UserCache userCache;

        @Override
        public void logout(HttpServletRequest request, HttpServletResponse response,
                Authentication authentication) {
            userCache.removeUserFromCache(((UserDetails) authentication.getPrincipal()).getUsername());
        }

        public void setUserCache(UserCache userCache) {
            this.userCache = userCache;
        }
    }

}