SpringBootSecurity学习(24)前后端分离版之OAuth2.0 应用登记

# 应用登记 一个应用要求 OAuth 授权,必须先到对方网站登记,让对方知道是谁在请求。举个例子,下面是github的登记页面: - https://github.com/settings/applications/new ![file](https://upload-images.jianshu.io/upload_images/3673891-1ff2829464c3e532.jpeg) 下面我们来自己做一个简单的应用登记,根据表 oauth_client_details 的结构,我们登记的时候只填写应用名称和回调地址即可,其它的字段如下: - client_id:使用UUID生成 - client_secret:使用UUID生成,并使用 BCryptPasswordEncoder 加密 - scope:默认all - authorized_grant_types :默认 authorization_code,password,refresh_token 三个 下面是sql语句: ![file](https://upload-images.jianshu.io/upload_images/3673891-bbe67a4de0b72822.jpeg) ![file](https://upload-images.jianshu.io/upload_images/3673891-b745fe52825f7155.jpeg) Service中的方法: ![file](https://upload-images.jianshu.io/upload_images/3673891-734cbf5b8617939b.jpeg) 接口定义: ![file](https://upload-images.jianshu.io/upload_images/3673891-38bc443f96cd7a8b.jpeg) 下面来测试接口: ![file](https://upload-images.jianshu.io/upload_images/3673891-5f311431944cd8fd.jpeg) 返回了预期中的客户端id和秘钥。来看一下数据库: ![file](https://upload-images.jianshu.io/upload_images/3673891-4e081139ea7cea34.jpeg) 现在我们就可以使用新登记的应用来请求令牌了: - http://localhost:8029/oauth/authorize?client_id=52f301a86511406ba5b4fbb4809614b0&response_type=code&redirect_uri=http://localhost:8029/ ![file](https://upload-images.jianshu.io/upload_images/3673891-3612d99201acb852.jpeg) 令牌请求结果: ![file](https://upload-images.jianshu.io/upload_images/3673891-3031cfe12199e553.jpeg) # 状态state字段 为了防止CSRF攻击,在申请授权码这一步时,可以在参数中增加一个state状态参数,这个参数是由客户端生成的随机字符串,授权服务会原封不动的返回这个参数和参数值,用户进行授权客户端的请求时也会携带此字符串用于比较。如下: - http://localhost:8029/oauth/authorize?client_id=52f301a86511406ba5b4fbb4809614b0&response_type=code&redirect_uri=http://localhost:8029/&state=123456789 返回结果如下: ![file](https://upload-images.jianshu.io/upload_images/3673891-03d043448c5c13f7.jpeg) 如果传递过去的和回来的不一样,可以认为不合法。 代码地址:https://gitee.com/blueses/spring-boot-security 29 > 本文由博客一文多发平台 [OpenWrite](https://openwrite.cn?from=article_bottom) 发布!

你可能感兴趣的:(SpringBootSecurity学习(24)前后端分离版之OAuth2.0 应用登记)