spring security OAuth2.0之客户端Client的实现
项目代码:https://github.com/hankuikuide/microservice-spring-security-oauth2
网上多数的项目客户端都是采用纯js写,或用postman发请求,和实际项目的应用还是有差距的,这里也是采用spring boot的实现。 主要功能在于:
- 使用授权码模式进行认证。
- 使用OAuth2RestTemplate发送请求给认证服务器和资源服务器,
- 结合Feign实现loadbalance.
先进行security的配置:
@Configuration
@EnableOAuth2Sso
public class UiSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired
OAuth2ClientAuthenticationProcessingFilter oauth2ClientAuthenticationProcessingFilter; @Override
public void configure(HttpSecurity http) throws Exception {
http.antMatcher("/**")
.authorizeRequests()
.antMatchers("/", "/login**")
.permitAll().anyRequest().authenticated()
.and()
.addFilterBefore(oauth2ClientAuthenticationProcessingFilter,BasicAuthenticationFilter.class)
.csrf().disable(); } }
在BasicAuthenticationFilter之前添加了一个过滤器。
客户端中最关键的代码,如下:
核心功能是
1. 注册OAuth2RestTemplate,
2.注册处理redirect uri的filter.也就是上面说的过滤器。
3. 注册check token服务
有了这个类,使用授权码模式,就可以把登录成功后的授权码接收到,并自动发给认证服务器请求token,并在后续的请求中自动添加token了。
@Configuration
public class Oauth2ClientConfig { private String redirectUri ="http://localhost:9001/login";
private String checkTokenUrl ="http://localhost:9002/auth/oauth/check_token"; @Bean
public OAuth2RestTemplate oauth2RestTemplate(OAuth2ClientContext context, OAuth2ProtectedResourceDetails details) {
OAuth2RestTemplate template = new OAuth2RestTemplate(details, context); AuthorizationCodeAccessTokenProvider authCodeProvider = new AuthorizationCodeAccessTokenProvider();
authCodeProvider.setStateMandatory(false);
AccessTokenProviderChain provider = new AccessTokenProviderChain(
Arrays.asList(authCodeProvider));
template.setAccessTokenProvider(provider); return template;
} /**
* 注册处理redirect uri的filter
* @param oauth2RestTemplate
* @param tokenService
* @return
*/
@Bean
public OAuth2ClientAuthenticationProcessingFilter oauth2ClientAuthenticationProcessingFilter(
OAuth2RestTemplate oauth2RestTemplate,
RemoteTokenServices tokenService) {
OAuth2ClientAuthenticationProcessingFilter filter = new OAuth2ClientAuthenticationProcessingFilter(redirectUri);
filter.setRestTemplate(oauth2RestTemplate);
filter.setTokenServices(tokenService); //设置回调成功的页面
filter.setAuthenticationSuccessHandler(new SimpleUrlAuthenticationSuccessHandler() {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
this.setDefaultTargetUrl("/home");
super.onAuthenticationSuccess(request, response, authentication);
}
});
return filter;
}
/**
* 注册check token服务
* @param details
* @return
*/
@Bean
public RemoteTokenServices tokenService(OAuth2ProtectedResourceDetails details) {
RemoteTokenServices tokenService = new RemoteTokenServices();
tokenService.setCheckTokenEndpointUrl(checkTokenUrl);
tokenService.setClientId(details.getClientId());
tokenService.setClientSecret(details.getClientSecret());
return tokenService;
}
}
再有虽然我们这里配置了OAuth2RestTemplate,但是通过为了实现loadbalance,通过我们会使用FeignClient,介绍一下如何将二者结合使用。
为了使用@EnableFeignClients
首先引入依赖管理:
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
启用FeignClient
@SpringBootApplication
@EnableFeignClients
public class ClientApplication {
@Bean
public RequestContextListener requestContextListener() {
return new RequestContextListener();
} public static void main(String[] args) {
SpringApplication.run(ClientApplication.class, args);
} }
重要的配置来了:配置请求拦截器,并注入OAuth2RestTemplate
@Configuration
public class OAuth2FeignAutoConfiguration { @Bean
public RequestInterceptor oauth2FeignRequestInterceptor( OAuth2RestTemplate oAuth2RestTemplate) {
return new OAuth2FeignRequestInterceptor(oAuth2RestTemplate);
}
}
实现这个拦截器:代码很简单就是把OAuth2RestTemplate 的token取出来放在restTemplate的header上,
public class OAuth2FeignRequestInterceptor implements RequestInterceptor {
private static final String AUTHORIZATION_HEADER = "Authorization";
private static final String BEARER_TOKEN_TYPE = "Bearer";
private final OAuth2RestTemplate oAuth2RestTemplate;
public OAuth2FeignRequestInterceptor(OAuth2RestTemplate oAuth2RestTemplate) {
this.oAuth2RestTemplate = oAuth2RestTemplate;
}
@Override
public void apply(RequestTemplate template) {
System.out.println("Constructing Header "+AUTHORIZATION_HEADER+" for Token " + BEARER_TOKEN_TYPE +":" +oAuth2RestTemplate.getAccessToken().toString());
template.header(AUTHORIZATION_HEADER,
String.format("%s %s",
BEARER_TOKEN_TYPE,
oAuth2RestTemplate.getAccessToken().toString()));
}
}
定义服务接口
@FeignClient(name = "resource-service", url = "http://localhost:9003/auth", fallback = ResourceServiceFallback.class )
public interface ResourceService { @RequestMapping(value = "/hello", method = RequestMethod.GET)
String hello();
}
大功告成!
spring security OAuth2.0之客户端Client的实现的更多相关文章
- springboot+spring security +oauth2.0 demo搭建(password模式)(认证授权端与资源服务端分离的形式)
项目security_simple(认证授权项目) 1.新建springboot项目 这儿选择springboot版本我选择的是2.0.6 点击finish后完成项目的创建 2.引入maven依赖 ...
- 基于spring boot2.0+spring security +oauth2.0+ jwt微服务架构
github地址:https://github.com/hankuikuide/microservice-spring-security-oauth2 项目介绍 该项目是一个演示项目,主要演示了,基于 ...
- Spring Security OAuth2.0认证授权四:分布式系统认证授权
Spring Security OAuth2.0认证授权系列文章 Spring Security OAuth2.0认证授权一:框架搭建和认证测试 Spring Security OAuth2.0认证授 ...
- 【OAuth2.0】Spring Security OAuth2.0篇之初识
不吐不快 因为项目需求开始接触OAuth2.0授权协议.断断续续接触了有两周左右的时间.不得不吐槽的,依然是自己的学习习惯问题,总是着急想了解一切,习惯性地钻牛角尖去理解小的细节,而不是从宏观上去掌握 ...
- Spring Security OAuth2.0 - AuthorizationServer和ResourceServer分离
<Spring Security实现OAuth2.0授权服务 - 基础版>和<Spring Security实现OAuth2.0授权服务 - 进阶版>两篇文章中介绍如何搭建OA ...
- Spring Security OAuth2.0认证授权三:使用JWT令牌
Spring Security OAuth2.0系列文章: Spring Security OAuth2.0认证授权一:框架搭建和认证测试 Spring Security OAuth2.0认证授权二: ...
- Spring Security OAuth2.0认证授权五:用户信息扩展到jwt
历史文章 Spring Security OAuth2.0认证授权一:框架搭建和认证测试 Spring Security OAuth2.0认证授权二:搭建资源服务 Spring Security OA ...
- Spring Security OAuth2.0认证授权六:前后端分离下的登录授权
历史文章 Spring Security OAuth2.0认证授权一:框架搭建和认证测试 Spring Security OAuth2.0认证授权二:搭建资源服务 Spring Security OA ...
- Spring Security OAuth2.0认证授权二:搭建资源服务
在上一篇文章[Spring Security OAuth2.0认证授权一:框架搭建和认证测试](https://www.cnblogs.com/kuangdaoyizhimei/p/14250374. ...
随机推荐
- Python爬虫十六式 - 第三式:Requests的用法
Requests: 让 HTTP 服务人类 学习一时爽,一直学习一直爽 Hello,大家好,我是Connor,一个从无到有的技术小白.今天我们继续来说我们的 Python 爬虫,上一次我们说到了 ...
- Codeforces Round #302 (Div. 2) D. Destroying Roads 最短路 删边
题目:有n个城镇,m条边权为1的双向边让你破坏最多的道路,使得从s1到t1,从s2到t2的距离分别不超过d1和d2. #include <iostream> #include <cs ...
- sqli-labs(23)
基于get的过滤了的注入 0X1测试闭合 /?id=' http://127.0.0.1/sql1/Less-23/?id=1%27%27 0X02 然后就是组合拳的操作了 未报错 那么应该是’闭合 ...
- 测试常用命令之awk篇
awk/gawk 1,内置变量 FILENAME:输入文件名称 FNR:当前数据文件中的数据行数 NF:数据文件中的字段总数 NR:已处理的输入数据行数目 FS:输入数据段分隔符 RS:输入数据行分隔 ...
- Java虚拟机JVM详解
一.JVM内存管理 1.1JVM运行时数据区 1.1.1程序计数器:记录当前线程正在执行的字节码指定的地址(行号) 为什么需要它:程序容易被打断 1.1.2虚拟机栈:存储当前线程运行方法时所需要的数据 ...
- JavaWEB开发03——JS
今日任务 使用JS完成页面定时弹出广告 使用JS完成表单的校验 使用JS完成表格的隔行换色 使用JS完成复选框的全选效果 使用JS完成省市的联动效果 JS控制下拉列表左右选择 教学导航 掌握JS中的B ...
- k8s中pod内dns无法解析的问题
用k8s创建了pod,然后进入pod后,发现在pod中无法解析www.baidu.com,也就是出现了无法解析外面的域名的问题.经过高人指点,做个小总结.操作如下. 一,将CoreDNS 的Confi ...
- legend3---Laravel Homestead的安装和使用
legend3---Laravel Homestead的安装和使用 一.总结 一句话总结: 配置好homestead之后编码非常方便:在虚拟机或者外部机器里面操作代码两者都会同时改变. 1.Homes ...
- zay大爷的神仙题目 D1T1-大美江湖
在前几天的时候,千古神犇zay(吊打zhx那个)出了一套神仙题目,所以我得来分析分析QWQ 先补个网易云链接QWQ 毕竟是T1嘛,还算是比较简单的,那道题,读完题目就发现是个中等模拟(猪国杀算大模拟的 ...
- 阶段3 1.Mybatis_12.Mybatis注解开发_6 mybatis注解开发一对一的查询配置
新建Account实体类 生成getter和setter还有toString方法 先创建dao类 全局的配置,这里要改成package 创建多对一的关系 在查询的时候输出user这个对象的内容 建立查 ...