【springboot】OAuth2+SpringSecurity+Mysql——密码模式

理解oauth2

oauth2是一种授权协议,客户端必须得到用户的授权,才能获得令牌,再通过令牌去获取资源。
总共有四种模式:

  1. 授权码模式(authorization code)
  2. 简化模式(implicit)
  3. 密码模式(resource owner password credentials)
  4. 客户端模式(client credentials)

密码模式中,用户向客户端提供自己的用户名和密码。客户端使用这些信息,向"服务商提供商"索要授权:

  1. 用户向客户端提供用户名和密码。
  2. 客户端将用户名和密码发给认证服务器,向后者请求令牌。
  3. 认证服务器确认无误后,向客户端提供访问令牌。

Spring Security OAuth2

Spring Security OAuth2建立在Spring Security的基础之上,实现了OAuth2的规范
Spring OAuth2.0提供者实际上分为授权服务(Authorization Service)资源服务(Resource Service),两个服务可能存在同一个应用程序中,也可以在不同的应用中,还可以有多个资源服务,它们共享同一个中央授权服务。

详细理解可参考以下文章
阮一峰 – 理解 OAuth 2.0
一张图搞定OAuth2.0
Spring Security与OAuth2介绍

密码模式

数据库建表

oauth2相关表6张,密码模式主要涉及到三张表

  • oauth_access_token:访问令牌
  • oauth_approvals:授权记录
  • oauth_client_details:客户端信息
  • oauth_client_token:客户端用来记录token信息
  • oauth_code:授权码
  • oauth_refresh_token:更新令牌
DROP TABLE IF EXISTS `oauth_access_token`;CREATE TABLE `oauth_access_token` (  `token_id` varchar(255) DEFAULT NULL COMMENT '加密的access_token的值',  `token` longblob COMMENT 'OAuth2AccessToken.java对象序列化后的二进制数据',  `authentication_id` varchar(255) DEFAULT NULL COMMENT '加密过的username,client_id,scope',  `user_name` varchar(255) DEFAULT NULL COMMENT '登录的用户名',  `client_id` varchar(255) DEFAULT NULL COMMENT '客户端ID',  `authentication` longblob COMMENT 'OAuth2Authentication.java对象序列化后的二进制数据',  `refresh_token` varchar(255) DEFAULT NULL COMMENT '加密的refresh_token的值') ENGINE=InnoDB DEFAULT CHARSET=utf8;

DROP TABLE IF EXISTS `oauth_approvals`;CREATE TABLE `oauth_approvals` (  `userId` varchar(255) DEFAULT NULL COMMENT '登录的用户名',  `clientId` varchar(255) DEFAULT NULL COMMENT '客户端ID',  `scope` varchar(255) DEFAULT NULL COMMENT '申请的权限范围',  `status` varchar(10) DEFAULT NULL COMMENT '状态(Approve或Deny)',  `expiresAt` datetime DEFAULT NULL COMMENT '过期时间',  `lastModifiedAt` datetime DEFAULT NULL COMMENT '最终修改时间') ENGINE=InnoDB DEFAULT CHARSET=utf8;

DROP TABLE IF EXISTS `oauth_client_details`;CREATE TABLE `oauth_client_details` (  `client_id` varchar(255) NOT NULL COMMENT '客户端ID',  `resource_ids` varchar(255) DEFAULT NULL COMMENT '资源ID集合,多个资源时用逗号(,)分隔',  `client_secret` varchar(255) DEFAULT NULL COMMENT '客户端密匙',  `scope` varchar(255) DEFAULT NULL COMMENT '客户端申请的权限范围',  `authorized_grant_types` varchar(255) DEFAULT NULL COMMENT '客户端支持的grant_type',  `web_server_redirect_uri` varchar(255) DEFAULT NULL COMMENT '重定向URI',  `authorities` varchar(255) DEFAULT NULL COMMENT '客户端所拥有的Spring Security的权限值,多个用逗号(,)分隔',  `access_token_validity` int(11) DEFAULT NULL COMMENT '访问令牌有效时间值(单位:秒)',  `refresh_token_validity` int(11) DEFAULT NULL COMMENT '更新令牌有效时间值(单位:秒)',  `additional_information` varchar(255) DEFAULT NULL COMMENT '预留字段',  `autoapprove` varchar(255) DEFAULT NULL COMMENT '用户是否自动Approval操作') ENGINE=InnoDB DEFAULT CHARSET=utf8;

