oauth2 认证服务器 资源服务器分离 使用Redis存储Token

Spring boot 版本 2.0.3.RELEASE
Spring Cloud 版本 Finchley.RELEASE
// 不使用Spring Cloud 可以不引入相关配置

Auth 项目

pom maven 引入

      <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
    <dependency>
           <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
     </dependency>
  <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-security</artifactId>
  </dependency>
  <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-security</artifactId>
   </dependency>
   
    <dependency>
          <groupId>org.springframework.security.oauth</groupId>
          <artifactId>spring-security-oauth2</artifactId>
           <version>2.3.4.RELEASE</version>
      </dependency>
   // 版本低了使用 redis保存token 有bug
  // error : org.springframework.data.redis.connection.RedisConnection.set([B[B)V
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

yml 配置

# redis 换成自己配置
spring:
  redis:
    host: 
    port: 6379
    password: 
    database: 
# 注册进入 eureka 
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8081/eureka
  instance:
    instance-id: auth
    prefer-ip-address: true

认证服务器配置 auth 项目

继承AuthorizationServerConfigurerAdapter重写相关配置

@Configuration
@EnableAuthorizationServer  //认证服务器
public class AuthenticationConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisConnectionFactory redisConnectionFactory;

    @Autowired
    private MyUserDetailsService myUserDetailsService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Bean
    public RedisTokenStore tokenStore() {
        RedisTokenStore tokenStore = new RedisTokenStore(redisConnectionFactory);
        tokenStore.setPrefix("user-token:");
        return tokenStore;
    }
/*    //  对生成的token进行二次处理 
    @Bean
    public TokenEnhancer tokenEnhancer() {
        return new RedisTokenEnhancer();
    }
*/
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security
                // 开启/oauth/token_key验证端口无权限访问
                .tokenKeyAccess("permitAll()")
                // 开启/oauth/check_token验证端口认证权限访问
                .checkTokenAccess("permitAll()")
                // 开启后请求需要带上 client_id client_secret 不需要 Basic 请求头
                // 默认请求头 Basic Base64(client_id+client_secret)
                .allowFormAuthenticationForClients();
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        // 内存方式存储
        clients.inMemory()
                .withClient("app")
                .secret(passwordEncoder.encode("123456"))
                .scopes("app")
                .authorizedGrantTypes("password", "refresh_token");
                // 认证支持类型

    }
    //  生成token的处理
    @Primary
    @Bean
    public DefaultTokenServices defaultTokenServices() {
        DefaultTokenServices tokenServices = new DefaultTokenServices();
        tokenServices.setTokenStore(tokenStore());
        // 是否支持 refreshToken
        tokenServices.setSupportRefreshToken(true);
       // 是否复用 refreshToken
        tokenServices.setReuseRefreshToken(true);
        // tokenServices.setTokenEnhancer(tokenEnhancer());
        // token有效期自定义设置,默认12小时
        tokenServices.setAccessTokenValiditySeconds(60 * 60 * 12);
        //默认30天,这里修改
        tokenServices.setRefreshTokenValiditySeconds(60 * 60 * 24 * 7);
        return tokenServices;
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {

        endpoints
                //.tokenEnhancer(tokenEnhancer())
                .tokenStore(tokenStore())
                .userDetailsService(myUserDetailsService)
                .authenticationManager(authenticationManager)
                .tokenServices(defaultTokenServices());
    }
}

security 配置

