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

image

关注我,一个仍存梦想的屌丝程序员,每天为你分享高质量编程博客。

follow us for dream

可关注微信公众号

image

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

    image

    2.查看Redis 是否生成token

    image

    3.请求资源

    image

作者:烙yoy印
链接:https://www.jianshu.com/p/45ddadbdc1d0
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

回复关键字:

1、回复 “10” 查看 最有价值的10个spring boot开源项目

2、回复 “国旗” 获取国旗头像教程**

3、回复 “Ubuntu” 获取****100 个最佳 Ubuntu 应用 和 linux神器

4、回复 “idea” 获取**最新idea破解教程 和 装逼神奇

5、回复 “ssh” 获取史上最好的 ssh工具 支持mac

6、回复 “代金券” 免费获取腾讯云和阿里云代金券

image

推荐阅读:

MySQL优化-一篇文章就够了(转发加收藏吧)

Spring Boot最核心的27个注解,你了解多少?

程序员一般可以从什么平台接私活?

看完这14张思维导图,你的python才算入门

手把手讲解 OkHttp硬核知识点(1)

Python 爬取微信公众号文章和评论 (有源码)

Java 开发人员常用的服务配置(Nginx、Tomcat、JVM、Mysql、Redis)

腾讯电话面试总结—Linux运维工程师

python爬虫:(嘿嘿嘿)爬你喜欢的照片

面试官问我:一个 TCP 连接可以发多少个 HTTP 请求?我竟然回答不上来…

教你迅雷&百度非会员也能享受不限速的特权

Chrome开发者工具(DevTools)使用技巧

100个最有价值的开源项目–微信开发系列

IDEA 2019 最新激活教程

一台Linux服务器可以负载多少个连接?(底部有福利)

免责声明:

1.本公众号所转载文章均来自公开网络。

2.如果出处标注有误或侵犯到原著作者权益,请联系删除。

3.转载本公众号中的文章请注明原文链接和作者,否则产生的任何版权纠纷均与本公众号无关。

发布了173 篇原创文章 · 获赞 195 · 访问量 45万+

猜你喜欢

转载自blog.csdn.net/chenjianandiyi/article/details/102923284