package com.dhcc.finance.config;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import com.dhcc.common.config.bean.BeforeRequestFilter;
import com.dhcc.common.config.bean.DefineAccessDeniedHandler;
import com.dhcc.common.config.bean.DefineAuthenticationEntryPoint;
import com.dhcc.common.constant.SysConstants;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * @功能描述:资源服务配置
 * @author chenrui
 * @date 2018年12月5日 下午6:08:36
 * @修改日志:
 */
@Slf4j
@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
	
	@Autowired
	DefaultTokenServices jwtTokenServices;
	
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
    	super.configure(resources);
        resources
        	.resourceId(SysConstants.RESOURCE_IDS.DHCC_FINANCE_MS_RESOURCE_ID)
        	.stateless(true)
        	.authenticationEntryPoint(new DefineAuthenticationEntryPoint()) // 用来解决匿名用户访问无权限资源时的异常
        	.accessDeniedHandler(new DefineAccessDeniedHandler()) // 用来解决认证过的用户访问无权限资源时的异常
        	.tokenServices(jwtTokenServices);
        log.info("ResourceServerSecurityConfigurer is complete!");
    }
    
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable();
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
        	.exceptionHandling()
	        .authenticationEntryPoint(new DefineAuthenticationEntryPoint()) // 用来解决匿名用户访问无权限资源时的异常
	        .accessDeniedHandler(new DefineAccessDeniedHandler()) // 用来解决认证过的用户访问无权限资源时的异常
        .and()
	        .authorizeRequests()
	        /*.antMatchers("/**").permitAll()*/
	        .antMatchers(SysConstants.PERMIT_ENDPOINT).permitAll()
	        .anyRequest().authenticated()
        .and()
        	.addFilterBefore(new BeforeRequestFilter(), UsernamePasswordAuthenticationFilter.class);
        log.info("HttpSecurity is complete!");
    }
    
}