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. 流程效果
- 访问客户端
- 跳转客户端登录
- 登陆后跳转授权登录
- 确认授权
- 跳转主页并获取资源服务器信息