微服务火热,前后端分离,oauth2 是我们接口调用认证的首选。springboot 天然集成 oauth2,使用非常方便,简单记录下,尝尝鲜。
一、新建boot项目
idea 新建 springboot项目,maven 引入pom依赖,推荐使用spring-cloud-starter-oauth2和spring-cloud-starter-security。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<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>
项目结构目录如下,
二、oauth2核心config配置
这一步是成功的关键,主要三个config:认证服务配置、资源服务配置和web安全配置。
1、AuthServerConfig,继承 AuthorizationServerConfigurerAdapter
@Configuration
@EnableAuthorizationServer
public class AuthServerConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private UserDetailsService userDetailsService;
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("appid")
.secret("{noop}secret")
.authorizedGrantTypes("password", "authorization_code", "client_credentials", "implicit", "refresh_token")
.scopes("all");
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
endpoints.authenticationManager(authenticationManager)
.userDetailsService(userDetailsService);
}
}
2、ResourceServerConfig,继承 ResourceServerConfigurerAdapter (这里简单起见,我们都做默认实现)
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
}
3、WebSecurityConfig,继承 WebSecurityConfigurerAdapter
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
/**
* 必须注入 AuthenticationManager,不然oauth无法处理四种授权方式
*
* @return
* @throws Exception
*/
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
/**
* 注入UserDetailsService
* @return
*/
@Bean
@Override
protected UserDetailsService userDetailsService() {
InMemoryUserDetailsManager userDetailsManager = new InMemoryUserDetailsManager();
userDetailsManager.createUser(User.withUsername("zhangsan").password("{noop}123").authorities("USER").build());
return userDetailsManager;
}
三、测试类编写
一切从简,前面三个配置类写好后,我们写个简单的测试controller。
@RestController
public class HelloController {
@GetMapping("/sayHi")
public String sayHi() {
return "你好,哈哈哈";
}
}
另,application-dev.yml 里没做其他配置,就是指定一个端口号。
server:
port: 7000
四、postman测试
上面都做完了 我们就开始测试啦。
1、直接请求controller地址,返回没有授权
2、获取token
3、带token参数访问接口地址,访问成功。
这样的话,一个简单的oauth2授权码模式就ok了。