public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient(“client-demo”)
.secret(passwordEncoder.encode(“123”))
.authorizedGrantTypes(“password”) //这里配置为密码模式
.scopes(“read_scope”);
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager);//密码模式必须添加authenticationManager
}
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security.allowFormAuthenticationForClients()
.checkTokenAccess(“isAuthenticated()”);
}
}
- 客户端的注册:这里通过inMemory的方式在内存中注册客户端相关信息;实际项目中可以通过一些管理接口及界面动态实现客户端的注册
- 校验Token权限控制:资源服务器如果需要调用授权服务器的/oauth/check_token接口校验token有效性,那么需要配置checkTokenAccess(“isAuthenticated()”)
- authenticationManager配置:需要通过endpoints.authenticationManager(authenticationManager)将Security中的authenticationManager配置到Endpoints中,否则,在Spring Security中配置的权限控制将不会在进行OAuth2相关权限控制的校验时生效。
1.1.3、Spring Security配置
通过Spring Security来完成用户及密码加解密等配置:
/**
• @Author 三分恶
• @Date 2020/5/20
• @Description SpringSecurity 配置
*/
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManager();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser(“fighter”)
.password(passwordEncoder().encode(“123”))
.authorities(new ArrayList<>(0));
}
@Override
protected void configure(HttpSecurity http) throws Exception {
//所有请求必须认证
http.authorizeRequests().anyRequest().authenticated();
}
}
1.2、资源服务器
资源服务器的职责:
- token的校验
- 给与资源
1.2.1、资源服务器配置
资源服务器依赖一样,而配置则通过继承自ResourceServerConfigurerAdapter的配置类来实现:
/**
• @Author 三分恶
• @Date 2020/5/20
• @Description
*/
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Bean
public RemoteTokenServices remoteTokenServices() {
final RemoteTokenServices tokenServices = new RemoteTokenServices();
tokenServices.setClientId(“client-demo”);
tokenServices.setClientSecret(“123”);
tokenServices.setCheckTokenEndpointUrl(“http://localhost:8090/oauth/check_token”);
return tokenServices;
}
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.stateless(true);
}
@Override
public void configure(HttpSecurity http) throws Exception {
//session创建策略
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED);
//所有请求需要认证
http.authorizeRequests().anyRequest().authenticated();
}
}
主要进行了如下配置:
- TokenService配置:在不采用JWT的情况下,需要配置RemoteTokenServices来充当tokenServices,它主要完成Token的校验等工作。因此需要指定校验Token的授权服务器接口地址
- 同时,由于在授权服务器中配置了/oauth/check_token需要客户端登录后才能访问,因此也需要配置客户端编号及Secret;在校验之前先进行登录
- 通过ResourceServerSecurityConfigurer来配置需要访问的资源编号及使用的TokenServices
1.2.2、资源服务接口
接口比较简单:
/**
• @Author 三分恶
• @Date 2020/5/20
• @Description
*/
@RestController
public class ResourceController {
@GetMapping(“/user/{username}”)
public String user(@PathVariable String username){
return “Hello !”+username;
}
}
1.3、测试
授权服务器使用8090端口启动,资源服务器使用默认端口。
1.3.1、获取token
访问/oauth/token端点,获取token:
- url: http://localhost:8090/oauth/token?username=fighter&password=123&scope=read_scope&grant_type=password
- 请求头:
- 返回的token
1.3.2、使用获取到的token访问资源接口
- 使用token调用资源,访问http://localhost:8080/user/fighter,注意使用token添加Bearer请求头
相当于在Headers中添加 Authorization:Bearer 4a3c351d-770d-42aa-af39-3f54b50152e9。
OK,可以看到资源正确返回。
这里仅仅是密码模式的精简化配置,在实际项目中,某些部分如:
- 资源服务访问授权服务去校验token这部分可能会换成Jwt、Redis等tokenStore实现,
- 授权服务器中的用户信息与客户端信息生产环境从数据库中读取,对应Spring Security的UserDetailsService实现类或用户信息的Provider
2、授权码模式
很多网站登录时,允许使用第三方网站的身份,这称为"第三方登录"。所谓第三方登录,实质就是 OAuth 授权。
例如用户想要登录 A 网站,A 网站让用户提供第三方网站的数据,证明自己的身份。获取第三方网站的身份数据,就需要 OAuth 授权。
以A网站使用GitHub第三方登录为例,流程示意如下:
接下来,简单地实现GitHub登录流程。
2.1、应用注册
在使用之前需要先注册一个应用,让GitHub可以识别。
- 访问地址:https:///settings/applications/new,填写注册表
应用的名称随便填,主页 URL 填写http://localhost:8080,回调地址填写 http://localhost:8080/oauth/redirect。
- 提交表单以后,GitHub 应该会返回客户端 ID(client ID)和客户端密钥(client secret),这就是应用的身份识别码
2.2、具体代码
- 只需要引入web依赖:
org.springframework.boot
spring-boot-starter-web
• GitHub相关配置
github.client.clientId=29d127aa0753c12263d7
github.client.clientSecret=f3cb9222961efe4c2adccd6d3e0df706972fa5eb
github.client.authorizeUrl=https:///login/oauth/authorize
github.client.accessTokenUrl=https:///login/oauth/access_token
github.client.redirectUrl=http://localhost:8080/oauth/redirect
github.client.userInfoUrl=https://api./user
• 对应的配置类
@Component
@ConfigurationProperties(prefix = “github.client”)
public class GithubProperties {
private String clientId;
private String clientSecret;
private String authorizeUrl;
private String redirectUrl;
private String accessTokenUrl;
private String userInfoUrl;
//省略getter、setter
}
• index.html:首页比较简单,一个链接向后端发起登录请求
网站首页
Login in with GitHub
• GithubLoginController.java:
* 使用RestTemplate发送http请求
* 使用Jackson解析返回的json,不用引入更多依赖
* 快捷起见,发送http请求的方法直接写在控制器中,实际上应该将工具方法分离出去
* 同样是快捷起见,返回的用户信息没有做任何解析
@Controller
public class GithubLoginController {
@Autowired
GithubProperties githubProperties;
/**
• 登录接口,重定向至github
•
• @return 跳转url
*/
@GetMapping(“/authorize”)
public String authorize() {
String url =githubProperties.getAuthorizeUrl() +
“?client_id=” + githubProperties.getClientId() +
“&redirect_uri=” + githubProperties.getRedirectUrl();
return “redirect:” + url;
}
/**
• 回调接口,用户同意授权后,GitHub会将授权码传递给此接口
• @param code GitHub重定向时附加的授权码,只能用一次
• @return
*/
@GetMapping(“/oauth/redirect”)
@ResponseBody
public String redirect(@RequestParam(“code”) String code) throws JsonProcessingException {
System.out.println(“code:”+code);
// 使用code获取token
String accessToken = this.getAccessToken(code);
// 使用token获取userInfo
String userInfo = this.getUserInfo(accessToken);
return userInfo;
}
/**
• 使用授权码获取token
• @param code
• @return
*/
private String getAccessToken(String code) throws JsonProcessingException {
String url = githubProperties.getAccessTokenUrl() +
“?client_id=” + githubProperties.getClientId() +
“&client_secret=” + githubProperties.getClientSecret() +
“&code=” + code +
“&grant_type=authorization_code”;
// 构建请求头
HttpHeaders requestHeaders = new HttpHeaders();
// 指定响应返回json格式
requestHeaders.add(“accept”, “application/json”);
// 构建请求实体
HttpEntity requestEntity = new HttpEntity<>(requestHeaders);
RestTemplate restTemplate = new RestTemplate();
// post 请求方式
ResponseEntity response = restTemplate.postForEntity(url, requestEntity, String.class);
String responseStr = response.getBody();
// 解析响应json字符串
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(responseStr);
String accessToken = jsonNode.get(“access_token”).asText();
System.out.println(“accessToken:”+accessToken);
return accessToken;
}
/**
•
• @param accessToken 使用token获取userInfo
• @return
*/
private String getUserInfo(String accessToken) {
String url = githubProperties.getUserInfoUrl();
// 构建请求头
HttpHeaders requestHeaders = new HttpHeaders();
// 指定响应返回json格式
requestHeaders.add(“accept”, “application/json”);
// AccessToken放在请求头中