Spring相关之SpringSecurity使用(七)

WebSecurityConfigurerAdapter

package com.lee.security.springsecurity;

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.authentication.AuthenticationProvider;
import org.springframework.security.authentication.ProviderManager;
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.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.access.channel.ChannelProcessingFilter;
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.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.security.web.context.SecurityContextRepository;
import org.springframework.web.cors.CorsUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;

/**
 * Spring Security 配置
 *
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private AuthenticationSuccessHandler myAuthenticationSuccessHandler;

    @Autowired
    private AuthenticationFailureHandler myAuthenticationFailureHandler;

    @Autowired
    private AccessDeniedHandler myAccessDeniedHandler;

    @Autowired
    private LogoutHandler myLogoutHandler;

    @Autowired
    private AuthenticationEntryPoint myAuthenticationEntryPoint;

    @Bean
    public AuthenticationProvider authenticationProvider() {
        MyAuthentiationProvider provider = new MyAuthentiationProvider();
        return provider;
    }

//    @Bean
//    public PersistentTokenRepository persistentTokenRepository() {
//        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
//        jdbcTokenRepository.setDataSource(dataSource);
//        //启动时自动生成相应表,可以在JdbcTokenRepositoryImpl里自己执行CREATE_TABLE_SQL脚本生成表
//        //jdbcTokenRepository.setCreateTableOnStartup(true);
//        return jdbcTokenRepository;
//    }

    @Bean
    public AuthenticationSuccessHandler authenticationSuccessHandler() {
        return new MyAuthenticationSuccessHandler();
    }

    @Bean
    public AuthenticationFailureHandler authenticationFailureHandler() {
        return new MyAuthenticationFailureHandler();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authenticationProvider());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.httpBasic().disable();

        // 权限检查失败处理
        http.exceptionHandling().accessDeniedHandler(myAccessDeniedHandler)
                .authenticationEntryPoint(myAuthenticationEntryPoint);
        AbstractAuthenticationProcessingFilter myFilter = new MyAuthenticationProcessingFilter();
        myFilter.setAuthenticationManager(super.authenticationManager());
        myFilter.setAuthenticationSuccessHandler(this.myAuthenticationSuccessHandler);
        myFilter.setAuthenticationFailureHandler(this.myAuthenticationFailureHandler);
        myFilter.setAllowSessionCreation(false);
        myFilter.afterPropertiesSet();
        http.addFilterAt(myFilter, UsernamePasswordAuthenticationFilter.class);
        // 退出
        http.logout().logoutUrl("/logout").clearAuthentication(true).addLogoutHandler(myLogoutHandler).permitAll();

        // 其它请求必须经过登录验证和权限检查
        http.authorizeRequests().requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
                .antMatchers("/**/api/ent/common/**", "/**/api/user/reg/**", "/**/api/user/common/**",
                        "/**/api/*/login/*", "/**/api/feedback/**")
                .permitAll().anyRequest().access("@myPermissionService.hasPermission(request,authentication)");
        // 帮助设置跨域访问的应答头
        http.addFilterBefore(corsFilter(), ChannelProcessingFilter.class);
        http.formLogin().loginProcessingUrl("/login").usernameParameter("rrtn");

    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
    }

    @Bean
    public Filter corsFilter() {
        return new Filter() {

            @Override
            public void destroy() {

            }

            @Override
            public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
                    throws IOException, ServletException {
                HttpServletResponse response = (HttpServletResponse) resp;
                response.setHeader("Access-Control-Allow-Origin", "*");
                response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT, HEAD, TRACE");
                response.setHeader("Access-Control-Max-Age", "360000");
                response.setHeader("Access-Control-Allow-Headers",
                        "Content-Type, Content-Length, Accept, TigerfaceToken, TempToken");
                response.setHeader("Access-Control-Allow-Credentials", "false");
                chain.doFilter(req, resp);
            }

            @Override
            public void init(FilterConfig arg0) throws ServletException {

            }

        };
    }
//
//  @Bean
//  public EmbeddedServletContainerCustomizer containerCustomizer() {
//    return new EmbeddedServletContainerCustomizer() {
//      @Override
//      public void customize(ConfigurableEmbeddedServletContainer container) {
//        Ssl ssl = new Ssl();
//        //Server.jks中包含服务器私钥和证书
//        ssl.setKeyStore("tomcat.crt");
//        ssl.setKeyStorePassword("fzxh_platform");
//        container.setSsl(ssl);
//        container.setPort(8443);
//      }
//    };
//  }
//
//  @Bean
//  public EmbeddedServletContainerFactory servletContainerFactory() {
//    TomcatEmbeddedServletContainerFactory factory =
//      new TomcatEmbeddedServletContainerFactory() {
//        @Override
//        protected void postProcessContext(Context context) {
//          //SecurityConstraint必须存在,可以通过其为不同的URL设置不同的重定向策略。
//          SecurityConstraint securityConstraint = new SecurityConstraint();
//          securityConstraint.setUserConstraint("CONFIDENTIAL");
//          SecurityCollection collection = new SecurityCollection();
//          collection.addPattern("/*");
//          securityConstraint.addCollection(collection);
//          context.addConstraint(securityConstraint);
//        }
//      };
//    factory.addAdditionalTomcatConnectors(createHttpConnector());
//    return factory;
//  }
//    
//  private Connector createHttpConnector() {
//    Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
//    connector.setScheme("http");
//    connector.setSecure(false);
//    connector.setPort(8080);
//    connector.setRedirectPort(8443);
//    return connector;
//  }



}

MyPermissionService

package com.lee.security.springsecurity;

import org.springframework.security.core.Authentication;

import javax.servlet.http.HttpServletRequest;

public interface MyPermissionService {
    boolean hasPermission(HttpServletRequest request, Authentication authentication);
}

MyPermissionServiceImpl

package com.lee.security.springsecurity;

import com.lee.security.util.SystemUtil;
import org.apache.log4j.Logger;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 *    检查权限
 */
@Component(value = "myPermissionService")
public class MyPermissionServiceImpl implements MyPermissionService
{

    private static Logger logger = Logger.getLogger(MyPermissionServiceImpl.class);


    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public boolean hasPermission(HttpServletRequest request, Authentication authentication)
    {
        if(authentication.isAuthenticated()){
            return false;
        }
        String url = request.getRequestURI();
        String method = request.getMethod();
        SpringSecurityUserInfo user = SystemUtil.getCurUser();
        List grantedAuthorities=user.getGrantedAuthorities();
        for (SimpleGrantedAuthority granted:grantedAuthorities) {

            String curl = granted.getAuthority().substring(granted.getAuthority().indexOf(":")+1);
            String cmethod = granted.getAuthority().substring(0,granted.getAuthority().indexOf(":"));
            if(antPathMatcher.match(curl,url)){
                if(method.equals(cmethod)||cmethod.equals("ALL")){
                    return true;
                }
            }
        }
        return false;
    }
}

你可能感兴趣的:(Spring相关之SpringSecurity使用(七))