springboot2.x實現oauth2受權碼登錄

一 進行受權頁

 
二 使用資源站用戶登錄
自動跨到資源登錄頁,先登錄
 

三 受權資源類型

登錄成功後,去受權你的資源,這些資源是在AuthorizationServerConfig.configure方法裏配置的
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient(ClientID)
.secret(passwordEncoder.encode(ClientSecret))
.authorizedGrantTypes("authorization_code", "refresh_token",
"password", "implicit")
.scopes("read","write","del","userinfo")
.redirectUris(RedirectURLs);
}

四 接到code

受權以後,系統會重定向到你的redirect_uri這個頁面,並帶上惟一的code

五 獲取access_token

咱們拿着code就要再去受權服務器去獲取token了,你能夠在你的代碼裏寫這個,也能夠手動拿着code,去拼成一個url,再去拿token,就像這下面的實例。
注意向oauth/token發的是post請求,client_id和client_secret若是在url上傳遞,若是在AuthorizationServerConfig類的configure方法中開啓allowFormAuthenticationForClients,代碼以下
@Override
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帶上,這個方法通常會作成公用的過濾器node

@Controller
public class UserController {
  @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);
    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裏添加它,例以下載代碼
@Configuration
@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方法,不然,你的權限將會失效!android

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

相關文章
相關標籤/搜索