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@EnableAuthorizationServerpublic 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@EnableResourceServerpublic 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注解,可以帮助实现单点登录。等项目发展起来以后,我们可以用这个来实现账号的统一授权。

时间: 2024-08-25 12:36:25

Spring Boot Restful WebAPI集成 OAuth2的相关文章

【ELK】3.spring boot 2.X集成ES spring-data-ES 进行CRUD操作 完整版

spring boot 2.X集成ES 进行CRUD操作  完整版 内容包括: ========================================================================================= 1.CRUD:单字段查询.复合查询.分页查询.评分查询 2.时间范围查询 3.GET方法传入时间类型解析不了的问题 4.term和match查询的区别 5.filter+query查询的区别 6.自定义ES的mapping,自定义setti

Spring Boot系列——如何集成Log4j2

上篇<Spring Boot系列--日志配置>介绍了Spring Boot如何进行日志配置,日志系统用的是Spring Boot默认的LogBack. 事实上,除了使用默认的LogBack,Spring Boot还可以使用Log4j.Log42等作为自己的日志系统.今天就那Log4j2来举例,说明Spring Boot是如何集成其他日志系统的. 添加jar包依赖 上篇提到过,Spring Boot默认使用LogBack,但是我们没有看到显示依赖的jar包,其实是因为所在的jar包spring-

深入Spring Boot:快速集成Dubbo + Hystrix

背景Hystrix 旨在通过控制那些访问远程系统.服务和第三方库的节点,从而对延迟和故障提供更强大的容错能力.Hystrix具备拥有回退机制和断路器功能的线程和信号隔离,请求缓存和请求打包,以及监控和配置等功能.Dubbo是Alibaba开源的,目前国内最流行的java rpc框架.本文介绍在spring应用里,怎么把Dubbo和Hystrix结合起来使用.Spring Boot应用生成dubbo集成spring boot的应用配置spring-cloud-starter-netflix-hys

Spring Boot之Swagger2集成

一.Swagger2简单介绍 Swagger2,它可以轻松的整合到Spring Boot中,并与Spring MVC程序配合组织出强大RESTful API文档.它既可以减少我们创建文档的工作量,同时说明内容又整合入实现代码中,让维护文档和修改代码整合为一体,可以让我们在修改代码逻辑的同时方便的修改文档说明.另外Swagger2也提供了强大的页面测试功能来调试每个RESTful API. 二.Spring Boot集成Swagger2步骤 1)引入Swagger2的Maven坐标 <!--swa

Spring Boot 数据访问集成 MyBatis

对于软件系统而言,持久化数据到数据库是至关重要的一部分.在 Java 领域,有很多的实现了数据持久化层的工具和框架(ORM).在 Java 应用程序中,ORM 框架的本质是简化编程中操作数据库的繁琐性,比如可以根据对象生成 SQL 的 Hibernate ,后面 Hibernate 也实现了JPA 的规范,使用 JPA 的方式只需要几行代码即可实现对数据的访问和操作:MyBatis 的前身是 IBATIS 是一个简化和实现了 Java 数据持久化层的开源框架,可以灵活调试 SQL , MyBat

spring boot(十八)集成FastDFS文件上传下载

上篇文章介绍了如何使用Spring Boot上传文件,这篇文章我们介绍如何使用Spring Boot将文件上传到分布式文件系统FastDFS中. 这个项目会在上一个项目的基础上进行构建. 1.pom包配置 我们使用Spring Boot最新版本1.5.9.jdk使用1.8.tomcat8.0. <dependency> <groupId>org.csource</groupId> <artifactId>fastdfs-client-java</art

Spring Boot 两步集成 日志收集ELK与分布式系统监控CAT

日志收集ELK与分布式系统监控CAT Spring Boot项目集成方法 一. pom.xml引入starter依赖 <dependency> <groupId>com.louis</groupId> <artifactId>ylog-spring-boot-starter</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> 二. boots

Spring Boot注解方式集成Mybatis

一.无配置文件注解版 1.pom文件必要jar包的引入 1 <dependency> 2 <groupId>mysql</groupId> 3 <artifactId>mysql-connector-java</artifactId> 4 </dependency> 5 <dependency> 6 <groupId>org.mybatis.spring.boot</groupId> 7 <a

spring boot 和 mybatis集成

1.pom.xml 添加mybatis和mysql依赖 <!-- 添加 MyBatis --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.2.0</version> </dependency> <!