SpringCloud配置OAuth2权限

0

配置SpringCloud环境OAuth2权限问题:

  • 配置Feign调用Token
  • 配置内网IP允许直接访问
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.AuthenticationException;
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.web.AuthenticationEntryPoint;

import com.acgist.boot.Message;
import com.acgist.boot.MessageCode;
import com.acgist.boot.WebUtils;

import feign.RequestInterceptor;
import feign.RequestTemplate;

/**
 * 资源安全
 * 
 * @author yusheng
 */
@Configuration
@ConditionalOnClass(EnableResourceServer.class)
@EnableResourceServer
public class ResourceServerAutoConfiguration extends ResourceServerConfigurerAdapter {

	@Value("#{'${system.permit.ip:}'.split(',')}")
	private String[] permitIp;
	@Value("#{'${system.permit.url:}'.split(',')}")
	private String[] permitUrl;
	
	@Bean
	@ConditionalOnMissingBean
	public RequestInterceptor feignRequestInterceptor() {
		
		return new RequestInterceptor() {

			@Override
			public void apply(RequestTemplate requestTemplate) {
				requestTemplate.header(TokenThreadLocal.AUTHORIZATION_HEADER, new String[] { TokenThreadLocal.get() });
			}
			
		};
	}

	@Override
	public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
		// 错误
		resources.authenticationEntryPoint(new AuthenticationEntryPoint() {
			@Override
			@SuppressWarnings("deprecation")
			public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
//				throw MessageCodeException.of(authException, MessageCode.CODE_3401, "没有授权");
				response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
				response.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE);
				response.getWriter().write(Message.fail(MessageCode.CODE_3401, "没有授权").toString());
			}
		});
	}
	
	@Override
	public void configure(HttpSecurity security) throws Exception {
		security
			.csrf().disable()
			.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
			.and()
			.authorizeRequests()
			.antMatchers(
				// 图标
				"/favicon.ico",
				// swagger
				"/v2/api-docs", "/swagger-ui/**", "/swagger-resources/**"
			).permitAll()
			// 配置允许IP
			.requestMatchers(request -> {
				final String clientIP = WebUtils.clientIP(request);
				return ArrayUtils.contains(this.permitIp, clientIP);
			}).permitAll()
			// 配置允许URL
			.antMatchers(this.permitUrl).permitAll()
			.anyRequest().authenticated();
	}
	
}
import javax.servlet.http.HttpServletRequest;

import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * Token传递
 * 
 * @author acgist
 */
public class TokenThreadLocal {

	/**
	 * 认证头部
	 */
	public static final String AUTHORIZATION_HEADER = "Authorization";
	/**
	 * 数据绑定
	 */
	private static final InheritableThreadLocal<String> LOCAL = new InheritableThreadLocal<>();
	
	/**
	 * @return Token
	 */
	public static final String get() {
		String token = null;
		final RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
		if (requestAttributes != null) {
			final HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
			token = request.getHeader(AUTHORIZATION_HEADER);
		}
		if(token == null) {
			token = LOCAL.get();
		}
		return token;
	}
	
	/**
	 * 设置Token(异步线程调用前调用)
	 */
	public static final void set() {
		LOCAL.set(get());
		RequestContextHolder.setRequestAttributes(RequestContextHolder.getRequestAttributes(), true);
	}
	
}