springboot整合oauth2

springboot整合oauth2.0

文章目录

  • springboot整合oauth2.0
      • 1.概念
      • 2.springboot整合oauth2.0示例
        • 2.1SecurityConfig配置
        • 2.2资源服务器配置和授权服务器配置
      • 3.测试

环境

springboot1.5.x

demo下载:https://github.com/2010yhh/springBoot-demos/tree/master/springboot-auth

1.概念

客户应用: 通常是一个web或者手机,他需要访问用户的受保护资源
资源服务器::是一个web站点或者web service API,用户的受保护数据保存在这个地方
授权服务器: 在客户应用成功认证并获得授权之后,想客户应用颁发访问令牌Access Token
资源拥有者:资源的拥有人,也就是用户。他可以想要分享给第三方应用的一些操作

参考:https://blog.csdn.net/zane3/article/details/79590699

https://blog.csdn.net/m0_37779570/article/details/82020898

https://blog.csdn.net/qq_33862644/article/details/79465430

http://blog.didispace.com/spring-security-oauth2-xjf-1/

2.springboot整合oauth2.0示例

2.1SecurityConfig配置

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    /**
     * 对应密码模式,内存中新建2个用户;实际用数据库查询
     *
     * @return
     */
    @Bean
    @Override
    protected UserDetailsService userDetailsService() {
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
        manager.createUser(User.withUsername("user_1").password("123456").authorities("USER").build());
        manager.createUser(User.withUsername("user_2").password("123456").authorities("USER").build());
        return manager;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http
                .requestMatchers().anyRequest()
                .and()
                .authorizeRequests()
                .antMatchers("/oauth/*").permitAll();//生产token的url允许任何登录的用户访问
        // @formatter:on
    }
}

2.2资源服务器配置和授权服务器配置

springboot整合oauth2_第1张图片

@Configuration
public class OAuth2ServerConfig {

    private static final String DEMO_RESOURCE_ID = "order";

    @Configuration
    @EnableResourceServer
    protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

        @Override
        public void configure(ResourceServerSecurityConfigurer resources) {
            resources.resourceId(DEMO_RESOURCE_ID).stateless(true);
        }

        @Override
        public void configure(HttpSecurity http) throws Exception {
            // @formatter:off
            http
                    // Since we want the protected resources to be accessible in the UI as well we need
                    // session creation to be allowed (it's disabled by default in 2.0.6)
                    .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
                    .and()
                    .requestMatchers().anyRequest()
                    .and()
                    .anonymous()
                    .and()
                    .authorizeRequests()
//                    .antMatchers("/product/**").access("#oauth2.hasScope('select') and hasRole('ROLE_USER')")
                    .antMatchers("/private/**").authenticated();//配置访问控制,必须认证过后才可以访问
            // @formatter:on
        }
    }

    @Configuration
    @EnableAuthorizationServer
    protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

        @Autowired
        AuthenticationManager authenticationManager;
        @Autowired
        RedisConnectionFactory redisConnectionFactory;

        @Override
        public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
            //配置两个客户端,模拟第三方应用,一个用于password认证一个用于client认证
            clients.inMemory().withClient("client_1")
                    .resourceIds(DEMO_RESOURCE_ID)
                    .authorizedGrantTypes("client_credentials", "refresh_token")
                    .scopes("select")
                    .authorities("client")
                    .secret("123456")
                    .and().withClient("client_2")
                    .resourceIds(DEMO_RESOURCE_ID)
                    .authorizedGrantTypes("password", "refresh_token")
                    .scopes("select")//作用域(Scopes): 客户请求访问令牌时,有资源拥有者额外指定的细分权限(permission)
                    .authorities("client")
                    .secret("123456");
        }

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

        @Override
        public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
            //允许表单认证
            oauthServer.allowFormAuthenticationForClients();
        }

    }

3.测试

1.测试需要启动redis,

2.直接get访问localhost:8080/public/1  localhost:8080/private/1

3.使用http工具post访问password模式http://localhost:8080/oauth/token?username=user_1&password=123456&grant_type=password&scope=select&client_id=client_2&client_secret=123456

使用http工具post访问client模式http://localhost:8080/oauth/token?grant_type=client_credentials&scope=select&client_id=client_1&client_secret=123456

4.再次带上获取的tokenget访问http://localhost:8080/private/1?access_token=bd77315b-5f83-433f-a4aa-b9f20b89ff34

http://localhost:8080/private/1?access_token=d6912dd2-347d-4e64-98a3-922380dab7a0

直接get访问:
springboot整合oauth2_第2张图片



客户端模式获取token
再利用客户端模式获取token访问


springboot整合oauth2_第3张图片

密码模式获取token
再利用密码模式获取token访问

springboot整合oauth2_第4张图片

你可能感兴趣的:(springboot)