1. OAuth2簡易實戰(二)
1.1. 目標
- 模擬客戶端獲取第三方授權,並調用第三方接口
1.2. 代碼
1.2.1. 核心流程
- 邏輯就是從數據庫讀取用戶信息,封裝成UserDetails對象,該邏輯在用戶進行登錄時調用,驗證由Spring Security框架完成
@Service("clientUserDetailsService")
public class ClientUserDetailsService implements UserDetailsService {
@Autowired
private UserRepository users;
@Override
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException {
Optional<ClientUser> optionalUser = users.findByUsername(username);
if (!optionalUser.isPresent()) {
throw new UsernameNotFoundException("invalid username or password");
}
return new ClientUserDetails(optionalUser.get());
}
}
- 驗證核心代碼
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
@Qualifier("clientUserDetailsService")
private UserDetailsService userDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
auth.userDetailsService(userDetailsService);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests().antMatchers("/", "/index.html").permitAll().anyRequest().authenticated().and()
.formLogin().and()
.logout().permitAll().and()
.csrf().disable();
}
}
- 驗證完成后,進入controller方法,判斷token不存在,調用授權連接,后續操作同上一篇的授權碼模式,在認證通過后,繼續轉發調用controller
- 整個流程核心是模擬oauth的http調用
- 完整代碼參看 https://github.com/spring2go/oauth2lab 中lab02
1.3. 流程效果
- 訪問客戶端

- 跳轉客戶端登錄

- 登陸后跳轉授權登錄

- 確認授權

- 跳轉主頁並獲取資源服務器信息
