介绍
咱就不多解释了,本篇适合对springsecurity、oauth2有一定了解,并已经配置好授权服务器、资源服务器的伙伴们看。
授权服务器端口5000
资源服务器端口5500
授权服务器核心配置
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("c1")
.secret(new BCryptPasswordEncoder().encode("123"))
.resourceIds("res1")//一个id对应一个需要被调用的资源服务器
.authorizedGrantTypes("authorization_code","password","client_credentials","implicit","refresh_token")//列出可以获得授权码的方式,参数是grant_type,
.scopes("all")//这个all需要与资源服务器的access的hasScope对上
.autoApprove(true)//得到code的时候自动获得,不需要选择是允许还是拒绝
.redirectUris("http://www.baidu.com");//参数正确后,重定向
}
内容
1、授权码方式
先进行登录操作
账户/密码:admin/123
登陆后在地址栏输入http://localhost:5000/oauth/authorize?client_id=c1&response_type=core&scpoe=all&redirect_uri=http://www.baidu.com
这些参数都对应着核心配置里的配置
回车后路径重定向http://www.baidu.com,并且ip后面还跟着一个授权码code
这下得到了这个授权码code——MgPLVC,因为获得令牌需要用post方法,所以我用postman测试
地址http://localhost:5000/oauth/token
参数
提交后
红框为得到的令牌
2、简易模式
简易模式不需要获得code,也不需要进入/oauth/token路径,
登陆后,直接在该浏览器地址栏输入
http://localhost:5000/oauth/authorize?client_id=c1&response_type=token&scpoe=all&redirect_uri=http://www.baidu.com
注意是response_type=token而不是response_type=code
回车后
直接得到了令牌
3、密码模式
密码模式获得令牌的方式不需要先得到code,而是直接输入账户密码参数
用post测试
地址http://localhost:5000/oauth/token
参数
点击提交直接能得到令牌
4、客户端模式
客户端模式不需要账户密码,只需要输入相应的客户端idclient_id与密钥client_secret 点击提交就可以得到令牌了
地址http://localhost:5000/oauth/token
参数
点击提交直接能得到令牌,但是这个方式得到的令牌是不带有用户信息的。
以上是四种常用的得到令牌的模式
5、验证token信息
链接http://localhost:5000/oauth/check_token
参数
value为得到的access_token
点击提交得到了一些消息,但是这个token是由客户端模式生成的,没有携带一些用户信息
使用密码模式重新生成一个带着用户信息的token
用这个token再去验证一下
得到结果
6、资源服务器用token访问资源
资源服务器的pom中也添加了springsecurity的maven坐标,放在以前,我们想要访问一个受到认证保护的资源需要登录,但是现在我们有token了!
资源服务器使用token访问资源(不需要通过密码登录,只需要授权服务器生成了token,并把这个token拿过来放入请求头中就可以相当于登录了。)
资源服务器有一个的接口
@RequestMapping("/myResource")
@PreAuthorize("hasRole('ROLE_管理员')")
public String myResource(){
return "this is a resource to other project";
}
接下来我们要访问到这个接口
对于这个@PreAuthorize(“hasRole(‘ROLE_管理员’)”),如果启动类上没加@EnableGlobalMethodSecurity(prePostEnabled = true)这个注解,那么@prePostEnabled将会失效,这个权限信息取自于token令牌。
postman测试
urlhttp://localhost:5500/myResource
这个token信息是填写在headers里的
*value是Bearer+空格+access_token
参数信息
[{“key”:“Authorization”,“value”:“Bearer 40e53537-a863-41a8-b53e-76d911b7d107”,“description”:"",“enabled”:true}]