OAuth 2.0 是一种授权协议,允许用户通过URL在服务中拿到授权代码资源,它就像最终用户发行令牌以允许一个服务访问另一个服务的一种方式。大家一定要清楚OAauth2是授权协议,它不是用来进行身份验证。有很多刚刚接触oauth2 的开发者都会在此处犯了错误,这可能会增加学习与理解的难度。在 OAuth 2.0 使用中,可以多个服务器协同工作来执行授权。
1.1 OAauth2 服务类型OAauth2服务分为以下几种,Authorization Server和Resource Server分别作为授权服务器和资源服务器。
pom.xml
org.springframework.boot spring-boot-starter-security 2.2.3.RELEASE org.springframework.boot spring-boot-starter-web 2.2.3.RELEASE org.springframework.security.oauth.boot spring-security-oauth2-autoconfigure 2.2.3.RELEASE org.apache.httpcomponents httpclient 4.5.13
1、客户端
访问受保护资源的 Web 应用程序,除了 Web 应用程序之外还可以是其他客户端。Android客户端、Web客户端(浏览器端)、微信客户端等等。
2、授权服务器 Authorization Server
被资源服务器信任的服务器,用来验证资源所有者,并向资源服务器颁发访问令牌。验证成功后生成 网路令牌 access_token作为客户端访问资源服务器的凭据,对访问资源进行授权。
3、资源服务器 Resource Server
存储登录用户信息资源的服务器。
Security oauth2 访问步骤
- 步骤一 用户使用客户端进行登录,登录成功后返回一个code令牌。
- 步骤二 通过code令牌获访问授权服务器获得授权的access_token。
- 步骤三 通过access_token到资源服务器获得系统的url资源。
在正常使用的时候项目会搭建三到二个WEB服务。授权服务器和验证在一起,资源服务器自己独立一个服务。下面的例子为了方便大家理解就将所有的服务都放在一个服务中。
1.2 OAuth 协议的授权模式OAuth 协议的授权模式共分为 4 种,分别说明如下:
- 授权码模式:授权码模式(authorization code)是功能最完整、流程最严谨的授权模式。
- 简化模式:简化模式不需要客户端服务器参与,直接在浏览器中向授权服务器中请令牌,一般若网站是纯静态页面,则可以采用这种方式。
- 密码模式:密码模式是用户把用户名密码直接告诉客户端,客户端使用这些信息向授权服务器中请令牌。
- 客户端模式:客户端模式是指客户端使用自己的名义而不是用户的名义向服务提供者申请授权。
继承 AuthorizationServerConfigurerAdapter 类就可以成为一般授权服务器的功能。
@Configuration
@EnableAuthorizationServer
public class OAuth2AuthorizationServer extends AuthorizationServerConfigurerAdapter {
//定义客户端详细信息服务的配置器。可以初始化客户端详细信息
public void configure(ClientDetailsServiceConfigurer clients)
//定义令牌端点上的安全约束。
public void configure(AuthorizationServerEndpointsConfigurer endpoints)
//定义授权和令牌端点以及令牌服务。
public void configure(AuthorizationServerSecurityConfigurer security)
}
2.1 授权验证方法 configure(ClientDetailsServiceConfigurer clients)
Client (客户端名称) : 身份验证服务器注册的客户端 ID
withClient("clientapp")
Secret (客户端密码) : 来之客户端的秘密
secret(passwordEncoder.encode("123456"))
Scope(范围): 客户端应用程序的范围。这显示了我们为客户端应用程序提供的访问权限。如果范围未定义或为空(默认),则客户端不受范围限制。
scopes("read_profile_info")
authorizedGrantTypes : 客户端使用的授权类型,对应OAuth 协议的几种授权模式。
authorizedGrantTypes("password", "authorization_code", "refresh_token")
authorities (客户端权限) : 授予客户端的权限。
authorities("READ_ONLY_CLIENT")
redirectUris : 将用户代理重定向到客户端的重定向端点。它必须是绝对 URL。
redirectUris("http://localhost:8081/login")
Token Validity : 设置访问和刷新令牌有效性。
accessTokenValiditySeconds(120) refreshTokenValiditySeconds(240000);
autoApprove: 直接授权模式(不需要打开授权页面)
.autoApprove(true)2.2 代码示例
@Configuration
@EnableAuthorizationServer
public class OAuth2AuthorizationServer extends AuthorizationServerConfigurerAdapter {
@Autowired
private BCryptPasswordEncoder passwordEncoder;
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security
// 开启 /oauth/check_token
.tokenKeyAccess("permitAll()")
// 开启 /oauth/token_key
.checkTokenAccess("isAuthenticated()")
// 允许表单认证
.allowFormAuthenticationForClients();
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
System.out.println("--------- 单点登录 -------");
clients
.inMemory()// 基于内存配置
.withClient("zhtbs")
.secret(passwordEncoder.encode("123456"))
//对应OAuth 协议的几种授权模式
.authorizedGrantTypes("password", "authorization_code", "refresh_token")
.authorities("READ_ONLY_CLIENT")
.scopes("read_profile_info")
.resourceIds("oauth2-resource")
.redirectUris("http://localhost:8080/login")
.autoApprove(true)
.accessTokenValiditySeconds(1200)
.refreshTokenValiditySeconds(24000);
}
}
3 资源服务器
继承ResourceServerConfigurerAdapter 类成为资源服务。
@Configuration
@EnableResourceServer
public class OAuth2ResourceServer extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
System.out.println("----------资源服务-----------");
http.authorizeRequests()
.antMatchers("/api/**").authenticated()
.antMatchers("/").permitAll();
}
}
创建一个资源业务API类
@RestController
public class ZhtRestController {
@GetMapping("/zht")
public String zht(){
return "测试一个";
}
@RequestMapping("/api/zht")
public Map getuser(){
Map map=new HashMap();
map.put("a1",1);
map.put("a2",1);
map.put("a3",1);
map.put("a4",1);
map.put("a5",1);
return map;
}
}
4 客户验证登录服务
@Configuration
@EnableWebSecurity
@Order(1)
public class ZhtSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.requestMatchers()
.antMatchers("/login", "/oauth/authorize")
.and()
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin().permitAll().and().csrf().disable();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
System.out.println("=========== 验证开始 ===========");
auth.inMemoryAuthentication()
.withUser("zht")
.password(passwordEncoder().encode("123456"))
.roles("USER");
}
@Bean
public BCryptPasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
}
5 登录过程
5.1 登录获得code令牌
在浏览器中录入oauth/authorize 路径。
http://localhost:8080/oauth/authorize?client_id=zhtbs&response_type=code&scope=read_profile_info
| |
.withClient("zhtbs") |
.scopes("read_profile_info")
转发到登录页面 用户名称zht 密码123456
通过验证获得授权的令牌 http://localhost:8080/login?code=WArwgX
- 通过 http://localhost:8080/oauth/token 拿到数据授权access_token
- 通过授权码访问资源服务器上API
public class HttpTest {
public static void main(String[] args) {
HttpTest.ZhtPost("WArwgX");
}
//获得 授权服务器上的 access_token
private static void ZhtPost(String code){
HttpPost httpPost = new HttpPost("http://localhost:8080/oauth/token");
httpPost.setHeader("accept","application/json");
httpPost.setHeader("Content-Type","application/x-www-form-urlencoded");
httpPost.setHeader("authorization","Basic "+Base64.getUrlEncoder().encodeToString("zhtbs:123456".getBytes()));
StringEntity postingString = new StringEntity("grant_type=authorization_code&code="+code+"&redirect_uri=http://localhost:8080/login" ,
"utf-8");
httpPost.setEntity(postingString);
CloseableHttpClient httpClient = null;
// 执行请求
CloseableHttpResponse response = null;
try {
httpClient = HttpClients.createDefault();
response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
String conte=EntityUtils.toString(entity, "UTF-8");
// 获得 授权服务器上的 access_token
System.out.println("-----"+conte);
ObjectMapper obj= new ObjectMapper();
Map map= obj.readValue(conte,Map.class);
//使用 token 访问 资源服务器上的url内容
ZhtGet((String)map.get("access_token"));
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
if(response!=null){
response.close();
}
if(httpClient!=null){
httpClient.close();
}
} catch (IOException e) {
}
}
}
//获得资源服务上的内容
private static void ZhtGet(String access_token){
HttpGet httpget = new HttpGet("http://localhost:8080/api/zht");
httpget.setHeader("authorization","Bearer "+access_token);
httpget.setHeader("cache-control","no-cache");
CloseableHttpClient httpClient = null;
// 执行请求
CloseableHttpResponse response = null;
try {
httpClient = HttpClients.createDefault();
response = httpClient.execute(httpget);
HttpEntity entity = response.getEntity();
//获得业务内容
System.out.println("-----"+EntityUtils.toString(entity, "UTF-8"));
} catch (IOException e) {
}
finally {
try {
if(response!=null){
response.close();
}
if(httpClient!=null){
httpClient.close();
}
} catch (IOException e) {
}
}
}
}
运行结果
// 获得授权 access_token
[main] DEBUG org.apache.http.headers - http-outgoing-0 >> POST /oauth/token HTTP/1.1
[main] DEBUG org.apache.http.wire - http-outgoing-0 >> "grant_type=authorization_code&code=UH0hFj&redirect_uri=http://localhost:8080/login"
[main] DEBUG org.apache.http.wire - http-outgoing-0 << "{"access_token":"119cd3dd-d11c-425f-b808-8a42e681e626",
"token_type":"bearer",
"refresh_token":"9cb475c9-9e56-4a04-be9d-ded2a17a5cf3",
"expires_in":1199,"scope":"read_profile_info"}[r][n]"
//获得资源服务上的API数据
[main] DEBUG org.apache.http.wire - http-outgoing-1 >> "GET /api/zht HTTP/1.1[r][n]"
[main] DEBUG org.apache.http.wire - http-outgoing-1 >> "authorization: Bearer 119cd3dd-d11c-425f-b808-8a42e681e626[r][n]"
[main] DEBUG org.apache.http.wire - http-outgoing-1 >> "cache-control: no-cache[r][n]"
[main] DEBUG org.apache.http.wire - http-outgoing-1 << "{"a1":1,"a2":1,"a3":1,"a4":1,"a5":1}[r][n]"
http://localhost:8080//oauth/token 获得授权 access_token请求
{"access_token":"119cd3dd-d11c-425f-b808-8a42e681e626",
"token_type":"bearer",
"refresh_token":"9cb475c9-9e56-4a04-be9d-ded2a17a5cf3",
"expires_in":1199,"scope":"read_profile_info"
}
//使用access_token 访问受保护的api
HttpGet httpget = new HttpGet("http://localhost:8080/api/zht");
httpget.setHeader("authorization","Bearer 119cd3dd-d11c-425f-b808-8a42e681e626");
httpget.setHeader("cache-control","no-cache");



