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
随机推荐
- Rust <8>:lifetime 高级语法与 trait 关联绑定
一.生命周期关联:如下声明表示,'s >= 'c struct Parser<'c, 's: 'c> { context: &'c Context<'s>, } ...
- redis基本介绍搭建篇
1.redis基本介绍 1.1 redis介绍 Redis属于非关系型数据库和Memcached类似,redis也是一个key-value型存储系统. 但redis支持的存储value类型相对更多,包 ...
- 2.3 Nginx服务的启停控制
在Linux平台下,控制Nginx服务的启停有多种方法 2.3.1 Nginx服务的信号控制 在Nginx服务的启停办法中,有一类是通过信号机制来实现的,Nginx服务器的信号控制如下: Nginx服 ...
- 在同一个项目中灵活运用application/json 和application/x-www-form-urlencoded 两种传输格式(配合axios,同时配置loading)
'use strict' import axios from 'axios' // import qs from 'qs' import { Notification} from 'element-u ...
- 我的scoi2018
高一,很尴尬,凉~ -------- 大家好,我是分界线,我弱弱的说本次采用倒序的写作手法 -------- 故事是这样讲的: Day0: 刚刚去那个电科搞的集训,早上才考了一波模拟赛,下午就过来住酒 ...
- CICS FILE OPEN
CEMT I CECD V FILE() GROUP() CEDA check error log in JESYSMSG FILE OPEN/CLOSE STATUS CICS ACTION res ...
- ICPC2008哈尔滨-A-Array Without Local Maximums
题目描述 Ivan unexpectedly saw a present from one of his previous birthdays. It is array of n numbers fr ...
- 63. (FileInputStream)输入字节流
IO分类: 按照数据流向分类: 输入流 输出流 按照处理的单位划分: 字节流:字节流读取的都是文件中的二进制数据,读取到的 ...
- BZOJ 3252: 攻略(思路题)
传送门 解题思路 比较好想的一道思路题,结果有个地方没开\(long\) \(long\) \(wa\)了三次..其实就是模仿一下树链剖分,重新定义重儿子,一个点的重儿子为所有儿子中到叶节点权值最大的 ...
- linux基础知识汇总(四)--ps grep命令
转:http://www.cnblogs.com/allen8807/archive/2010/11/10/1873843.html http://www.cnblogs.com/end/archiv ...