Spring Security OAuth2.0(22):分布式系统授权-搭建网关

📅 2026/7/15 4:42:17
Spring Security OAuth2.0(22):分布式系统授权-搭建网关
本章代码已提交至Gitee: https://gitee.com/lengcz/distributed-security01.git文章目录网关创建网关安全配置网关网关整合OAuth2.0 有两种思路一种是认证服务器生成jwt令牌所有请求统一在网关层验证判断权限等操作另一种是由各资源服务器处理网关只做请求转发。这里选择第一种我们把API网关作为OAuth2.0的资源服务器角色实现接入客户端权限拦截和令牌解析并转发当前登录用户信息jsonToken)给微服务这样下游微服务就不需要关心令牌格式解析以及OAuth2.0相关机制了。API网关在认证授权体系里主要负责两件事1作为OAuth2.0的资源服务器角色实现接入方权限拦截2令牌解析并转发当前登录用户信息明文token)给微服务微服务拿到明文token(明文token中包含登录用户的身份和权限信息后也需要做两件事用户授权拦截看当前用户是否有权限访问该资源将用户信息存储金当前线程上下文有利于后续业务逻辑随时获取当前用户信息创建网关创建网关 distributed-security-gatewaypom.xml?xml version1.0 encodingUTF-8?projectxmlnshttp://maven.apache.org/POM/4.0.0xmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsdparentartifactIddistributed-security/artifactIdgroupIdcom.it2.security/groupIdversion1.0-SNAPSHOT/version/parentmodelVersion4.0.0/modelVersionartifactIddistributed-security-gateway/artifactIddependenciesdependencygroupIdorg.springframework.cloud/groupIdartifactIdspring-cloud-starter-netflix-eureka-client/artifactId/dependencydependencygroupIdorg.springframework.cloud/groupIdartifactIdspring-cloud-starter-netflix-hystrix/artifactId/dependencydependencygroupIdorg.springframework.cloud/groupIdartifactIdspring-cloud-starter-netflix-ribbon/artifactId/dependencydependencygroupIdorg.springframework.cloud/groupIdartifactIdspring-cloud-starter-openfeign/artifactId/dependencydependencygroupIdcom.netflix.hystrix/groupIdartifactIdhystrix-javanica/artifactId/dependencydependencygroupIdorg.springframework.retry/groupIdartifactIdspring-retry/artifactId/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-actuator/artifactId/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-web/artifactId/dependencydependencygroupIdorg.springframework.cloud/groupIdartifactIdspring-cloud-starter-netflix-zuul/artifactId/dependencydependencygroupIdorg.springframework.cloud/groupIdartifactIdspring-cloud-starter-security/artifactId/dependencydependencygroupIdorg.springframework.cloud/groupIdartifactIdspring-cloud-starter-oauth2/artifactId/dependencydependencygroupIdorg.springframework.security/groupIdartifactIdspring-security-jwt/artifactId/dependencydependencygroupIdjavax.interceptor/groupIdartifactIdjavax.interceptor-api/artifactId/dependencydependencygroupIdcom.alibaba/groupIdartifactIdfastjson/artifactId/dependencydependencygroupIdorg.projectlombok/groupIdartifactIdlombok/artifactId/dependency/dependencies/projectapplication.propertiesspring.application.namegateway-server server.port53010 spring.main.allow-bean-definition-overriding true logging.level.root info logging.level.org.springframework info zuul.retryable true zuul.ignoredServices * zuul.add-host-header true zuul.sensitiveHeaders * zuul.routes.uaa-service.stripPrefix false zuul.routes.uaa-service.path /uaa/** zuul.routes.order-service.stripPrefix false zuul.routes.order-service.path /order/** eureka.client.serviceUrl.defaultZone http://localhost:53000/eureka/ eureka.instance.preferIpAddress true eureka.instance.instance-id ${spring.application.name}:${server.port} management.endpoints.web.exposure.include refresh,health,info,env feign.hystrix.enabled true feign.compression.request.enabled true feign.compression.request.mime-types[0] text/xml feign.compression.request.mime-types[1] application/xml feign.compression.request.mime-types[2] application/json feign.compression.request.min-request-size 2048 feign.compression.response.enabled true feign.httpclient.connection-timeout10000启动类importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;importorg.springframework.cloud.client.discovery.EnableDiscoveryClient;importorg.springframework.cloud.netflix.zuul.EnableZuulProxy;SpringBootApplicationEnableZuulProxy//网关zuul代理EnableDiscoveryClient//需要从注册中心拿地址publicclassGatewayServer{publicstaticvoidmain(String[]args){SpringApplication.run(GatewayServer.class,args);}}统一认证服务UAA与统一用户服务都是网关下微服务需要在网关下新增路由配置zuul.routes.uaa-service.stripPrefix false zuul.routes.uaa-service.path /uaa/** zuul.routes.order-service.stripPrefix false zuul.routes.order-service.path /order/**配置ResourceServerConfigpackagecom.it2.security.distributed.gateway.config;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.context.annotation.Configuration;importorg.springframework.security.config.annotation.web.builders.HttpSecurity;importorg.springframework.security.config.http.SessionCreationPolicy;importorg.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;importorg.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;importorg.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;importorg.springframework.security.oauth2.provider.token.TokenStore;ConfigurationpublicclassResourceServerConfig{publicstaticfinalStringRESOURCE_IDres1;AutowiredprivateTokenStoretokenStore;//uaa资源服务配置ConfigurationEnableResourceServerpublicclassUAAServerConfigextendsResourceServerConfigurerAdapter{AutowiredprivateTokenStoretokenStore;Overridepublicvoidconfigure(ResourceServerSecurityConfigurerresources)throwsException{resources.resourceId(RESOURCE_ID)//资源id.tokenStore(tokenStore)//自己验证令牌// .tokenServices(tokenService()) //验证令牌的服务.stateless(true);}Overridepublicvoidconfigure(HttpSecurityhttp)throwsException{http.authorizeRequests().antMatchers(/uaa/**).permitAll();}}//uaa资源服务配置ConfigurationEnableResourceServerpublicclassOrderServerConfigextendsResourceServerConfigurerAdapter{AutowiredprivateTokenStoretokenStore;Overridepublicvoidconfigure(ResourceServerSecurityConfigurerresources)throwsException{resources.resourceId(RESOURCE_ID)//资源id.tokenStore(tokenStore)//自己验证令牌// .tokenServices(tokenService()) //验证令牌的服务.stateless(true);}Overridepublicvoidconfigure(HttpSecurityhttp)throwsException{http.authorizeRequests().antMatchers(/order/**).access(#oauth2.hasScope(ROLE_API));}}//配置其他资源服务}上面定义了两个微服务的资源其中UAAServerConfig指定了若请求匹配/uaa/网关不进行拦截。OrderServerConfig指定了若请求匹配/order/也就是访问统一用户服务接入客户端需要有scope中包含read并且authorities权限中需要包含ROLE_USER由于res1这个接入客户端read包括ROLE_ADMINROLE_USERROLE_API三个权限。安全配置这个资源服务同样也需要接入安全配置。importorg.springframework.context.annotation.Configuration;importorg.springframework.security.config.annotation.web.builders.HttpSecurity;importorg.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;ConfigurationpublicclassWebSecurityConfigextendsWebSecurityConfigurerAdapter{//配置安全拦截机制protectedvoidconfigure(HttpSecurityhttp)throwsException{http.authorizeRequests().antMatchers(/**).permitAll().and().csrf().disable();}}