Spring Boot + Spring Security OAuth2示例
简介
在这篇文章中,我们将讨论使用Spring Boot + Spring Security OAuth2保护REST API的示例。我们将实现AuthorizationServer,ResourceServer和一些REST API用于不同的CRUD基本操作并使用Postman测试通过这些API。我们将使用MySQL数据库来读取用户凭据而不是内存中的身份验证。另外,为了简化我们的ORM解决方案,我们将使用spring-data-jpa和BCryptPasswordEncoder进行密码编码,以最快的速度上手。
了解OAuth
OAuth只是一种安全授权协议,用于处理第三方应用程序的授权,使第三方应用程序能够获得对Web服务的有限访问权限,以便在不泄露密码的情况下访问用户数据。(例如在许多网站上使用fackbook,twitter登录)所有工作都在此协议下。对OAuth有相关的知识了解,掌握及上手更容易。基本上涉及三方:OAuth提供商,OAuth客户和所有者。在此,OAuth提供商提供诸如Facebook,Twitter等身份验证令牌。同样,OAuth Client是希望代表所有者访问凭证的应用程序,所有者是在OAuth提供程序(如facebook和twitter)上拥有帐户的用户。
了解OAuth2
OAuth2是一种授权框架,,使应用程序能够获得对HTTP服务(如Facebook,GitHub)上的用户帐户的访问权限。它的工作原理是将用户身份验证委派给托管用户帐户的服务,并授权第三方应用程序访问用户帐户。OAuth 2为Web和桌面应用程序以及移动设备提供授权流程。
OAuth2角色
OAuth2提供4种不同的角色:
资源所有者(Resource Owner)
资源服务器(Resource Server)
授权服务器(Authorization Server)
客户端(Client)
Maven依赖(Maven Dependencies)
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-security-oauth2</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
OAuth2授权服务器配置
这个类扩展AuthorizationServerConfigurerAdapter并负责生成特定于客户端的令牌。在这里,我们使用内存凭证,其中client_id为test-client,CLIENT_SECRET为test-secret。但您也可以自由使用JDBC实现。
@EnableAuthorizationServer:启用授权服务器.AuthorizationServerEndpointsConfigurer定义授权和令牌端点以及令牌服务。
- AuthorizationConfig.java
package com.battle.oauth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org