spring cloud下基于oauth2认证授权的实现 -欧洲杯足彩官网

`
wiselyman
  • 浏览: 2076971 次
  • 性别:
  • 来自: 合肥
博主相关
  • 博客
  • 微博
  • 相册
  • 收藏
  • 博客专栏
    点睛spring4.1
    浏览量:80745
    点睛spring mvc4...
    浏览量:129940
    社区版块
    • ( 11)
    • ( 19)
    • ( 0)
    存档分类
    最新评论

    spring cloud下基于oauth2认证授权的实现

     

    spring cloud需要使用oauth2来实现多个微服务的统一认证授权,通过向oauth服务发送某个类型的grant type进行集中认证和授权,从而获得access_token,而这个token是受其他微服务信任的,我们在后续的访问可以通过access_token来进行,从而实现了微服务的统一认证授权。

     格式正常地址:包含源码

    本示例提供了四大部分:

    • discovery-service:服务注册和发现的基本模块
    • auth-server:oauth2认证授权中心
    • order-service:普通微服务,用来验证认证和授权
    • api-gateway:边界网关(所有微服务都在它之后)

    oauth2中的角色:

    • resource server:被授权访问的资源
    • authotization server:oauth2认证授权中心
    • resource owner: 用户
    • client:使用api的客户端(如android 、ios、web app)

    grant type:

    • authorization code:用在服务端应用之间
    • implicit:用在移动app或者web app(这些app是在用户的设备上的,如在手机上调起微信来进行认证授权)
    • resource owner password credentials(password):应用直接都是受信任的(都是由一家公司开发的,本例子使用)
    • client credentials:用在应用api访问。

    1.基础环境

    使用postgres作为账户存储,redis作为token存储,使用docker-compose在服务器上启动postgresredis

    redis:
      image: sameersbn/redis:latest
      ports:
        - "6379:6379"
      volumes:
        - /srv/docker/redis:/var/lib/redis:z
      restart: always
    postgresql:
      restart: always
      image: sameersbn/postgresql:9.6-2
      ports:
        - "5432:5432"
      environment:
        - debug=false
        - db_user=wang
        - db_pass=yunfei
        - db_name=order
      volumes:
        - /srv/docker/postgresql:/var/lib/postgresql:z
    

    2.auth-server

    2.1 oauth2服务配置

    redis用来存储token,服务重启后,无需重新获取token.

    @configuration
    @enableauthorizationserver
    public class authorizationserverconfig extends authorizationserverconfigureradapter {
        @autowired
        private authenticationmanager authenticationmanager;
        @autowired
        private redisconnectionfactory connectionfactory;
        @bean
        public redistokenstore tokenstore() {
            return new redistokenstore(connectionfactory);
        }
        @override
        public void configure(authorizationserverendpointsconfigurer endpoints) throws exception {
            endpoints
                    .authenticationmanager(authenticationmanager)
                    .tokenstore(tokenstore());
        }
        @override
        public void configure(authorizationserversecurityconfigurer security) throws exception {
            security
                    .tokenkeyaccess("permitall()")
                    .checktokenaccess("isauthenticated()");
        }
        @override
        public void configure(clientdetailsserviceconfigurer clients) throws exception {
            clients.inmemory()
                    .withclient("android")
                    .scopes("xx") //此处的scopes是无用的,可以随意设置
                    .secret("android")
                    .authorizedgranttypes("password", "authorization_code", "refresh_token")
                .and()
                    .withclient("webapp")
                    .scopes("xx")
                    .authorizedgranttypes("implicit");
        }
    }
    

    2.2 resource服务配置

    auth-server提供user信息,所以auth-server也是一个resource server

    @configuration
    @enableresourceserver
    public class resourceserverconfig extends resourceserverconfigureradapter {
        @override
        public void configure(httpsecurity http) throws exception {
            http
                    .csrf().disable()
                    .exceptionhandling()
                    .authenticationentrypoint((request, response, authexception) -> response.senderror(httpservletresponse.sc_unauthorized))
                .and()
                    .authorizerequests()
                    .anyrequest().authenticated()
                .and()
                    .httpbasic();
        }
    }
    
    @restcontroller
    public class usercontroller {
        @getmapping("/user")
        public principal user(principal user){
            return user;
        }
    }
    

    2.3 安全配置

    @configuration
    public class securityconfig extends websecurityconfigureradapter {
        @bean
        public userdetailsservice userdetailsservice(){
            return new domainuserdetailsservice();
        }
        @bean
        public passwordencoder passwordencoder() {
            return new bcryptpasswordencoder();
        }
        @override
        protected void configure(authenticationmanagerbuilder auth) throws exception {
            auth
                    .userdetailsservice(userdetailsservice())
                    .passwordencoder(passwordencoder());
        }
        @bean
        public securityevaluationcontextextension securityevaluationcontextextension() {
            return new securityevaluationcontextextension();
        }
        //不定义没有password grant_type
        @override
        @bean
        public authenticationmanager authenticationmanagerbean() throws exception {
            return super.authenticationmanagerbean();
        }
    }
    

    2.4 权限设计

    采用用户(sysuser) 角色(sysrole) 权限(sysauthotity)设置,彼此之间的关系是多对多。通过domainuserdetailsservice 加载用户和权限。

    2.5 配置

    spring:
      profiles:
        active: ${spring_profiles_active:dev}
      application:
          name: auth-server
      jpa:
        open-in-view: true
        database: postgresql
        show-sql: true
        hibernate:
          ddl-auto: update
      datasource:
        platform: postgres
        url: jdbc:postgresql://192.168.1.140:5432/auth
        username: wang
        password: yunfei
        driver-class-name: org.postgresql.driver
      redis:
        host: 192.168.1.140
    server:
      port: 9999
    eureka:
      client:
        serviceurl:
          defaultzone: http://${eureka.host:localhost}:${eureka.port:8761}/eureka/
    logging.level.org.springframework.security: debug
    logging.leve.org.springframework: debug
    ##很重要
    security:
      oauth2:
        resource:
          filter-order: 3
    

    2.6 测试数据

    data.sql里初始化了两个用户admin->role_admin->query_demo,wyf->role_user

    3.order-service

    3.1 resource服务配置

    @configuration
    @enableresourceserver
    public class resourceserverconfig  extends resourceserverconfigureradapter{
        @override
        public void configure(httpsecurity http) throws exception {
            http
                    .csrf().disable()
                    .exceptionhandling()
                    .authenticationentrypoint((request, response, authexception) -> response.senderror(httpservletresponse.sc_unauthorized))
                .and()
                    .authorizerequests()
                    .anyrequest().authenticated()
                .and()
                    .httpbasic();
        }
    }
    

    3.2 用户信息配置

    order-service是一个简单的微服务,使用auth-server进行认证授权,在它的配置文件指定用户信息在auth-server的地址即可:

    security:
      oauth2:
        resource:
          id: order-service
          user-info-uri: http://localhost:8080/uaa/user
          prefer-token-info: false
    

    3.3 权限测试控制器

    具备authorityquery-demo的才能访问,即为admin用户

    @restcontroller
    public class democontroller {
        @getmapping("/demo")
        @preauthorize("hasauthority('query-demo')")
        public string getdemo(){
            return "good";
        }
    }
    

    4 api-gateway

    api-gateway在本例中有2个作用:

    • 本身作为一个client,使用implicit

       

    • 作为外部app访问的方向代理

    4.1 关闭csrf并开启oauth2 client支持

    @configuration
    @enableoauth2sso
    public class securityconfig extends websecurityconfigureradapter{
        @override
        protected void configure(httpsecurity http) throws exception {
            http.csrf().disable();
        }
    }
    

    4.2 配置

    zuul:
      routes:
        uaa:
          path: /uaa/**
          sensitiveheaders:
          serviceid: auth-server
        order:
          path: /order/**
          sensitiveheaders:
          serviceid: order-service
      add-proxy-headers: true
    security:
      oauth2:
        client:
          access-token-uri: http://localhost:8080/uaa/oauth/token
          user-authorization-uri: http://localhost:8080/uaa/oauth/authorize
          client-id: webapp
        resource:
          user-info-uri: http://localhost:8080/uaa/user
          prefer-token-info: false
    

    5 演示

    5.1 客户端调用

    使用postmanhttp://localhost:8080/uaa/oauth/token发送请求获得access_token(admin用户的如7f9b54d4-fd25-4a2c-a848-ddf8f119230b)

    • admin用户




    • wyf用户



    5.2 api-gateway中的webapp调用

    暂时没有做测试,下次补充。

     

    4
    1
    分享到:
    |
    评论
    10 楼 淡炒番茄 2018-07-31  
    博主,你这个认证服务器是个单应用,作微服务、我要用几个认证服务器怎么做呢?
    9 楼 dyj025 2018-04-18  
    wiselyman 写道
    dyj025 写道
    楼主源码访问不了.可否移到github.com?感谢!

    https://github.com/wiselyman/uaa-zuul

    代码运行不起来啊.auth-server运行直接报:propertyreferenceexception: no property examplewithrange found for type sysauthority!
    8 楼 wiselyman 2018-04-15  
    dyj025 写道
    楼主源码访问不了.可否移到github.com?感谢!

    https://github.com/wiselyman/uaa-zuul
    7 楼 dyj025 2018-04-12  
    楼主源码访问不了.可否移到github.com?感谢!
    6 楼 wiselyman 2018-01-11  
    w1054993544 写道
    博主你好,我想请问一下:gateway采取集群模式,所有的微服务都没有公网ip,如下设置就不能满足了:
    access-token-uri: http://localhost:8080/uaa/oauth/token
    user-authorization-uri: http://localhost:8080/uaa/oauth/authorize
    user-info-uri: http://localhost:8080/uaa/user。
    针对这种情况如何处理呢?

    可以使用服务名(服务发现)替换localhost:8080
    5 楼 2018-01-02  
    博主你好,我想请问一下:gateway采取集群模式,所有的微服务都没有公网ip,如下设置就不能满足了:
    access-token-uri: http://localhost:8080/uaa/oauth/token
    user-authorization-uri: http://localhost:8080/uaa/oauth/authorize
    user-info-uri: http://localhost:8080/uaa/user。
    针对这种情况如何处理呢?
    4 楼 wiselyman 2017-12-26  
    星际牛仔 写道
    博主,有源码吗?

    http://www.wisely.top/2017/06/14/spring-cloud-oauth2-zuul/
    3 楼 wiselyman 2017-12-26  
    ddnzero 写道
    求一份源码

    http://www.wisely.top/2017/06/14/spring-cloud-oauth2-zuul/
    2 楼 2017-12-21  
    求一份源码
    1 楼 2017-11-10  
    博主,有源码吗?

    相关推荐

      springcloud(八):api网关整合oauth2认证授权服务。

      spring cloud 安全:集成oauth2实现身份认证和单点登录 示例代码 spring cloud 安全:集成oauth2实现身份认证和单点登录 示例代码

      springcloud整合oauth2和jwt实现权限认证,整合mybaits

      主要介绍了spring cloud下基于oauth2认证授权的实现示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

      基于 spring cloud hoxton 、spring boot 2.2、 oauth2 的rbac权限管理系统 基于数据驱动视图的理念封装 ant design vue,即使没有 vue 的使用经验也能快速上手 提供 lambda 、stream api 、webflux 的生产实践 ...

      基于 spring cloud 2021 、spring boot 2.7、 oauth2 的 rbac 权限管理系统源码

      系统说明:基于 spring cloud 2021 、spring boot 2.6、 oauth2 的 rbac 权限管理系统 基于数据驱动视图的理念封装 element-ui,即使没有 vue 的使用经验也能快速上手 提供对常见容器化支持 docker、kubernetes、...

      springcloud springboot oauth2 spring security redis实现的微服务统一认证授权

      spring cloud oauth2使用授权码模式实现登录验证授权

      基于spring cloud finchley.sr1 网关基于 spring cloud gateway 提供consul 服务注册发现版本pigxc 最终一致性的分布式事务欧洲杯足彩官网的解决方案 图形化代码生成,不会vue也能做到敏捷开发 基于 spring security oauth 深度定制...

      spring cloud框架下的单点登录sso技术 oauth2实现的认证 授权 以及zuul作为网关路由 可以参考学习使用

      基于spring cloud alibaba,oauth2,基于vue的后台权限管理框架,集成了基于mq的可靠消息的分布式事务欧洲杯足彩官网的解决方案。

      基于springcloud2.1的微服务开发脚手架,整合了spring-security-oauth2、nacos、feign、sentinel、springcloud-gateway等。服务治理方面引入elasticsearch、skywalking、springboot-admin、zipkin等,让项目开发快速...

      springcloud-分享版: 基于spring cloud、oauth2.0的前后端分离的系统。 通用rbac权限设计及其数据权限和分库分表 支持服务限流、动态路由、灰度发布、 支持常见登录方式, 多系统sso登录 基于 spring cloud hoxton ...

      该项目采用了springcloud oauth2实现了服务的单点登录以及授权服务与客户端之间的访问方式

      第七章 springcloud oauth2认证中心-搭建认证中心.pdf

      spring boot 2.0.8.release 、spring cloud finchley.sr2 、spring security oauth2 1. 减少中间件依赖 2.0 依赖中间件只需要 mysql、redis 即可,提供傻瓜式部署方案,大大缩减了上手和使用成本。 2. 提供常见...

      spring boot spring security oauth2.0,sprint cloud spring security oauth2集成。四种认证方式。附带有代码,和案例,案例,还有视频链接。我保证看完就回,如果视频链接失效,评论回复我,我单独再给你一份。

    global site tag (gtag.js) - google analytics
    网站地图