Springboot利用Security做OAuth2资源服务器

Springboot利用Security做OAuth2授权验证_LO嘉嘉VE的博客-CSDN博客_springbootsecurity oauth2 密码认证

验证服务器在上一篇文章中.

验证服务器是做权限验证,有没有登录,有没有权限访问某些内容等。资源服务器指提供业务功能的服务器,他们会向验证服务器进行验证是否有权限访问,有则处理请求,无则直接返回401无授权。

一、验证服务器本身就是资源服务器

这样就简单了,在上一篇文章的基础上,直接添加一个ResourceServerConfig的配置就行了

代码如下

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().authenticated()
                .and()
                .httpBasic();
    }

}

这时,验证服务器内提供的接口,需要授权才能访问。

我们用api访问软件进行测试,截图分别如下:

 

二、微服务配置的资源服务器 

单独构建的资源服务器会向授权服务器进行验证,验证的接口为/oauth/check_token。

我们第一步是给授权服务器的配置文件Oauth2ServerConfig添加允许访问验证接口的代码:

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) {
        security.allowFormAuthenticationForClients();
        //允许访问/oauth/check_token    
        security.checkTokenAccess("permitAll()");
    }

第二步配置资源服务器

1、pom添加依赖

        <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>

2、创建资源服务器的配置

@Configuration
@EnableResourceServer
public class OAuth2ResourceConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/noAuth/**").permitAll() //设置/oauth/**的接口不需要授权就可以访问
                .anyRequest().authenticated();
    }

}

3、application中配置权限验证服务器的地址

security:
  oauth2:
    resource:
      id: test
      token-info-uri: http://127.0.0.1:8080/oauth/check_token
      prefer-token-info: true
    client:
      access-token-uri: http://127.0.0.1:8080/oauth/token
      user-authorization-uri: http://127.0.0.1:8080/oauth/authorize
      client-id: test
      client-secret: test

配置好以上三步,资源服务器的配置就算完成了,配合验证服务器,我们可以启动进行测试。

访问/noAuth 接口,是否有token都可以访问

访问/test 接口,必须有权限才可以

测试访问截图如下:

 

 

 

源码测试地址:

Hello-Security: OAuth2授权服务器 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

LO嘉嘉VE

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

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

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

打赏作者

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

抵扣说明:

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

余额充值