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帶上,這個方法一般會做成公用的過濾器

@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方法,否則,你的權限將會失效!

@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;
  }
}

感謝閱讀!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM