微服务架构和实践java程序员

第十节 spring could security实现OAuth

2018-09-05  本文已影响43人  勃列日涅夫

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

使用Oauth2的授权码模式

  1. 首先创建一个安全服务spring security,用于控制身份验证和授权。
 <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>
//启用资源服务器
@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
keytool -genkey -keyalg RSA -alias selfsigned -keystore keystore.jks -ext san=dns:localhost  -storepass password -validity 365 -keysize 2048

执行过程如下图:


制作开发证书

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


图片.png
  1. 有了安全服务器,现在创建api server作为对外公开的api并通过安全服务器认证
 <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>
@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 实现

上一篇下一篇

猜你喜欢

热点阅读