@Configuration
@EnableWebSecurity
public class BasicSecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 用户登录处理逻辑
     *
     * @return
     */
    @Override
    public UserDetailsService userDetailsService() {
        return new MyUserDetailsService();
    }

    /**
     * 加密器
     *
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }


    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS).permitAll()
                .anyRequest().authenticated()
                .and()
                .httpBasic();
    }
}

MyUserDetailsService 用户登录验证逻辑和权限处理

  @Service
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;

//    @Autowired
//    private UserContext userContext;

    @Autowired
    private TbUserService tbUserService;

    @Autowired
    private TbPermissionMapper tbPermissionMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

 /*     
        // 从数据库验证用户密码 查询用户权限
      //  rabc
       TbUser tbUser = tbUserService.getByUsername(username);
        List<GrantedAuthority> grantedAuthorities = Lists.newArrayList();
        if (tbUser != null) {
            List<TbPermission> tbPermissions = tbPermissionMapper.selectByUserId(tbUser.getId());

            tbPermissions.stream().forEach(tbPermission -> {
                if (tbPermission != null && tbPermission.getEnname() != null) {
                    GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(tbPermission.getEnname());
                    grantedAuthorities.add(grantedAuthority);
                }
            });
        }

        return new User(tbUser.getUsername(), tbUser.getPassword(), grantedAuthorities);
*/  
    // 逻辑用户名随便输入 只要密码是123456 即可登录系统并拥有admin权限
        if (username != null) {
           return new User(username, this.passwordEncoder.encode("123456"),
                    AuthorityUtils.createAuthorityList("admin"));
        } else {
            throw new UsernameNotFoundException("用户[" + username + "]不存在");
       }
    }
}

Resource 项目

版本和Auth一样

pom maven 引入

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
  </dependency>
  <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>
 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
    <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

yml配置

和Auth项目类似 引入 redis
根据自己需要是否使用eureka

Resource 配置

继承ResourceServerConfigurerAdapter

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Autowired
    private RedisConnectionFactory redisConnectionFactory;

    @Bean
    public RedisTokenStore tokenStore() {
        RedisTokenStore tokenStore = new RedisTokenStore(redisConnectionFactory);
        tokenStore.setPrefix("user-token:");
        return tokenStore;
    }


    @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();
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.tokenStore(tokenStore());
    }
}

security配置

@Configuration
@EnableWebSecurity
// @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)  // 权限验证注解
public class BasicSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS).permitAll()
                .anyRequest().authenticated()
                .and()
                .httpBasic()
                .and().csrf().disable();
    }
}

暴露 资源

@RestController
@RequestMapping("/user")
public class TestController {

      @GetMapping("/hello")
//    @PreAuthorize("hasAuthority('System')")   // 验证权限
    public String hello() {
        return "hello xxx ";
    }
}

测试

  1. 获取token
    获取token.png
    2.查看Redis 是否生成token
    查看Redis Token.png
    3.请求资源
    请求资源服务器.png

###点个赞吧!!!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
在网关中使用OAuth2和Redis的主要目的是实现身份验证和授权功能,同时使用Redis作为缓存来提高系统的性能和扩展性。 首先,OAuth2是一个开放标准的授权协议,用于授权第三方应用访问受保护的资源。在网关中,OAuth2用于验证用户的身份和授权访问请求。用户首先将其凭据提交到网关,然后网关使用OAuth2进行身份验证,以确保用户有权访问所请求的资源。 接下来,Redis是一个开源的内存数据库,用于存储和缓存数据。在网关中,Redis可以用作缓存存储,以提高访问速度和减轻后端服务的负载。网关可以将经过身份验证和授权的访问令牌(access token存储Redis中,以便在后续请求中快速验证令牌的有效性,而无需每次都向认证服务器发送请求。 为了在网关中实现OAuth2和Redis的功能,您需要进行以下配置: 1. 在网关的配置文件(通常是application.properties或application.yml)中,添加有关OAuth2和Redis的配置信息。这些配置包括认证服务器的URL、客户端ID和密钥、授权模式等。 2. 在网关的代码中,您需要使用Spring Security OAuth2库来实现OAuth2的身份验证和授权功能。您可以使用OAuth2AuthenticationProcessingFilter来拦截请求并进行身份验证。 3. 您还需要使用Redis库来连接和操作Redis数据库。您可以使用RedisTemplate或Jedis等工具类来实现与Redis的交互。通过使用Redis,您可以将访问令牌存储在缓存中,并在需要时快速检查其有效性。 总结起来,网关使用OAuth2和Redis来实现身份验证和授权功能,并通过使用Redis作为缓存来提高系统的性能和扩展性。OAuth2用于验证用户的身份和授权访问请求,而Redis用于存储访问令牌,并在需要时快速验证令牌的有效性。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [最新版微服务架构鉴权解决方案Spring Cloud Gateway + Oauth2.0+mybatis+mysql+redis+nacos 统一认证和鉴权](https://blog.csdn.net/qq_33036061/article/details/124443096)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

BananaNo2

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值