OAuth2簡易實戰(二)-模擬客戶端調用


1. OAuth2簡易實戰(二)

1.1. 目標

  1. 模擬客戶端獲取第三方授權,並調用第三方接口

1.2. 代碼

1.2.1. 核心流程

  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());
    }

}
  1. 驗證核心代碼
@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();
    }

}
  1. 驗證完成后,進入controller方法,判斷token不存在,調用授權連接,后續操作同上一篇的授權碼模式,在認證通過后,繼續轉發調用controller
  2. 整個流程核心是模擬oauth的http調用
  3. 完整代碼參看 https://github.com/spring2go/oauth2lab 中lab02

1.3. 流程效果

  1. 訪問客戶端
  2. 跳轉客戶端登錄
  3. 登陸后跳轉授權登錄
  4. 確認授權
  5. 跳轉主頁並獲取資源服務器信息


免責聲明!

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



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