前言
要解决的问题:不暴露客户密码的情况下授权三方服务访问客户资源
角色:资源拥有者,客户端应用(三方服务),授权服务器,资源服务器
模式:授权码模式:需要客户授权得到授权码后再次通过三方服务的密码取得token,双重校验,最安全,最复杂
简易模式:无需授权码对用户暴露返回的Token,不安全
密码模式:客户端应用需要资源拥有者密码。全链路可信情况下使用
客户端模式:无需资源拥有者密码,只需要客户端应用密码进行校验,服务器对服务器使用
本试验主要演示注册码模式,分为授权服务器和资源服务器俩个应用,后续会持续扩展为单个授权服务器和多个资源服务器。
试验步骤
按照以下截图创建授权服务器,授权服务器包结构如下
1 使用pom文件导入相应依赖,主要导入了以下依赖包
1)SpringBoot的security和web,
2)SpringSecurity的OAuth2
pom文件如下
xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0modelVersion> <groupId>io.spring2gogroupId> <artifactId>authcode-serverartifactId> <version>0.0.1-SNAPSHOTversion> <packaging>jarpackaging> <name>authcode-servername> <description>Demo project for Spring Bootdescription> <parent> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-parentartifactId> <version>1.5.10.RELEASEversion> <relativePath /> parent> <properties> <project.build.sourceEncoding>UTF-8project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8project.reporting.outputEncoding> <java.version>1.8java.version> properties> <dependencies> <dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-securityartifactId> dependency> <dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-webartifactId> dependency> <dependency> <groupId>org.springframework.security.oauthgroupId> <artifactId>spring-security-oauth2artifactId> dependency> <dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-testartifactId> <scope>testscope> dependency> <dependency> <groupId>org.springframework.securitygroupId> <artifactId>spring-security-testartifactId> <scope>testscope> dependency> dependencies> <build> <plugins> <plugin> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-maven-pluginartifactId> plugin> plugins> build> project>
2 修改application.properties设置用户登录密码
# Spring Security Setting security.user.name=bobo security.user.password=xyz
3 制作SpringBoot的启动文件
package com.test.authcodeserver; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class AuthCodeServerApplication { public static void main(String[] args) { SpringApplication.run(AuthCodeServerApplication.class, args); } }4 设置授权服务代码
package com.test.authcodeserver.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; import org.springframework.security.oauth2.provider.token.DefaultTokenServices; import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore; import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore; @Configuration @EnableAuthorizationServer public class AuthCodeServerConfig extends AuthorizationServerConfigurerAdapter { @Override public void configure(final AuthorizationServerSecurityConfigurer oauthServer) throws Exception { oauthServer.tokenKeyAccess("permitAll()") .checkTokenAccess("isAuthenticated()"); } @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { //JdbcClientDetailsService可以动态管理数据库中客户端数据 //http://localhost:8080/oauth/authorize?client_id=testclientid&redirect_uri=http://localhost:9001/authCodeCallback&response_type=code&scope=read_userinfo clients.inMemory() .withClient("testclientid")//clientId:(必须的)用来标识客户的Id。 .secret("1234")//secret:(需要值得信任的客户端)客户端安全码,如果有的话。 .redirectUris("http://localhost:9001/authCodeCallback")//客户端应用负责获取授权码的endpoint .authorizedGrantTypes("authorization_code")// 授权码模式 .scopes("read_userinfo", "read_contacts");//scope:用来限制客户端的访问范围,如果为空(默认)的话,那么客户端拥有全部的访问范围。 } }
5 启动SpringBoot服务
6 客户端服务访问授权服务器,铜鼓访问如下url取得授权码
http://localhost:8080/oauth/authorize?client_id=testclientid&redirect_uri=http://localhost:9001/authCodeCallback&response_type=code&scope=read_userinfo
访问完成后会redirect回客户端服务器并将授权码作为参数传回,其中localhost:9001即为客户端应用
7 客户端使用返回的授权码获取访问令牌
发送请求参数如下
url:http://localhost:8080/oauth/token
code=ifz2BV&grant_type=authorization_code&redirect_uri=http%3A%2F%2Flocalhost%3A9001%2FauthCodeCallback&scope=read_userinfo
得到的令牌数据
}
以上授权服务器就简单完成了,下面将制作资源服务器
--------------------------------------------------------------------------------------------------
资源服务器
0 资源服务器的包结构
1 资源服务器配置,使用RemoteTokenServices调取认证服务器的认证方法来对Token进行认证
package com.test.resourceserver.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.core.AuthenticationException; import org.springframework.security.oauth2.common.OAuth2AccessToken; import org.springframework.security.oauth2.common.exceptions.InvalidTokenException; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer; import org.springframework.security.oauth2.provider.OAuth2Authentication; import org.springframework.security.oauth2.provider.token.DefaultTokenServices; import org.springframework.security.oauth2.provider.token.RemoteTokenServices; import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices; import org.springframework.security.web.AuthenticationEntryPoint; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; //资源服务配置 @Configuration @EnableResourceServer public class OAuth2ResourceConfig extends ResourceServerConfigurerAdapter { @Primary @Bean public RemoteTokenServices tokenServices() { final RemoteTokenServices tokenService = new RemoteTokenServices(); tokenService.setCheckTokenEndpointUrl("http://localhost:8080/oauth/check_token"); tokenService.setClientId("testclientid"); tokenService.setClientSecret("1234"); return tokenService; } @Override public void configure(HttpSecurity http) throws Exception { // http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED) // .and() // .authorizeRequests() // .anyRequest() // .authenticated() // .and() // .requestMatchers() // .antMatchers("/api/**"); http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED) .and() .authorizeRequests().anyRequest().permitAll(); } }
2 提供对外的API接口
package com.test.resourceserver.api; import org.springframework.http.ResponseEntity; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.User; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class UserController { // 资源API @RequestMapping("/api/userinfo") public ResponseEntity调用 getUserInfogetUserInfo() { String user = (String) SecurityContextHolder.getContext() .getAuthentication().getPrincipal(); String email = user+ "@test.com"; UserInfo userInfo = new UserInfo(); userInfo.setName(user); userInfo.setEmail(email); return ResponseEntity.ok(userInfo); } }
http://localhost:8004/api/userinfo
authorization: Bearer 638aa01c-4ccd-4873-ab86-d46f22aea091
调用后返回资源服务器的结果
至此一个资源服务器和认证服务器分离的资源调用就结束了。