系统采用前后端分离的架构,采用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的更多相关文章

  1. 【ELK】4.spring boot 2.X集成ES spring-data-ES 进行CRUD操作 完整版+kibana管理ES的index操作

    spring boot 2.X集成ES 进行CRUD操作  完整版 内容包括: ============================================================ ...

  2. 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 ...

  3. spring boot rest 接口集成 spring security(2) - JWT配置

    Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...

  4. spring boot rest 接口集成 spring security(1) - 最简配置

    Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...

  5. spring boot / cloud (三) 集成springfox-swagger2构建在线API文档

    spring boot / cloud (三) 集成springfox-swagger2构建在线API文档 前言 不能同步更新API文档会有什么问题? 理想情况下,为所开发的服务编写接口文档,能提高与 ...

  6. Spring Boot HikariCP 一 ——集成多数据源

    其实这里介绍的东西主要是参考的另外一篇文章,数据库读写分离的. 参考文章就把链接贴出来,里面有那位的代码,简单明了https://gitee.com/comven/dynamic-datasource ...

  7. Spring Boot系列——如何集成Log4j2

    上篇<Spring Boot系列--日志配置>介绍了Spring Boot如何进行日志配置,日志系统用的是Spring Boot默认的LogBack. 事实上,除了使用默认的LogBack ...

  8. 使用 JSONDoc 记录 Spring Boot RESTful API

    这个博文可以分为两部分:第一部分我将编写一个Spring Boot RESTful API,第二部分将介绍如何使用JSONDoc来记录创建的API.做这两个部分最多需要15分钟,因为使用Spring ...

  9. 14、Spring Boot 2.x 集成 Druid 数据源

    14.Spring Boot 2.x 集成 Druid 数据源 完整源码: Spring-Boot-Demos

随机推荐

  1. 网神SecVSS 3600漏洞扫描系统

    网神SecVSS 3600漏洞扫描系统严格按照计算机信息系统安全的国家标准.相关行业标准设计.编写.制造.网神SecVSS 3600漏洞扫描系统可以对不同操作系统下的计算机(在可扫描IP范围内)进行漏 ...

  2. The request with exception: The SSL connection could not be established, see inner exception. requestId 解决方案

    DOTNET CORE 部署 Centos7 抛出异常 环境变量如下: .NET Core SDK (reflecting any global.json): Version: 2.2.401 Com ...

  3. redis zset 介绍

    $key = 'key'; //新增 zadd($key,分数,标识) //删除某个标识 zrem($key,标识) //查询某个标识的排名(从0开始的 所有在输出的时候要加一) zrevrank($ ...

  4. 马士兵对话京东T6阿里P7(薪水):月薪5万,他为何要离职?

    马士兵大佬你知道吗? 你竟然不知道?你怎么可能不知道!你不知道是不可能的! 记得自己的第一行Java代码,你的Hello World是跟着谁学的吗?我的就是马士兵老师! 马士兵是唯一一个在当时讲课是让 ...

  5. jdk紧急漏洞,XMLDecoder反序列化攻击

    昨天在公司发现了一个jdk中的XMLDecoder反序列化的漏洞,看起来很危险!下面通过两个示例来看看这个漏洞的危害! 示例1:利用XmlDecoder删除本地文件 首先来看这个xmldecoder. ...

  6. Android组件内核之Activity调用栈分析(一)

    阿里P7Android高级架构进阶视频免费学习请点击:https://space.bilibili.com/474380680 导语 我们陈述一下Activity,Activity是整个应用用户交互的 ...

  7. git拉取远程所有分支

    第一步: git branch -r | grep -v '->' | while read remote; do git branch --track "${remote#origi ...

  8. ArrayList的几种初始化方法

    1.使用Arrays.asList方法 ArrayList<Object> obj = new ArrayList<Object>(Arrays.asList(Object o ...

  9. 如何通过cmd命令远程重启或远程关闭Windows服务器

    一.想要远程控制服务器,前提条件是远程服务器需要开启IPC$ ,且本地能访问远程服务器445端口 1.开启ipc$ net share IPC$ 2.如果只指定管理员才有执行ipc$的权限 net s ...

  10. Raid,分区表与LVM逻辑卷

    1.组Raid 磁盘前512K组合 前446K:MBR引导程序 中64K:分区表 后2K:校检码 Raid0:极致的读写速度,一个数据分散到多个盘去读写.但是极不安全,一旦坏了一块盘那么所有盘都将无法 ...