Spring Boot Restful WebAPI集成 OAuth2
系统采用前后端分离的架构,采用OAuth2协议是很自然的事情。
下面开始实战,主要依赖以下两个组件:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
</dependency>
例外还要配置两个Config:
一、认证服务器
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter { @Autowired
private UserApprovalHandler userApprovalHandler; @Autowired
private AuthenticationManager authenticationManager; @Autowired
private TokenStore tokenStore; @Autowired
private MyUserService userService; @Autowired
private ClientDetailsService clientDetailsService; @Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("aizoukeji")
// .authorizedGrantTypes("password", "authorization_code", "implicit")
.authorizedGrantTypes("password")
.authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
.scopes("read", "write", "trust")
.secret("18657189775")
.accessTokenValiditySeconds(60 * 2);//Access token is only valid for 2 minutes.
// refreshTokenValiditySeconds(600);//Refresh token is only valid for 10 minutes.
} @Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(tokenStore)
.userApprovalHandler(userApprovalHandler)
.authenticationManager(authenticationManager)
.userDetailsService(userService);
} @Bean
public TokenStore tokenStore() {
return new InMemoryTokenStore();
} @Bean
@Autowired
public TokenStoreUserApprovalHandler userApprovalHandler(TokenStore tokenStore){
TokenStoreUserApprovalHandler handler = new TokenStoreUserApprovalHandler();
handler.setTokenStore(tokenStore);
handler.setRequestFactory(new DefaultOAuth2RequestFactory(clientDetailsService));
handler.setClientDetailsService(clientDetailsService);
return handler;
} @Bean
@Autowired
public ApprovalStore approvalStore(TokenStore tokenStore) throws Exception {
TokenApprovalStore store = new TokenApprovalStore();
store.setTokenStore(tokenStore);
return store;
}
}
二、资源服务器
@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
private static final String RESOURCE_ID = "my_rest_api"; @Override
public void configure(ResourceServerSecurityConfigurer resources) {
resources.resourceId(RESOURCE_ID).stateless(true);
} @Override
public void configure(HttpSecurity http) throws Exception {
// http.requestMatchers().antMatchers("/**")
// .and()
// .authorizeRequests().antMatchers("/v1/**").authenticated()
// .and()
// .exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler()); http.authorizeRequests().antMatchers("/v1/**").authenticated()
.and()
.exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
}
}
踩过的坑
一开始一直在配置WebSecurityConfigurerAdapter,其实这个跟ResourceServerConfigurerAdapter是冲突的,如果用OAuth来做认证的话,那么只要配置ResourceServerConfigurerAdapter就可以了
延伸
Spring OAuth中有个SSO注解,可以帮助实现单点登录。等项目发展起来以后,我们可以用这个来实现账号的统一授权。
Spring Boot Restful WebAPI集成 OAuth2的更多相关文章
- 【ELK】4.spring boot 2.X集成ES spring-data-ES 进行CRUD操作 完整版+kibana管理ES的index操作
spring boot 2.X集成ES 进行CRUD操作 完整版 内容包括: ============================================================ ...
- 15、Spring Boot 2.x 集成 Swagger UI
1.15.Spring Boot 2.x 集成 Swagger UI 完整源码: Spring-Boot-Demos 1.15.1 pom文件添加swagger包 <swagger2.versi ...
- spring boot rest 接口集成 spring security(2) - JWT配置
Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...
- spring boot rest 接口集成 spring security(1) - 最简配置
Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...
- spring boot / cloud (三) 集成springfox-swagger2构建在线API文档
spring boot / cloud (三) 集成springfox-swagger2构建在线API文档 前言 不能同步更新API文档会有什么问题? 理想情况下,为所开发的服务编写接口文档,能提高与 ...
- Spring Boot HikariCP 一 ——集成多数据源
其实这里介绍的东西主要是参考的另外一篇文章,数据库读写分离的. 参考文章就把链接贴出来,里面有那位的代码,简单明了https://gitee.com/comven/dynamic-datasource ...
- Spring Boot系列——如何集成Log4j2
上篇<Spring Boot系列--日志配置>介绍了Spring Boot如何进行日志配置,日志系统用的是Spring Boot默认的LogBack. 事实上,除了使用默认的LogBack ...
- 使用 JSONDoc 记录 Spring Boot RESTful API
这个博文可以分为两部分:第一部分我将编写一个Spring Boot RESTful API,第二部分将介绍如何使用JSONDoc来记录创建的API.做这两个部分最多需要15分钟,因为使用Spring ...
- 14、Spring Boot 2.x 集成 Druid 数据源
14.Spring Boot 2.x 集成 Druid 数据源 完整源码: Spring-Boot-Demos
随机推荐
- vue父组件与子组件之间的数据传递
父组件向子组件传递数据 父组件用数据绑定:子组件用props接收 <!-- test-vue-model父组件 --> <template> <div> <m ...
- JVM系列文章合集
博客作者:纯洁的微笑 JVM系列(①):java类的加载机制 JVM系列(②):JVM内存结构 JVM系列(③):GC算法 垃圾收集器 JVM系列(④):jvm调优-命令大全(jps jstat jm ...
- python基础【第七篇】
字典 列表可以存储大量的数据类型,但是只能按照顺序存储,数据与数据之间关联性不强. 所以咱们需要引入一种容器型的数据类型,解决上面的问题,这就需要dict字典. 字典(dict)是python中唯⼀的 ...
- window下eclipse搭建hadoop环境
1 生成插件jar 1.1 安装java,ant运行环境 1.2 下载hadoop-2.5.0.tar.gz并解压到指定目录 1.3 下载hadoop2x-eclipse-plugin-master. ...
- [轉]C/C++中的volatile使用時機?
不知各位對volatile(揮發性的)這個字陌不陌生? 我相信大家在一些程式或多或少都看 過這個字眼, 但是究竟要在何種場合用它呢?.當然一定是有需要, C/C++才會有這個保留字, 否則只是增加pr ...
- shell脚本命令行参数里的空白符
看一个小脚本 #!/bin/bash #demonstarting the shift command count= while [ -n "$1" ] ; do echo &qu ...
- add characteristic to color
Problem: add a new Char. name D_COI6 that the description is Injected coloration #7 (COI6) in the D_ ...
- springboot整合RocketMq(非事务)
1.配置文件 1.yml配置文件 rocketmq: #mq配置 producer: iseffect: true type: default # (transaction,default) tran ...
- 【牛客网-剑指offer】旋转数组的最小数字
题目: 把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转. 输入一个非递减排序的数组的一个旋转,输出旋转数组的最小元素. 例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋 ...
- Android VideoView无法播放网络视频
今天学习Android播放视频和音频,其中在练习播放视频的时候无法播放网络视频,网络视频是别人发布在网上的,但是把视频放在本地是可以的,最后推测是没有开放网络的访问权限的问题,果然开放了之后就能正常访 ...