Spring Boot OAuth2 使用实践

28 篇文章 0 订阅
6 篇文章 0 订阅

一、添加依赖

  <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
  <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
  </dependency>
  <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
        <exclusions>
              <exclusion>
                   <groupId>io.lettuce</groupId>
                   <artifactId>lettuce-core</artifactId>
              </exclusion>
        </exclusions>
   </dependency>
   <dependency>
        <groupId>redis.clients</groupId>
        <artifactId>jedis</artifactId>
   </dependency>
   <dependency>
        <groupId>org.springframework.security.oauth</groupId>
        <artifactId>spring-security-oauth2</artifactId>
        <version>2.3.3.RELEASE</version>
   </dependency>

二、Redis服务器连接信息

spring.redis.database=0
spring.redis.host=192.168.0.104
spring.redis.port=6379
spring.redis.password=198811
spring.redis.jedis.pool.max-active=8
spring.redis.jedis.pool.max-idle=8
spring.redis.jedis.pool.max-wait=1ms
spring.redis.jedis.pool.min-idle=0

三、配置授权服务器

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
    @Resource
    AuthenticationManager authenticationManager;

    @Autowired
    RedisConnectionFactory redisConnectionFactory;

    @Resource
    UserDetailsService userDetailsService;

    @Bean
    PasswordEncoder passwordEncoder()
    {
        return  new BCryptPasswordEncoder();
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("password")
                .authorizedGrantTypes("password","refresh_token")
                .accessTokenValiditySeconds(1800)
                .resourceIds("rid")
                .scopes("all")
                .secret("$2a$10$eCsDZyD0xQcxEM9qbhyo7ebQtqDF.w6U2.m1m7NQywYHKIwUahVR6");
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(new RedisTokenStore(redisConnectionFactory))
                .authenticationManager(authenticationManager)
                .userDetailsService(userDetailsService);
    }
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.allowFormAuthenticationForClients();
    }

}

 

四、配置资源服务器

@Configuration
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
       resources.resourceId("rid").stateless(true);
    }
    @Override
    public void configure(HttpSecurity http) throws Exception {
       http.authorizeRequests()
               .antMatchers("/admin/**").hasRole("admin")
               .antMatchers("/user/**").hasRole("user")
               .anyRequest().authenticated();
    }
}

五、配置Security

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

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

        return super.userDetailsService();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("admin")
                .password("$2a$10$eCsDZyD0xQcxEM9qbhyo7ebQtqDF.w6U2.m1m7NQywYHKIwUahVR6")
                .roles("admin")
                .and()
                .withUser("san")
                .password("$2a$10$eCsDZyD0xQcxEM9qbhyo7ebQtqDF.w6U2.m1m7NQywYHKIwUahVR6")
                .roles("user");
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.antMatcher("/oauth/**").authorizeRequests()
                .antMatchers("/oauth/**")
                .permitAll()
                .and()
                .csrf()
                .disable();
    }

}

六、测试验证

1.用Postman 发送一个POST请求获取token

http://localhost:9090/oauth/token?username=san&password=123&grant_type=password&client_id=password&scope=all&client_secret=123
{
    "access_token": "7d45f7bd-80ec-4f4e-93fe-b54cc7b21dfc",
    "token_type": "bearer",
    "refresh_token": "a9423a89-a14e-49cf-ae20-cf0a26a25058",
    "expires_in": 1799,
    "scope": "all"
}

2.使用refresh_token重新获取新到access_token

http://localhost:9090/oauth/token?grant_type=refresh_token&refresh_token=a9423a89-a14e-49cf-ae20-cf0a26a25058&client_id=password&client_secret=123
{
    "access_token": "da577ad7-78c3-4c53-9b15-51e5fefe8417",
    "token_type": "bearer",
    "refresh_token": "a9423a89-a14e-49cf-ae20-cf0a26a25058",
    "expires_in": 1799,
    "scope": "all"
}

3.使用access_token访问测试

http://localhost:9090/admin/hello?access_token=66018cdf-f92e-4f7e-895a-07b7321add03

 

七、查看Redis中到数据

redis-cli -h 127.0.0.1 -p 6379
Could not connect to Redis at 127.0.0.1:6379: Connection refused
Could not connect to Redis at 127.0.0.1:6379: Connection refuse
//这个错误是因为配置文件绑定了IP
Keys  *
(error) NOAUTH Authentication required.
//这个错误是因为设置 了访问密码
auth 198811
OK
192.168.0.104:6379> keys *
 1) "access_to_refresh:66018cdf-f92e-4f7e-895a-07b7321add03"
 2) "mykey"
 3) "uname_to_access:password:san"
 4) "access:66018cdf-f92e-4f7e-895a-07b7321add03"
 5) "client_id_to_access:password"
 6) "refresh_to_access:a9423a89-a14e-49cf-ae20-cf0a26a25058"
 7) "auth:66018cdf-f92e-4f7e-895a-07b7321add03"
 8) "\xac\xed\x00\x05t\x00\x04book"
 9) "name"
10) "auth_to_access:b4263db9d80f4bd329d2438813bbebb8"
11) "refresh_auth:a9423a89-a14e-49cf-ae20-cf0a26a25058"
12) "refresh:a9423a89-a14e-49cf-ae20-cf0a26a25058"

https://www.cnblogs.com/tqlin/p/11358470.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值