DROP TABLE IF EXISTS `oauth_client_token`;CREATE TABLE `oauth_client_token` (  `token_id` varchar(255) DEFAULT NULL COMMENT '加密的access_token值',  `token` longblob COMMENT 'OAuth2AccessToken.java对象序列化后的二进制数据',  `authentication_id` varchar(255) DEFAULT NULL COMMENT '加密过的username,client_id,scope',  `user_name` varchar(255) DEFAULT NULL COMMENT '登录的用户名',  `client_id` varchar(255) DEFAULT NULL COMMENT '客户端ID') ENGINE=InnoDB DEFAULT CHARSET=utf8;

DROP TABLE IF EXISTS `oauth_code`;CREATE TABLE `oauth_code` (  `code` varchar(255) DEFAULT NULL COMMENT '授权码(未加密)',  `authentication` varbinary(255) DEFAULT NULL COMMENT 'AuthorizationRequestHolder.java对象序列化后的二进制数据') ENGINE=InnoDB DEFAULT CHARSET=utf8;

DROP TABLE IF EXISTS `oauth_refresh_token`;CREATE TABLE `oauth_refresh_token` (  `token_id` varchar(255) DEFAULT NULL COMMENT '加密过的refresh_token的值',  `token` longblob COMMENT 'OAuth2RefreshToken.java对象序列化后的二进制数据 ',  `authentication` longblob COMMENT 'OAuth2Authentication.java对象序列化后的二进制数据') ENGINE=InnoDB DEFAULT CHARSET=utf8;

插入一条客户端信息
其中密码为user,数据库中存放的是加密后的

INSERT INTO oauth_client_details VALUES('user_client','project_api', '$2a$10$BurTWIy5NTF9GJJH4magz.9Bd4bBurWYG8tmXxeQh1vs7r/wnCFG2', 'read,write', 'password,refresh_token', '', '', 7200, 1800, NULL, 'true');

用户及权限相关表

  • user:用户表
  • role:角色表
  • permission:权限表
  • user_role
  • role_permission
    本文为测试只涉及role不涉及permission,下图是本文的user表结构,必须有用户名和密码,其他看自己需求,角色及权限看自己需求
    在这里插入图片描述

添加依赖

<!-- security-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>
            <version>2.3.3.RELEASE</version>
        </dependency>

Authorization Server - Spring Security配置

用于登录认证

package com.example.demo.config.oauth;

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.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @Description: security类 配置
 * @Author: Lorogy
 * @Date: 2021/1/22 9:56
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    /**
     * 自定义UserDetailsService用来从数据库中根据用户名查询用户信息以及角色信息
     */
    @Autowired
    public UserDetailsService userDetailsService;

    
    @Bean //防止服务器@Autowired authenticationManager无法注入
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService)
                .passwordEncoder(passwordEncoder());
    }

    /**
     * @Description: 密码编码验证器
     * @Param: []
     * @Return: org.springframework.security.crypto.password.PasswordEncoder
     */
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    /**
     * @Description: 验证配置,第一步认证,请求需走的过滤器链
     * @Param: [http]
     * @Return: void
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest()
                .authenticated()
                .and()
                .userDetailsService(userDetailsService);
    }
}

自定义UserDetailsService

package com.example.demo.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.model.TbRole;
import com.example.demo.model.TbUser;
import com.example.demo.model.TbUserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description:
 * @Author: Lorogy
 * @Date: 2021/1/22 10:53
 */
@Component
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private TbUserService userService;

    //重写认证的过程,由AuthenticationManager去调,从数据库中查找用户信息
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询用户是否存在
        TbUser tbUser = userService.findByName(username);
        if (tbUser == null) {
            throw new RuntimeException("username: " + username + " can not be found");
        }
        // 设置用户权限,可在数据库建表,通过用户查询到相应权限(角色),按以下方式加入
        List<GrantedAuthority> authorities = new ArrayList<>();
        
        List<Role> list = userService.getRoleById(tbUser.getId());
        for (int i = 0; i < list.size(); i++) {
            authorities.add(new SimpleGrantedAuthority(list.get(i).getRole()));
        }
        return new User(tbUser.getUsername(), tbUser.getPassword(), authorities);
    }
}

Authorization Server - 授权服务

用于授权,配置token

package com.example.demo.config.oauth;

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.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
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.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;

import javax.sql.DataSource;

/**
 * @Description: 授权服务器 配置
 * @Author: Lorogy
 * @Date: 2021/1/22 10:20
 */
@Configuration
@EnableAuthorizationServer //注解开启了验证服务器
public class OAuth2AuthServerConfig extends AuthorizationServerConfigurerAdapter {
    @Autowired
    public UserDetailsService userDetailsService;

    @Autowired
    private DataSource dataSource;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Bean
    public TokenStore tokenStore() {
        return new JdbcTokenStore(dataSource);
    }

    /**
     * @Description: 配置 token 节点的安全策略
     * @Param: [security]
     * @Return: void
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.tokenKeyAccess("permitAll()")
                .checkTokenAccess("isAuthenticated()");//默认"denyAll()",不允许访问/oauth/check_token;"isAuthenticated()"需要携带auth;"permitAll()"直接访问
    }

    /**
     * @Description: 配置客户端信息, 相当于在认证服务器中注册哪些客户端(包括资源服务器)能访问
     * @Param: [clients]
     * @Return: void
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.jdbc(dataSource); // 设置客户端的配置从数据库中读取,存储在oauth_client_details表
    }

    /**
     * @Description: 配置授权(authorization)以及令牌(token)的访问端点和令牌服务(token services)
     * @Param: [endpoints]
     * @Return: void
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager) // 开启密码验证
                .tokenStore(tokenStore()) // 设置tokenStore,生成token时会向数据库中保存
                .userDetailsService(userDetailsService);

    }
}

Resource Server - 资源服务器

用于设置资源访问权限

package com.example.demo.config.oauth;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;

/**
 * @Description: 资源服务器 配置
 * @Author: Lorogy
 * @Date: 2021/1/22 11:02
 */
@Configuration
@EnableResourceServer
public class OAuth2ResourceServerConfig extends ResourceServerConfigurerAdapter {
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.resourceId("project_api");//对应客户端resource_ids
    }

    /**
     * @Description: 设置资源访问权限需要重写该方法
     * @Param: [http]
     * @Return: void
     */
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/test/hello").permitAll()//不需要授权即可访问
                .antMatchers("/test/**").authenticated()//需要授权则可访问
                .antMatchers("/user").hasRole("ADMIN") //是ROLE_ADMIN权限可访问
                .antMatchers("/apis/**").hasRole("USER");//是ROLE_USER权限可访问
    }
}

测试

package com.example.demo.controller;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Description:
 * @Author: Lorogy
 * @Date: 2021/1/26 15:55
 */
@RestController
@RequestMapping(value = "/test")
public class TestController {
    @GetMapping("/hello")
    public String hello(){
        return "Hello";
    }

    @GetMapping("/meet")
    public String meet(){
        return "I meet you";
    }

    @GetMapping("/welcome")
    public String welcome(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return "Welcome " + authentication.getName();
    }

    @GetMapping("/project")
    @PreAuthorize("hasRole('ROLE_ADMIN')")  //具有此角色才可以访问
    public String project(){
        return "This is my project";
    }


}

默认提供的四个URL

  • /oauth/authorize : 授权AuthorizationEndpoint
  • /oauth/token : 令牌TokenEndpoint
  • /oauth/check_token : 令牌校验CheckTokenEndpoint
  • /oauth/confirm_access : 授权页面WhitelabelApprovalEndpoint
  • /oauth/error : 错误页面WhitelabelErrorEndpoint

1. 获取令牌:/oauth/token
Auth配置:客户端用户名和密码,即oauth_client_token表的client_idclient_secret,本文密码是user
在这里插入图片描述
Params设置:用户名(user表)、密码(user表)和授权模式(oauth_client_token表的authorized_grant_types,本文是password,密码模式)
在这里插入图片描述
返回参数

  • access_token:本地访问获取到的access_token,会自动写入到数据库中。
  • token_type:获取到的access_token的授权方式
  • refersh_token:刷新token时所用到的授权
  • tokenexpires_in:有效期(从获取开始计时,值秒后过期)
  • scope:客户端的接口操作权限(read:读,write:写)

2. 通过令牌访问资源
方法一:access_token可以拼接在url
在这里插入图片描述
方法二:access_token也可以设置在header的authorization
在这里插入图片描述

3. 校验令牌
本文设置为需要认证授权
在这里插入图片描述
4. 更新令牌
在这里插入图片描述

在这里插入图片描述

