oauth2四种常用方式获得令牌的方式 |
您所在的位置:网站首页 › AFTool_BBK518授权验证 › oauth2四种常用方式获得令牌的方式 |
介绍
咱就不多解释了,本篇适合对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 简易模式不需要获得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 回车后 密码模式获得令牌的方式不需要先得到code,而是直接输入账户密码参数 用post测试 地址http://localhost:5000/oauth/token 参数 客户端模式不需要账户密码,只需要输入相应的客户端idclient_id与密钥client_secret 点击提交就可以得到令牌了 地址http://localhost:5000/oauth/token 参数 链接http://localhost:5000/oauth/check_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}] |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |