【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表结构,必须有用户名和密码,其他看自己需求,角色及权限看自己需求
    【springboot】OAuth2+SpringSecurity+Mysql——密码模式_第1张图片

添加依赖


        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-securityartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.security.oauthgroupId>
            <artifactId>spring-security-oauth2artifactId>
            <version>2.3.3.RELEASEversion>
        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
【springboot】OAuth2+SpringSecurity+Mysql——密码模式_第2张图片
Params设置:用户名(user表)、密码(user表)和授权模式(oauth_client_token表的authorized_grant_types,本文是password,密码模式)
【springboot】OAuth2+SpringSecurity+Mysql——密码模式_第3张图片
返回参数

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

2. 通过令牌访问资源
方法一:access_token可以拼接在url
【springboot】OAuth2+SpringSecurity+Mysql——密码模式_第4张图片
方法二:access_token也可以设置在header的authorization
【springboot】OAuth2+SpringSecurity+Mysql——密码模式_第5张图片

3. 校验令牌
本文设置为需要认证授权
【springboot】OAuth2+SpringSecurity+Mysql——密码模式_第6张图片
4. 更新令牌
【springboot】OAuth2+SpringSecurity+Mysql——密码模式_第7张图片

【springboot】OAuth2+SpringSecurity+Mysql——密码模式_第8张图片

测试成功!

你可能感兴趣的:(后端,数据库,oauth2,mysql,spring,boot)