首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >第十节 spring could security实现OAuth2

第十节 spring could security实现OAuth2

作者头像
用户1418372
发布2018-09-13 10:23:45
发布2018-09-13 10:23:45
9430
举报
文章被收录于专栏:清晨我上码清晨我上码

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

  1. 首先创建一个安全服务spring security,用于控制身份验证和授权。
  • 增加pom依赖
代码语言:javascript
复制
 <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表示启用授权服务器,可参照如下配置:
代码语言:javascript
复制
//启用资源服务器
@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");
        }
    }
}
  • 配置文件
代码语言:javascript
复制
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
  1. 有了安全服务器,现在创建api server作为对外公开的api并通过安全服务器认证
  • 增加pom依赖
代码语言:javascript
复制
 <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
代码语言:javascript
复制
@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);
    }
}
  • 配置文件
代码语言:javascript
复制
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
# 其他略

启动测试。。 spring boot 实现

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018.09.05 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 使用spring could security实现OAuth2来控制服务中api的安全
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档