Spring Cloud oAuth2(一)搭建授权服务器以及访问

系列文章

Spring Cloud oAuth2(一)搭建授权服务器以及访问

Spring Cloud oAuth2(二)搭建资源服务器以及测试

SpringCloud OAuth2 + JWT 认证授权(一)授权服务器

SpringCloud OAuth2 + JWT 认证授权(二)资源服务器

前言

这里在对springcloud ouath2学习的过程中遇到的问题和解决办法做一个简单的总结。

开始

用Spring Cloud oAuth2的前提是必须对Spring Security有所了解,两者是相辅相成的,首先让我们对Spring Cloud oAuth2有个大概的了解:

  • Spring Cloud oAuth2 主要应用于认证与授权,场景多是在不提供密码的前提下授权第三方应用访问用户的资源。( 参考:什么是oAth2)

  • Spring Cloud oAuth2主要有三大块:资源所有者、授权服务提供者、客户端 。( 参考:oAuth2交互流程)

授权

Spring Cloud版本Greenwich.SR2,Spring Boot版本2.1.10.RELEASE,相关pom以及配置省略。
这里只简单实现授权服务器,首先实现Spring Security权限管控三个重要的方法:

@EnableWebSecurity
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailService userDetailService;

    //配置哪些需要验证
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //1.配置所有请求都需要经过验证
        http.authorizeRequests().anyRequest().authenticated().and().csrf().disable().formLogin().permitAll();
    }

	//版本需要配置密码加密方式
    @Bean
    public PasswordEncoder passwordEncoder()
    {
        return  new BCryptPasswordEncoder();
    }


    //配置验证的方式和加密方式
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailService).passwordEncoder(passwordEncoder());
    }

    //配置验证管理器
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}

重写UserDetailsService :

//实现用户查询权限
@Service
public class UserDetailService implements UserDetailsService {

    @Autowired
    private UserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    //这里的dao层是直接实现jpa
        return userDao.findByUsername(username) ;
    }
}

简单的spring security实现就完成了,下面实现AuthorizationServerConfigurerAdapter授权逻辑:

@Configuration
@EnableAuthorizationServer
public class AutherizationServerConfig extends AuthorizationServerConfigurerAdapter {

	//注入密码验证方式,下面客户端密码也需要同样的方式
    @Autowired
    private PasswordEncoder passwordEncoder;
	
	//token放在数据库中
    @Autowired
    @Qualifier("dataSource")
    private DataSource dataSource;

	//添加授权,启用密码授权的方式
    @Autowired
    @Qualifier("authenticationManagerBean")
    private AuthenticationManager authenticationManager;

	//获取数据库中的权限等
    @Autowired
    private UserDetailService userDetailService;

    //授权服务token安全配置
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security
        		//不拦截所有获取token的访问
                .tokenKeyAccess("permitAll()")
                //验证token
                .checkTokenAccess("isAuthenticated()")
                .allowFormAuthenticationForClients();
    }

    //客户端配置
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients
        		//客户端放在内存中(可放在数据库里面或者非关系型数据库)
                .inMemory()
                //客户端id
                .withClient("smith")
                //密码加密方式(版本必须,不然报错)
                .secret(passwordEncoder.encode("smith12345"))
                //这里有四种授权方式,下面专门细说
                .authorizedGrantTypes("refresh_token","password")
                //域
                .scopes("all");

    }


    //授权节点服务配置
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                //存储在jdbc里面
                .tokenStore(new JdbcTokenStore(dataSource))
                .authenticationManager(authenticationManager)
                .userDetailsService(userDetailService);
    }
}

四种授权方式以及访问方式