测试成功!

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
### 回答1: springcloud是一个开源的微服务框架,它基于Spring Boot,并提供了一整套解决方案,用于构建分布式系统中的各个微服务。通过使用springcloud,我们可以轻松实现服务注册与发现、负载均衡、断路器、配置中心等功能,简化了微服务开发和管理的复杂度。 springboot是一个基于Spring的轻量级开发框架,它通过开箱即用的原则,提供了一种快速构建应用程序的方式。使用springboot,我们可以简化繁琐的配置,只需少量的代码即可实现一个功能完整的应用程序,并且可以方便地和其他Spring生态的框架进行集成。 OAuth2是一种授权协议,用于保护Web应用程序、移动应用程序和API的资源。通过OAuth2协议,用户可以授权第三方应用程序访问他们的资源,而无需提供他们的密码。它提供了一种安全且可扩展的机制来处理用户身份验证和授权,并且被广泛应用于各种应用程序中。 Spring Security是一个Java框架,用于提供身份验证和访问控制的功能。它可以轻松地集成到Spring应用程序中,提供了一套强大的API和安全策略,用于保护应用程序免受各种攻击,包括身份验证和授权、会话管理、密码加密等。 Redis是一种内存数据存储系统,它以键值对的形式存储数据,并支持多种数据结构,如字符串、列表、集合、有序集合等。Redis具有高速、持久化和可扩展性等特点,可用于缓存、消息队列、分布式锁等各种场景。在使用Spring框架开发时,我们可以使用Redis作为缓存层,提高应用程序的性能和响应速度。 综上所述,Spring Cloud提供了构建和管理微服务的解决方案,Spring Boot简化了应用程序的开发,OAuth2和Spring Security提供了安全和授权的功能,而Redis作为内存数据存储系统,为应用程序提供了可扩展的缓存和数据存储能力。这些技术和框架相互协作,可以帮助开发者更快速、更安全地构建分布式系统。 ### 回答2: Spring Cloud是一个用于构建分布式系统的开发工具包,它提供了多个子项目来解决分布式系统的常见问题,例如服务注册与发现、配置管理、断路器、负载均衡等。Spring Boot是用于简化Spring应用程序开发的工具,它提供了一种自动配置的方式来快速搭建和运行Spring应用。OAuth2是一个开放标准,用于授权访问特定资源,它允许用户使用某个网站的授权信息来访问其他网站上的受保护资源。Spring Security是一个全面的身份验证和授权框架,它提供了一套安全服务,用于保护Web应用程序中的资源。Redis是一个高性能的键值存储系统,它常被用作缓存、队列、消息中间件等。 结合以上几个技术,可以构建一个基于Spring Cloud的分布式系统,使用Spring Boot快速搭建各个服务,使用Spring Security进行身份验证和授权管理。而OAuth2可以用于保护系统中的资源,通过认证服务器进行用户认证和授权,使得只有授权的用户才能访问相应的资源。Spring SecurityOAuth2可以集成使用,通过Spring Security提供的权限管理功能来管理不同角色对资源的访问权限。同时,将Redis作为缓存服务器,可用于提高系统的性能和响应速度。 总之,Spring Cloud、Spring BootOAuth2、Spring Security和Redis等技术可以在构建分布式系统时发挥重要作用,帮助我们快速搭建实现各个功能模块,并提供高性能和安全性。 ### 回答3: Spring Cloud是一套基于Spring Boot的微服务框架,它提供了在分布式系统中构建和管理各种微服务的解决方案。它具有服务注册与发现、负载均衡、熔断、服务网关等功能,可以方便地实现微服务架构。 Spring Boot是一个用于快速开发基于Spring框架的应用程序的工具,它简化了Spring应用程序的配置和部署流程。它提供了自动化配置、内嵌服务器、开箱即用的特性,使得我们只需要关注业务逻辑的开发而不用过多关注框架的配置。 OAuth2是一种开放标准的授权协议,它使得用户可以通过授权的方式将与用户相关的信息共享给第三方应用程序。它使用令牌的方式进行授权,具有安全性高、可扩展性好的优点,常用于实现单点登录和授权管理。 Spring Security是一个用于在Java应用程序中提供身份验证和访问控制的框架。它可以与Spring BootSpring Cloud集成,提供了认证、授权、密码加密等功能,帮助我们更好地保护应用程序的安全。 Redis是一种高性能的键值存储系统,它支持多种数据结构,如字符串、列表、哈希表等。它具有高并发读写、持久化、分布式等特点,常用于缓存、消息队列、会话管理等场景。 综上所述,Spring Cloud提供了构建微服务的解决方案,Spring Boot简化了Spring应用程序的开发,OAuth2实现了授权管理,Spring Security提供了身份验证和访问控制,而Redis则可以用于缓存和数据存储。这些技术的结合可以帮助我们构建安全、高效的分布式系统。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值