package com.css.simulation.resource.common.infra.config.oauth;

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.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;

import javax.annotation.Resource;

@Configuration
public class OAuth2ResourceServerConfiguration extends ResourceServerConfigurerAdapter {


    @Resource
    private OauthParameter oauthParameter;

    @Resource
    private ResourceServerTokenServices resourceServerTokenServices;

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.resourceId(oauthParameter.getResourceId())      // 资源 id
                .tokenServices(resourceServerTokenServices)    // 使用远程服务验证令牌的服务
                .stateless(true);   // 无状态模式，即无需用户登录，无 session
    }

    /**
     * 配置拦截请求，通过 scope
     */
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()   // 禁用 csrf
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)// 无状态验证
                .and()
                .authorizeRequests()
                .antMatchers("/simulation/resource/common/redis/getDictMaps").permitAll()
//                .anyRequest().access("#oauth2.hasScope('all')") // 拦截所有请求判断 scope
        ;
    }
}