四种方式得不同在于客户端配置(ClientDetailsServiceConfigurer)的地方,下面代码只列出对客户端配置的修改。
  • 授权码方式authorization_code

    相关配置:

  		clients
                //客户端放在内存中(可放在数据库里面或者非关系型数据库)
                .inMemory()
                //客户端id
                .withClient("kevin")
                //密码加密方式(版本必须,不然报错)
                .secret(passwordEncoder.encode("kevin12345"))
                //授权码的方式
                .authorizedGrantTypes("authorization_code","refresh_token")
                //返回地址(后面会跟授权码)
                .redirectUris("http://www.baidu.com")
                //域
                .scopes("all");
     如何访问:
  1. 浏览器链接访问http://localhost:9002/auth/oauth/authorize?response_type=code&client_id=kevin&client_secret=kevin12345&redirect_uri=http://www.baidu.com&scope=all
    第一次授权需要登陆验证

    登陆过后点击授权:
    在这里插入图片描述
    授权后获得验证码:
    在这里插入图片描述

 		 clients
                //客户端放在内存中(可放在数据库里面或者非关系型数据库)
                .inMemory()
                //客户端id
                .withClient("kevin")
                //密码加密方式(版本必须,不然报错)
                .secret(passwordEncoder.encode("kevin12345"))
                //这里有四种授权方式,下面专门细说
                .authorizedGrantTypes("password","refresh_token")
                //域
                .scopes("all");
     如何访问:
		clients
                //客户端放在内存中(可放在数据库里面或者非关系型数据库)
                .inMemory()
                //客户端id
                .withClient("kevin")
                //密码加密方式(版本必须,不然报错)
                .secret(passwordEncoder.encode("kevin12345"))
                //这里有四种授权方式,下面专门细说
                .authorizedGrantTypes("implicit","refresh_token")
                .redirectUris("http://www.baidu.com")
                //域
                .scopes("all");
     如何访问:
  1. 浏览器访问http://localhost:9002/auth/oauth/authorize?response_type=token&client_id=kevin&client_secret=kevin12345&redirect_uri=http://www.baidu.com&scope=all
    在这里插入图片描述
  • 客户端方式client_credentials
    相关配置:
  		clients
                //客户端放在内存中(可放在数据库里面或者非关系型数据库)
                .inMemory()
                //客户端id
                .withClient("kevin")
                //密码加密方式(版本必须,不然报错)
                .secret(passwordEncoder.encode("kevin12345"))
                //这里有四种授权方式,下面专门细说
                .authorizedGrantTypes("client_credentials","refresh_token")
                //域
                .scopes("all");
     如何访问:
  1. post请求http://localhost:9002/auth/oauth/token?grant_type=client_credentials&client_id=kevin&client_secret=kevin12345

在这里插入图片描述
四种授权模式得使用场景需要自己去领会,这里使用较少,不做赘述。

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: Spring Cloud OAuth2 Gateway是基于Spring Cloud Gateway和Spring Security OAuth2的网关服务,用于保护和管理微服务的访问权限。它提供了一种统一的认证和授权机制,可以集成多种认证方式,如基于密码、令牌、JWT等的认证方式,同时也支持多种授权方式,如基于角色、权限等的授权方式。通过Spring Cloud OAuth2 Gateway,可以实现微服务的安全访问和管理,提高系统的安全性和可靠性。 ### 回答2: Spring Cloud OAuth2 Gateway 是基于 Spring Cloud 的一种解决方案,用于构建微服务架构下的网关服务。 Spring Cloud OAuth2 Gateway 并不直接处理身份认证和授权,而是作为一个网关服务,负责转发请求和处理反向代理等功能。它集成了 Spring Cloud 的相关组件,比如 Eureka、Ribbon 和 Zuul,通过这些组件的协同作用,可以实现服务的负载均衡、熔断、动态路由等功能。 在 Spring Cloud OAuth2 Gateway 中,OAuth2 认证和授权是通过与认证授权服务(通常是 Spring Security OAuth2)进行协作来实现的。当客户端发起请求时,请求会先到达 Gateway,然后 Gateway 会将请求代理到认证授权服务,认证授权服务会对请求进行认证和授权,并返回相应的结果。认证和授权通过后,Gateway 会将请求转发到相应的微服务。 Spring Cloud OAuth2 Gateway 还提供了可扩展的过滤器机制,可以对请求进行预处理和后处理,比如添加请求头、修改请求内容等。使用过滤器可以实现一些自定义的功能,比如统一鉴权、请求日志记录等。 总结来说,Spring Cloud OAuth2 Gateway 是一个基于 Spring Cloud 的网关服务,用于处理微服务架构下的请求转发和反向代理。它与认证授权服务协作,实现了 OAuth2 认证和授权的功能,并提供了过滤器机制来增强功能和定制化处理。 ### 回答3: Spring Cloud Gateway 是基于Spring WebFlux 提供的一个路由服务,使用它可以轻松实现网关的搭建和管理,并且支持代理请求、路由转发、请求过滤等功能。同时,也提供了 OAuth2 的集成以实现网关级别的身份认证和授权OAuth2 是一种用于开放式授权的协议,它允许用户通过第三方应用或服务来授权访问受限资源。Spring Cloud Gateway OAuth2 插件提供了一种在网关中验证和认证用户的方法。 使用 Spring Cloud Gateway OAuth2 插件,可以在网关层面对资源进行保护,只允许通过授权的用户访问受限资源,并且可以根据用户的角色和权限进行进一步的控制。 配置 Spring Cloud Gateway OAuth2 需要以下步骤: 1. 引入相关的依赖,包括 spring-cloud-starter-gateway 和 spring-security-oauth2。 2. 配置 OAuth2 的认证服务器和资源服务器的信息,包括认证服务器的地址、客户端信息和资源服务器的端点等。 3. 在网关的路由配置中,指定需要受保护的路由和相应的过滤器链,例如认证过滤器和授权过滤器。 4. 可以根据需要自定义过滤器,实现一些额外的操作,比如添加请求头、修改请求路径等。 5. 启动网关应用程序。 通过 Spring Cloud Gateway OAuth2 的集成,可以实现网关层面的统一身份认证和权限控制,提高系统的安全性和可扩展性。同时,也简化了微服务中的认证和授权配置。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值