springboot2.x实现oauth2授权码登陆

一 进行授权页

浏览器输入http://localhost:8081/oauth/authorize?response_type=code&redirect_uri=http://localhost:8081/callback&client_id=android1&scop=all

二 使用资源站用户登陆

自动跨到资源登陆页,先登陆

118538-20190802151434192-1606055485.png

三 授权资源类型

登陆成功后,去授权你的资源,这些资源是在AuthorizationServerConfig.configure方法里配置的

clients.inMemory()
.withClient(ClientID)
.secret(passwordEncoder.encode(ClientSecret))
.authorizedGrantTypes("authorization_code", "refresh_token", "password", "implicit")
.scopes("read","write","del","userinfo")
.redirectUris(RedirectURLs);
}
118538-20190802151523934-750605919.png

四 接到code

授权之后,系统会重定向到你的redirect_uri这个页面,并带上唯一的code

118538-20190802151555640-1309002031.png

五 获取access_token

我们拿着code就要再去授权服务器去获取token了,你可以在你的代码里写这个,也可以手动拿着code,去拼成一个url,再去拿token,就像这下面的实例。

注意向oauth/token发的是post请求,client_id和client_secret如果在url上传递,如果在AuthorizationServerConfig类的configure方法中开启allowFormAuthenticationForClients,代码如下

public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
  oauthServer.tokenKeyAccess("isAuthenticated()")
      .checkTokenAccess("permitAll()")
      .allowFormAuthenticationForClients();//支持把secret和clientid写在url上,否则需要在头上 }

然后请求后给有下面的响应

Authorization Ccode------RFRLFY
access_token_url http://localhost:8081/oauth/token?client_id=android1&code=RFRLFY&grant_type=authorization_code&redirect_uri=http://localhost:8081/callback&client_secret=android1
Access Token Response ---------{"access_token":"faadf3bf-6488-4036-bc3b-21b0a979602c","token_type":"bearer","refresh_token":"1b01f133-c5ab-419f-8125-088c85916ecb","expires_in":43187,"scope":"read"}

回调页面代码,主要实现了对code的获取,对access_token的组织,然后请求时把access_token带上,这个方法一般会做成公用的过滤器

  @RequestMapping(value = "/callback", method = RequestMethod.GET) public ResponseEntity<String> callback(@RequestParam("code") String code) throws JsonProcessingException, IOException {
    ResponseEntity<String> response = null;
    System.out.println("Authorization Ccode------" + code);
    RestTemplate restTemplate = new RestTemplate();
    String access_token_url = "http://localhost:8081/oauth/token";
    access_token_url += "?client_id=android1&code=" + code;
    access_token_url += "&grant_type=authorization_code";
    access_token_url += "&redirect_uri=http://localhost:8081/callback";
    access_token_url += "&client_secret=android1";
    System.out.println("access_token_url " + access_token_url);
    response = restTemplate.exchange(access_token_url, HttpMethod.POST, null, String.class);
    ObjectMapper mapper = new ObjectMapper();
    JsonNode node = mapper.readTree(response.getBody());
    String token = node.path("access_token").asText(); System.out.println("access_token" +access_token);</pre>

<pre> String url = "http://localhost:8081/index"; HttpHeaders headers1 = new HttpHeaders(); headers1.add("Authorization", "Bearer " + token); HttpEntity<String> entity = new HttpEntity<>(headers1); ResponseEntity<String> result = restTemplate.exchange(url, HttpMethod.GET, entity, String.class); return result; }

六 拿着access_token去请求具体的资源

可以在url地址上直接:http://localhost:8081/index?access_token=faadf3bf-6488-4036-bc3b-21b0a979602c

七 如何开启oauth scopes授权

.access("#oauth2.hasScope('del')") 这个需要在ResourceServerConfig.configure里添加它,例如下载代码

@EnableResourceServer
@Order(6) public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Override public void configure(HttpSecurity http) throws Exception {
http.csrf().disable()//禁用了 csrf 功能
.authorizeRequests()//限定签名成功的请求
.antMatchers("/index").access("#oauth2.hasScope('del')") //授权码scopes里需要选中del才可以访问
.antMatchers("/user").authenticated()//签名成功后可访问,不受role限制
.anyRequest().permitAll()//其他没有限定的请求,允许访问
.and().anonymous()//对于没有配置权限的其他请求允许匿名访问
.and().formLogin()//使用 spring security 默认登录页面
.and().httpBasic();//启用http 基础验证
 }
}

八 需要注意的地方

如果你对用户进行了角色和权限的配置,对于某些保护接口需要有指定权限才能访问的话,需要重getAuthorities方法,否则,你的权限将会失效!

@Data public class User extends BaseEntity implements UserDetails {
  @Id
  @GeneratedValue private Long id; private String username; private String password; private String firstName; private String lastName;
  @Email private String email; private String imageUrl;

  @JsonIgnore
  @ManyToMany(targetEntity = Role.class, fetch = FetchType.EAGER)
  @BatchSize(size = 20) private Set<Role> roles = new HashSet<>();

  @Transient private Set<GrantedAuthority> authorities = new HashSet<>(); /** * 注意,这块需要加@Override重写,否则权限无效.
   *
   * @return
   */ @Override public Set<GrantedAuthority> getAuthorities() {
    Set<GrantedAuthority> authorities = new HashSet<>(); for (Role role : this.roles) { for (Authority authority : role.getAuthorities()) {
        authorities.add(new SimpleGrantedAuthority(authority.getValue()));
      }
    } return authorities;
  }

  @Override public boolean isAccountNonExpired() { return true;
  }

  @Override public boolean isAccountNonLocked() { return true;
  }

  @Override public boolean isCredentialsNonExpired() { return true;
  }

  @Override public boolean isEnabled() { return true;
  }
}

感谢阅读!

愿与诸君共进步,大量的面试题及答案还有资深架构师录制的视频录像:有Spring,MyBatis,Netty源码分析,高并发、高性能、分布式、微服务架构的原理,JVM性能优化、分布式架构等这些成为架构师必备的知识体系,可以微信搜索539413949获取,最后祝大家都能拿到自己心仪的offer

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,427评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,551评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,747评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,939评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,955评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,737评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,448评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,352评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,834评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,992评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,133评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,815评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,477评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,022评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,147评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,398评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,077评论 2 355

推荐阅读更多精彩内容