开发手册 欢迎您!
软件开发者资料库

Spring Boot - 使用JWT的OAuth2

使用JWT的Spring Boot OAuth2 - 从基本到高级概念的简单简单步骤学习Spring Boot,其中包括简介,快速入门,Bootstrapping,Tomcat部署,构建系统,代码结构,Spring Bean和依赖注入,Runners,Application Properties,记录,构建RESTful Web服务,异常处理,拦截器,Servlet过滤器,Tomcat端口号,Rest模板,文件处理,服务组件,Thymeleaf,使用RESTful Web服务,CORS支持,国际化,调度,启用HTTPS,Eureka服务器,服务注册与Eureka,Zuul代理服务器和路由,Spring云配置服务器,Spring云配置客户端,执行器,管理服务器,管理客户端,启用Swagger2,创建Docker镜像,跟踪微服务日志,Flyway数据库,发送电子邮件,Hystrix,Web套接字,批处理服务,Apache Kafka的Spring,Twilio,单元测试用例,休息控制器单元测试,数据库处理,保护我们b应用程序,带有JWT的OAuth2,Google云平台,Google OAuth2登录。

在本章中,您将详细了解Spring Boot Security机制和使用JWT的OAuth2.

授权服务器

授权服务器是一个Web API安全性的最高架构组件.授权服务器充当集中授权点,允许您的应用和HTTP端点识别应用程序的功能.

资源服务器

资源服务器是一个应用程序,它为客户端提供访问令牌以访问资源服务器HTTP端点.它是包含HTTP端点,静态资源和动态网页的库集合.

OAuth2

OAuth2是一个授权框架,可以启用应用程序Web Security从客户端访问资源.要构建OAuth2应用程序,我们需要关注授权类型(授权代码),客户端ID和客户端密钥.

JWT令牌

JWT令牌是一个JSON Web令牌,用于表示双方之间保密的声明.您可以在 www.jwt.io/了解有关JWT令牌的更多信息.

现在,我们将构建一个OAuth2应用程序,该应用程序可以在JWT令牌的帮助下使用授权服务器,资源服务器.

您可以使用以下通过访问数据库,使用JWT令牌实现Spring Boot Security的步骤.

首先,我们需要在构建配置文件中添加以下依赖项.

Maven用户可以在pom.xml文件中添加以下依赖项.

   org.springframework.boot   spring-boot-starter-jdbc   org.springframework.boot   spring-boot-starter-security   org.springframework.boot   spring-boot-starter-web   org.springframework.security.oauth   spring-security-oauth2   org.springframework.security   spring-security-jwt   com.h2database   h2   org.springframework.boot   spring-boot-starter-test   test   org.springframework.security   spring-security-test   test

Gradle用户可以在build.gradle文件中添加以下依赖项.

compile('org.springframework.boot:spring-boot-starter-security')compile('org.springframework.boot:spring-boot-starter-web')testCompile('org.springframework.boot:spring-boot-starter-test')testCompile('org.springframework.security:spring-security-test')compile("org.springframework.security.oauth:spring-security-oauth2")compile('org.springframework.security:spring-security-jwt')compile("org.springframework.boot:spring-boot-starter-jdbc")compile("com.h2database:h2:1.4.191")

其中,

  • Spring Boot Starter Security : 实现Spring Security

  • Spring Security OAuth2 : 实现OAUTH2结构以启用授权服务器和资源服务器.

  • Spring Security JWT : 为Web安全生成JWT令牌

  • Spring Boot Starter JDBC : 访问数据库以确保用户可用.

  • Spring Boot Starter Web : 写入HTTP端点.

  • H2数据库 : 存储用于身份验证和授权的用户信息.

完整的构建配置文件如下所示.

      4.0.0   com.IT屋   websecurityapp   0.0.1-SNAPSHOT   jar   websecurityapp   Demo project for Spring Boot         org.springframework.boot      spring-boot-starter-parent      1.5.9.RELEASE                   UTF-8      UTF-8      1.8                     org.springframework.boot         spring-boot-starter-jdbc                           org.springframework.boot         spring-boot-starter-security                           org.springframework.boot         spring-boot-starter-web                           org.springframework.security.oauth         spring-security-oauth2                           org.springframework.security         spring-security-jwt                           com.h2database         h2                           org.springframework.boot         spring-boot-starter-test         test                           org.springframework.security         spring-security-test         test                                       org.springframework.boot            spring-boot-maven-plugin                     

Gradle  -  build.gradle

