一、环境搭建
-
添加依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-oauth2</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
-
添加配置
server: port: 8080 spring: application: name: oauth
-
创建业务实现类
@Service public class UserService implements UserDetailsService { private List<User> userList; @Autowired private PasswordEncoder passwordEncoder; /** * 初始化数据 */ @PostConstruct public void initData() { String password = passwordEncoder.encode("123456"); userList = new ArrayList<>(); userList.add(new User("admin", password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin"))); userList.add(new User("zhangsan", password, AuthorityUtils.commaSeparatedStringToAuthorityList("client"))); userList.add(new User("lisi", password, AuthorityUtils.commaSeparatedStringToAuthorityList("client"))); } @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { List<User> findUserList = userList.stream() .filter(user -> user.getUsername().equals(username)) .collect(Collectors.toList()); if (!CollectionUtils.isEmpty(findUserList)) { return findUserList.get(0); } else { throw new UsernameNotFoundException("用户名不存在!"); } } }
-
创建认证服务器配置类
@Configuration @EnableAuthorizationServer public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { @Autowired private PasswordEncoder passwordEncoder; @Autowired private AuthenticationManager authenticationManager; @Autowired private UserDetailServiceImpl userDetailsService; /** * 使用密码模式所需配置 */ @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) { endpoints.authenticationManager(authenticationManager) .userDetailsService(userDetailsService); } @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.inMemory() // 配置client_id .withClient("admin") // 配置client_secret .secret(passwordEncoder.encode("admin123456")) // 配置访问token的有效期 .accessTokenValiditySeconds(3600) // 配置刷新token的有效期 .refreshTokenValiditySeconds(864000) // 配置redirect_uri,用于授权成功后跳转 .redirectUris("http://www.my.com") // 配置scope,申请的权限范围 .scopes("all") // 配置grant_type,授权的模式 .authorizedGrantTypes("authorization_code", "password", "refresh_token"); } }
-
创建资源服务器配置类
@Configuration @EnableResourceServer public class ResourceServerConfig extends ResourceServerConfigurerAdapter { // 配置需要保护的资源路径 @Override public void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .anyRequest() .authenticated() .and() .requestMatchers() .antMatchers("/user/**"); } }
-
创建SpringSecurity配置
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Override public void configure(HttpSecurity http) throws Exception { http.csrf().disable() .authorizeRequests() .antMatchers("/oauth/**", "/login/**") .permitAll() .anyRequest() .authenticated() .and() .formLogin() .permitAll(); } }
-
添加控制器类
@RestController @RequestMapping("/user") public class UserController { @GetMapping("/info") public Object getUserInfo(Authentication authentication) { return authentication.getPrincipal(); } }
二、授权码模式测试
-
登录授权获取授权码
访问地址:
http://localhost:8080/oauth/authorize?response_type=code&client_id=admin&redirect_uri=http://www.my.com&scope=all&state=normal# 查看跳转的请求路径 https://www.my.com/?code=eTsADY&state=normal
-
获取访问令牌
使用Postman工具
-
测试获取用户信息
三、密码模式测试
-
获取访问令牌
使用Postman工具
-
测试获取用户信息
四、刷新令牌
【源码地址】:GitHub