美文网首页微服务架构和实践java程序员
第十节 spring could security实现OAuth

第十节 spring could security实现OAuth

作者: 勃列日涅夫 | 来源:发表于2018-09-05 22:31 被阅读43次

    使用spring could security实现OAuth2来控制服务中api的安全

    使用Oauth2的授权码模式

    1. 首先创建一个安全服务spring security,用于控制身份验证和授权。
    • 增加pom依赖
     <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-security</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-oauth2</artifactId>
            </dependency>
    
    • 在启动类上增加@EnableResourceServer表示允许该服务作为资源服务器使用
      同时启用@EnableAuthorizationServer表示启用授权服务器,可参照如下配置:
    //启用资源服务器
    @SpringBootApplication
    @RestController
    @EnableResourceServer
    public class SecurityApp {
    
        @RequestMapping("/user")
        public Principal user(Principal user) {
            return user;
        }
    
        public static void main(String[] args) {
            SpringApplication.run(SecurityApp.class, args);
        }
    //同时配置oauth2授权服务器
        @Configuration
        @EnableAuthorizationServer
        protected static class OAuth2Config extends AuthorizationServerConfigurerAdapter {
    
            @Autowired
            private AuthenticationManager authenticationManager;
    
            @Override
            public void configure(AuthorizationServerEndpointsConfigurer endpointsConfigurer) throws Exception {
                endpointsConfigurer.authenticationManager(authenticationManager);
            }
    
            @Override
            public void configure(ClientDetailsServiceConfigurer clientDetailsServiceConfigurer) throws Exception {
                //作为示例使用硬编码配置
                clientDetailsServiceConfigurer.inMemory()
                        .withClient("client")
                        .secret("clientsecret")
                        .authorizedGrantTypes("authorization_code", "refresh_token", "implicit", "password", "client_credentials")
                        .scopes("apiAccess");
            }
        }
    }
    
    • 配置文件
    info:
        component:
            Security Server
    
    server:
        port: 9001
        ssl:
            key-store: classpath:keystore.jks
            key-store-password: password
            key-password: password
    # contextPath表示上下文;路径
        contextPath: /auth
    # 暂时使用硬编码
    security:
        user:
            password: password
    
    logging:
        level:
            org.springframework.security: DEBUG
    
    • 除此之外,在security-server服务启用https,加密传输的方式,配置如下:
      1) 创建证书嵌入到项目中
    keytool -genkey -keyalg RSA -alias selfsigned -keystore keystore.jks -ext san=dns:localhost  -storepass password -validity 365 -keysize 2048
    

    执行过程如下图:


    制作开发证书

    将证书放入项目,并配置如图:


    图片.png
    • 注意:使用-ext来定义主题设备名称(san). 可以使用浏览器或者Openssl下载证书,
    1. 有了安全服务器,现在创建api server作为对外公开的api并通过安全服务器认证
    • 增加pom依赖
     <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-security</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-oauth2</artifactId>
            </dependency>
    
    • 将api-server作为资源服务器 添加@EnableResourceServer
    @SpringBootApplication
    @EnableEurekaClient
    @EnableCircuitBreaker
    @EnableResourceServer
    @Configuration
    @ComponentScan({"com.xzg.api.service", "com.xzg.common"})
    public class ApiApp {
    
        private static final Logger LOG = LoggerFactory.getLogger(ApiApp.class);
    
        static {
            // for localhost testing only
            LOG.warn("Will now disable hostname check in SSL, only to be used during development");
            HttpsURLConnection.setDefaultHostnameVerifier((hostname, sslSession) -> true);
        }
    
        @Value("${app.rabbitmq.host:localhost}")
        String rabbitMqHost;
    
        @Bean
        public ConnectionFactory connectionFactory() {
            LOG.info("Create RabbitMqCF for host: {}", rabbitMqHost);
            CachingConnectionFactory connectionFactory = new CachingConnectionFactory(rabbitMqHost);
            return connectionFactory;
        }
    
        @LoadBalanced
        @Bean
        RestTemplate restTemplate() {
            return new RestTemplate();
        }
    
        public static void main(String[] args) {
            LOG.info("Register MDCHystrixConcurrencyStrategy");
            HystrixPlugins.getInstance().registerConcurrencyStrategy(new MDCHystrixConcurrencyStrategy());
            SpringApplication.run(ApiApp.class, args);
        }
    }
    
    • 配置文件
    info:
      component: API Service
    
    spring:
        application:
            name: api-service
        aop:
            proxyTargetClass: true
    
    server:
      port: 7771
    
    security:
      oauth2:
        resource:
          userInfoUri: https://localhost:9001/auth/user
    
    management:
      security:
        enabled: false
    # 其他略
    

    依次启动eureka-server security-server和api-server来测试

    spring boot 实现

    相关文章

      网友评论

        本文标题:第十节 spring could security实现OAuth

        本文链接:https://www.haomeiwen.com/subject/qonnwftx.html