0
点赞
收藏
分享

微信扫一扫

SpringSecurity实现OAuth2.0 - 授权服务和资源服务分离

老罗话编程 2022-02-15 阅读 81

《SpringSecurity实现OAuth2.0_01_基础版授权服务》和《SpringSecurity实现OAuth2.0_02_进阶版授权服务》两篇文章中介绍如何搭建OAuth2.0授权服务器和资源服务器。

本文将继续优化,将授权服务器和资源服务器分离,部署在不同的服务器上面。

简要说明

Spring Security OAuth2.0既可以把授权服务器(AuthorizationServer)和资源服务器(ResourceServer)配置在一个应用中,也可以分开配置。

授权服务器负责用户登录、授权、token验证等。

资源服务器负责提供受保护资源,只是需要到授权服务器进行token验证。

在此部分,将介绍以下内容:

  • 如何将AuthorizationServer和ResourceServer分开配置,各司其职。
  • 使用postman替换curl命令作为接口调用的工具。
  • 依赖、实体类、工具类、DAO、Service、授权页、登录页等内容与上一部分没有区别,不再赘述,只记录需要修改的内容。

AuthorizationServer配置

在上一部分的代码(Spring Security实现OAuth2.0进阶)中抽取以下内容:

  • 实体类。
  • 登录页和授权页。
  • DAO和Service层。
  • Mybatis配置、Security配置和AuthorizationServerConfigurer配置。

需要修改一部分代码。

修改AuthorizationServerConfigurer配置

重写configure(AuthorizationServerSecurityConfigurer)方法,配置前来验证token的client需要拥有ROLE_TRUSTED_CLIENT角色。

@Configuration
public class Oauth2AuthorizationServerConfiguration extends
        AuthorizationServerConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private DataSource dataSource;

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security)
            throws Exception {
        // 配置前来验证token的client需要拥有的角色
        security.checkTokenAccess("hasAuthority('ROLE_TRUSTED_CLIENT')");
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients)
            throws Exception {
        // 不变
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints)
            throws Exception {
        // 不变
    }
}

修改启动类

启动类删除@EnableResourceServer注解。

@SpringBootApplication
@EnableAuthorizationServer
@MapperScan("org.net5ijy.oauth2.repository")
public class Oauth2AuthorizationServer {
    public static void main(String[] args) {
        // args = new String[] { "--debug" };
        SpringApplication.run(Oauth2AuthorizationServer.class, args);
    }
}

ResourceServer配置

在上一部分的代码(Spring Security实现OAuth2.0进阶)中抽取以下内容:

  • 响应工具类
  • 受保护资源controller

配置Spring Security

@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests().antMatchers("/order/**").authenticated();

        // 禁用CSRF
        http.csrf().disable();
    }
}

配置ResourceServerConfigurer

需要配置一个受信任的client到授权服务器验证token令牌。

@Configuration
public class Oauth2ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

    private static final String URL = "http://localhost:7002/oauth/check_token";

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        RemoteTokenServices tokenService = new RemoteTokenServices();
        tokenService.setCheckTokenEndpointUrl(URL);
        tokenService.setClientId("net5ijy");
        tokenService.setClientSecret("12345678");
        resources.tokenServices(tokenService);
    }
}

修改启动类

启动类删除@EnableAuthorizationServer注解。

@SpringBootApplication
@EnableResourceServer
public class Oauth2ResourceServer {
    public static void main(String[] args) {
        SpringApplication.run(Oauth2ResourceServer.class, args);
    }
}

测试授权码模式

首先启动授权服务器,再启动资源服务器。

获取authorization_code授权码

使用浏览器访问:

http://localhost:7002/oauth/authorize?response_type=code&client_id=tencent&redirect_uri=http://localhost:8080&scope=all

地址:

http://localhost:7002/oauth/authorize

参数说明
response_typecode
client_id根据实际的client-id填写,此处写tencent
redirect_uri生成code后的回调地址,http://localhost:8080
scope权限范围

登录,admin002和123456

在这里插入图片描述

允许授权:

在这里插入图片描述

看到浏览器重定向到了http://localhost:8080并携带了code参数,这个code就是授权服务器生成的授权码:

在这里插入图片描述

获取token令牌

地址:

http://localhost:7002/oauth/token

参数说明
grant_type授权码模式,写authorization_code
scope权限范围
redirect_uri回调地址,http://localhost:8080需要urlencode
code就是上一步生成的授权码

使用postman获取token令牌。

在这里插入图片描述

在这里插入图片描述

返回值:

{
    "access_token": "e50a400c-439f-4df0-95d5-79154d2cbf87",
    "token_type": "bearer",
    "refresh_token": "29ac936f-69ef-4356-91b1-775fbec65805",
    "expires_in": 3599,
    "scope": "all"
}

这样就获取到了token令牌,该token的访问权限范围是all权限,在1小时后失效。

使用token访问资源

http://localhost:7003/order/demo?access_token=e50a400c-439f-4df0-95d5-79154d2cbf87

源码下载

https://gitee.com/xuguofeng2020/springsecurityoauth2

举报

相关推荐

0 条评论