buildscript {   ext {      springBootVersion = '1.5.9.RELEASE'   }   repositories {      mavenCentral()   }   dependencies {      classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")   }}apply plugin: 'java'apply plugin: 'eclipse'apply plugin: 'org.springframework.boot'group = 'com.it1352'version = '0.0.1-SNAPSHOT'sourceCompatibility = 1.8repositories {   mavenCentral()}dependencies {   compile('org.springframework.boot:spring-boot-starter-security')   compile('org.springframework.boot:spring-boot-starter-web')   testCompile('org.springframework.boot:spring-boot-starter-test')   testCompile('org.springframework.security:spring-security-test')   compile("org.springframework.security.oauth:spring-security-oauth2")   compile('org.springframework.security:spring-security-jwt')   compile("org.springframework.boot:spring-boot-starter-jdbc")   compile("com.h2database:h2:1.4.191")  }

现在,在主要的Spring Boot应用程序中,添加@EnableAuthorizationServer和@EnableResourceServer注释,以在同一应用程序中充当Auth服务器和资源服务器.

此外,您可以使用以下使用JWT Token编写一个简单的HTTP端点以使用Spring Security访问API的代码.

package com.it1352.websecurityapp; import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@SpringBootApplication@EnableAuthorizationServer@EnableResourceServer@RestControllerpublic class WebsecurityappApplication {   public static void main(String[] args) {      SpringApplication.run(WebsecurityappApplication.class, args);   }   @RequestMapping(value = "/products")   public String getProductName() {      return "Honey";      }}

使用以下代码定义POJO类以存储用户身份以进行身份验证.

package com.it1352.websecurityapp; import java.util.ArrayList;import java.util.Collection;import org.springframework.security.core.GrantedAuthority;public class UserEntity {   private String username;   private String password;   private Collection grantedAuthoritiesList = new ArrayList<>();      public String getPassword() {      return password;   }   public void setPassword(String password) {      this.password = password;   }   public Collection getGrantedAuthoritiesList() {      return grantedAuthoritiesList;   }   public void setGrantedAuthoritiesList(Collection grantedAuthoritiesList) {      this.grantedAuthoritiesList = grantedAuthoritiesList;   }   public String getUsername() {      return username;   }   public void setUsername(String username) {      this.username = username;   }}

现在,使用以下代码并定义扩展org.springframework.security.core的CustomUser类.用于Spring Boot身份验证的userdetails.User类.

package com.it1352.websecurityapp; import org.springframework.security.core.userdetails.User;public class CustomUser extends User {   private static final long serialVersionUID = 1L;   public CustomUser(UserEntity user) {      super(user.getUsername(), user.getPassword(), user.getGrantedAuthoritiesList());   }}

您可以创建@Repository类以从数据库中读取用户信息并将其发送给Custom用户服务并添加授权的权限"ROLE_SYSTEMADMIN".

package com.it1352.websecurityapp; import java.sql.ResultSet;import java.util.ArrayList;import java.util.Collection;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.security.core.GrantedAuthority;import org.springframework.security.core.authority.SimpleGrantedAuthority;import org.springframework.stereotype.Repository;@Repositorypublic class OAuthDao {   @Autowired   private JdbcTemplate jdbcTemplate;   public UserEntity getUserDetails(String username) {      Collection grantedAuthoritiesList = new ArrayList<>();      String userSQLQuery = "SELECT * FROM USERS WHERE USERNAME=?";      List list = jdbcTemplate.query(userSQLQuery, new String[] { username },         (ResultSet rs, int rowNum) -> {                  UserEntity user = new UserEntity();         user.setUsername(username);         user.setPassword(rs.getString("PASSWORD"));         return user;      });      if (list.size() > 0) {         GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_SYSTEMADMIN");         grantedAuthoritiesList.add(grantedAuthority);         list.get(0).setGrantedAuthoritiesList(grantedAuthoritiesList);         return list.get(0);      }      return null;   }}

您可以创建扩展org.springframework.security.core.userdetails的自定义用户详细信息服务类. UserDetailsService调用DAO存储库类,如图所示.

package com.it1352.websecurityapp; import org.springframework.beans.factory.annotation.Autowired;import org.springframework.security.core.userdetails.UserDetailsService;import org.springframework.security.core.userdetails.UsernameNotFoundException;import org.springframework.stereotype.Service;@Servicepublic class CustomDetailsService implements UserDetailsService {   @Autowired   OAuthDao oauthDao;   @Override   public CustomUser loadUserByUsername(final String username) throws UsernameNotFoundException {      UserEntity userEntity = null;      try {         userEntity = oauthDao.getUserDetails(username);         CustomUser customUser = new CustomUser(userEntity);         return customUser;      } catch (Exception e) {         e.printStackTrace();         throw new UsernameNotFoundException("User " + username + " was not found in the database");      }   }}

接下来,创建一个@configuration类以启用Web Security,定义密码编码器(BCryptPasswordEncoder),并定义AuthenticationManager bean.安全配置类应扩展WebSecurityConfigurerAdapter类.

package com.it1352.websecurityapp; import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.security.authentication.AuthenticationManager;import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.config.annotation.web.builders.WebSecurity;import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;import org.springframework.security.config.http.SessionCreationPolicy;import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;import org.springframework.security.crypto.password.PasswordEncoder;@Configuration@EnableWebSecurity@EnableGlobalMethodSecurity(prePostEnabled = true)public class SecurityConfiguration extends WebSecurityConfigurerAdapter {   @Autowired   private CustomDetailsService customDetailsService;   @Bean   public PasswordEncoder encoder() {      return new BCryptPasswordEncoder();   }   @Override   @Autowired   protected void configure(AuthenticationManagerBuilder auth) throws Exception {      auth.userDetailsService(customDetailsService).passwordEncoder(encoder());   }   @Override   protected void configure(HttpSecurity http) throws Exception {      http.authorizeRequests().anyRequest().authenticated().and().sessionManagement()         .sessionCreationPolicy(SessionCreationPolicy.NEVER);   }   @Override   public void configure(WebSecurity web) throws Exception {      web.ignoring();   }   @Override   @Bean   public AuthenticationManager authenticationManagerBean() throws Exception {      return super.authenticationManagerBean();   }}

现在,定义OAuth2配置类以添加客户端ID,客户端密钥,定义JwtAccessTokenConverter,私钥和令牌签名者密钥和验证者密钥的公钥,并使用范围为令牌有效性配置ClientDetailsServiceConfigurer.

package com.it1352.websecurityapp ; import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.context.annotation.Bean;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.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;@Configurationpublic class OAuth2Config extends AuthorizationServerConfigurerAdapter {   private String clientid = "it1352";   private String clientSecret = "my-secret-key";   private String privateKey = "private key";   private String publicKey = "public key";   @Autowired   @Qualifier("authenticationManagerBean")   private AuthenticationManager authenticationManager;      @Bean   public JwtAccessTokenConverter tokenEnhancer() {      JwtAccessTokenConverter converter = new JwtAccessTokenConverter();      converter.setSigningKey(privateKey);      converter.setVerifierKey(publicKey);      return converter;   }   @Bean   public JwtTokenStore tokenStore() {      return new JwtTokenStore(tokenEnhancer());   }   @Override   public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {      endpoints.authenticationManager(authenticationManager).tokenStore(tokenStore())      .accessTokenConverter(tokenEnhancer());   }   @Override   public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {      security.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");   }   @Override   public void configure(ClientDetailsServiceConfigurer clients) throws Exception {      clients.inMemory().withClient(clientid).secret(clientSecret).scopes("read", "write")         .authorizedGrantTypes("password", "refresh_token").accessTokenValiditySeconds(20000)         .refreshTokenValiditySeconds(20000);   }}

现在,使用openssl创建一个私钥和公钥.

您可以使用以下命令生成私钥.

openssl genrsa -out jwt.pem 2048openssl rsa -in jwt.pem

您可以使用For公钥生成使用以下命令.

openssl rsa -in jwt.pem -pubout

对于早于1.5版本的Spring Boot版本,添加以下属性在您的application.properties文件中定义OAuth2资源过滤器顺序.

security.oauth2.resource.filter-order = 3

YAML文件用户可以在YAML文件中添加以下属性.

security:   oauth2:      resource:         filter-order: 3

现在,在下创建schema.sql和data.sql文件类路径资源 src/main/resources/directory 将应用程序连接到H2数据库.

schema.sql文件如下所示 :

CREATE TABLE USERS (ID INT PRIMARY KEY, USERNAME VARCHAR(45), PASSWORD VARCHAR(60));

data.sql文件如下所示 :

INSERT INTO USERS (ID, USERNAME,PASSWORD) VALUES (   1, 'it1352@gmail.com','$2a$08$fL7u5xcvsZl78su29x1ti.dxI.9rYO8t0q5wk2ROJ.1cdR53bmaVG');INSERT INTO USERS (ID, USERNAME,PASSWORD) VALUES (   2, 'myemail@gmail.com','$2a$08$fL7u5xcvsZl78su29x1ti.dxI.9rYO8t0q5wk2ROJ.1cdR53bmaVG');

注意 : 密码应以数据库表中的Bcrypt Encoder格式存储.

您可以创建可执行的JAR文件,并使用以下Maven或Gradle命令运行Spring Boot应用程序.

对于Maven,您可以使用下面给出的命令 :

mvn clean install

在"BUILD SUCCESS"之后,您可以在目标目录下找到JAR文件.

对于Gradle,您可以使用命令如图所示 :

gradle clean build

"BUILD SUCCESSFUL"之后",你可以在build/libs目录下找到JAR文件.

现在,使用此处显示的命令运行JAR文件 :

java -jar 

应用程序在Tomcat端口8080上启动.

Tomcat端口8080应用程序输出

现在通过POSTMAN命中POST方法URL以获取OAUTH2令牌.

http ://localhost:8080/oauth/token

现在,添加请求标题如下 :

  • 授权 : 基本身份验证,包含您的客户ID和客户密码.

  • 内容类型 :  application/x-www-form-urlencoded

Add请求标题

现在,添加请求参数如下 :

  • grant_type = password

  • 用户名=您的用户名

  • 密码=您的密码

添加请求参数

现在,点击API并获取access_token,如图所示 :

获取访问令牌

现在,在请求标头中点击带有承载访问令牌的资源服务器API,如图所示.

带有承载访问令牌的资源服务器API

然后你可以看到输出如下图所示 :

OAuth2 with JWT Output