SpringSecurity集成oauth2(jwt)

2023-05-16

版本

springboot版本:2.2.7.RELEASE
spring-security-oauth2版本:2.3.6.RELEASE

主要依赖

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <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.6.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-jwt</artifactId>
        <version>1.0.9.RELEASE</version>
    </dependency>

WebSecurity配置

package com.wisea.config.oauth;

import org.springframework.context.annotation.Bean;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@EnableWebSecurity
@Order(1)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Bean
    @ConditionalOnProperty(prefix = "web", value="cors", havingValue = "true")
    public CorsFilter corsFilter() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowCredentials(true);
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(urlBasedCorsConfigurationSource);
    }

    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 不定义没有password grant_type,密码模式需要AuthenticationManager支持
     *
     * @return
     * @throws Exception
     */
    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.requestMatchers().antMatchers("/oauth/**")
                .and()
                .authorizeRequests()
                //.antMatchers("/oauth/**").permitAll()
                .antMatchers("/oauth/**").authenticated()
                .and().httpBasic()
                .and().cors();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .passwordEncoder(passwordEncoder())
                .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("root")
                .and()
                .withUser("chinoukin").password(new BCryptPasswordEncoder().encode("123456")).roles("manager");
    }

}

authServer配置

package com.wisea.config.oauth;

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.core.annotation.Order;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
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.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;

import java.util.concurrent.TimeUnit;

@Configuration
@EnableAuthorizationServer
@Order(5)
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    @Qualifier("authenticationManagerBean")
    AuthenticationManager authenticationManager;

    @Autowired
    private TokenStore tokenStore;

    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(jwtAccessTokenConverter());
    }

    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("test-jwt.jks"), "test123".toCharArray());
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setKeyPair(keyStoreKeyFactory.getKeyPair("test-jwt"));
        return converter;
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("cli1")
                .authorizedGrantTypes("password")
                .secret(new BCryptPasswordEncoder().encode("123456"))
                //.redirectUris("http://baidu.com")
                .scopes("read")

                .and()
                .withClient("cli2")
                .authorizedGrantTypes("authorization_code")
                .secret(new BCryptPasswordEncoder().encode("123456"))
                .redirectUris("/auth_code")
                .scopes("read")
                .autoApprove(true)
                ;
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(tokenStore).tokenEnhancer(jwtAccessTokenConverter()).authenticationManager(authenticationManager);
        // 配置tokenServices参数
        DefaultTokenServices tokenServices = new DefaultTokenServices();
        tokenServices.setTokenStore(endpoints.getTokenStore());
        tokenServices.setSupportRefreshToken(false);
        tokenServices.setClientDetailsService(endpoints.getClientDetailsService());
        tokenServices.setTokenEnhancer(endpoints.getTokenEnhancer());
        tokenServices.setAccessTokenValiditySeconds((int) TimeUnit.DAYS.toSeconds(30)); // 30天
        endpoints.tokenServices(tokenServices);
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        // 允许表单认证
        security.allowFormAuthenticationForClients().tokenKeyAccess("permitAll()")
                .checkTokenAccess("isAuthenticated()");
    }
}

ResourceServer配置

package com.wisea.config.oauth;

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.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
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;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    @Bean
    @ConditionalOnProperty(prefix = "web", value="cors", havingValue = "true")
    public CorsFilter corsFilter() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowCredentials(true);
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(urlBasedCorsConfigurationSource);
    }

    @Autowired
    TokenStore tokenStore;


    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().exceptionHandling()
                .authenticationEntryPoint((request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED))
                .and().authorizeRequests()
                .antMatchers("/env").permitAll()
                .antMatchers("/env1").authenticated()
                .antMatchers("/env2").hasRole("manager")
                .and().cors();
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.tokenStore(tokenStore);
    }

    @Configuration
    public static class JwtConfig {

        public static final String public_cert = "public.cert";

        @Autowired
        private JwtAccessTokenConverter jwtAccessTokenConverter;

        @Bean
        @Qualifier("tokenStore")
        public TokenStore tokenStore() {
            return new JwtTokenStore(jwtAccessTokenConverter);
        }

        @Bean
        protected JwtAccessTokenConverter jwtAccessTokenConverter() {
            JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
            Resource resource = new ClassPathResource(public_cert);

            String publicKey;
            try {
                publicKey = new String(FileCopyUtils.copyToByteArray(resource.getInputStream()));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

            converter.setVerifierKey(publicKey);
            return converter;
        }
    }

}

其他

当ResourceServer和AuthServer为同一服务时,只需要如下配置即可

package com.wisea.config.oauth;

import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
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 javax.servlet.http.HttpServletResponse;

@Configuration
@EnableResourceServer
@Order(3)
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().exceptionHandling()
                .authenticationEntryPoint((request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED))
                .and()
                .requestMatchers().anyRequest()
                .and().authorizeRequests()
                .antMatchers("/env1").authenticated()
                .antMatchers("/env2").hasRole("manager")
                .and().cors();
    }
}

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

SpringSecurity集成oauth2(jwt) 的相关文章

随机推荐

  • 迭代器分类

    输入迭代器 读 xff0c 不能写 xff1b 只支持自增运算 istream iterator 61 61 61 43 43 gt 输出迭代器 写 xff0c 不能读 xff1b 只支持自增运算 ostream iterator 43 4
  • VC++中隐藏代码

    1 引言 在VS编辑器中可以对类中的方法 注释等内容进行隐藏 xff0c 单击左侧的 号即可完成隐藏 xff0c 隐藏后变为 43 xff0c 单击 43 号可以将隐藏的代码展开 2 隐藏任意代码 如果想在编辑器中隐藏任意代码段 xff0c
  • 常见签名算法之SHA256withRSA

    概述 在https blog csdn net chinoukin article details 100934995章节中 xff0c 我介绍了用Hmac算法用于签名算法中的方法 xff0c 本章节中将对常见的签名算法 SHA256wit
  • httpclient4封装类与HttpParser封装类

    httpclient4封装类与HttpParser封装类 最近工作中需要做一个爬虫去抓取指定页面的一些内容 xff0c 准备使用HttpParser来解析页面结构 xff0c 顺便看了一下httpclient4 xff0c 可以将它们配合使
  • 【Linux操作系统分析】进程——进程切换,进程的创建和撤销

    1 进程 进程是程序执行时的一个实例 xff0c 可以把它看作充分描述程序已经执行到何种程度的数据结构的汇集 从内核的观点看 xff0c 进程的目的是担当分配系统资源 xff08 CPU时间 xff0c 内存等 xff09 的实体 xff0
  • C++中的.和::和:和->的区别

    在学习C 43 43 的过程中我们经常会用到 和 和 xff1a 和 gt xff0c 在此整理一下这些常用符号的区别 1 A B则A为对象或者结构体 xff1b 2 A gt B则A为指针 xff0c gt 是成员提取 xff0c A g
  • 通过Curl 对url进行encode操作

    最近做项目的时候 xff0c 通过 Gflags Reload 时候 发现对于某些value中包含 61 中文等字符的支持不够好 xff0c value被截断了 经过分析后 xff0c 发现程序对url切分是用 61 amp 为标准的 xf
  • STM32进阶之串口环形缓冲区实现(转载)

    转载自微信公众号 玩转单片机 xff0c 感谢原作者 杰杰 队列的概念 在此之前 xff0c 我们来回顾一下队列的基本概念 xff1a 队列 Queue xff1a 是一种先进先出 First In First Out 简称 FIFO 的线
  • 位和结构体寄存器访问方法(转)

    1 2 1 传统 define 方法 1 2 外设位域结构体方法综述 DSP281x 头文件和外设示例使用位域结构体方法 xff0c 映射和访问基于F28x 外设寄存器 本节将介绍这种方法 xff0c 并把它和传统的 define 方法加以
  • 关于将函数写入头文件问题(分离式编译)

    如果某些函数在其他很多 cpp 文件中被调用 xff0c 那么为了避免写大量重复的代码以及让代码量更小一些 xff0c 我们可以将这些函数写头文件中 xff0c 然后其他 cpp 文件只需要引用该头文件然后就可以使用包含在头文件中的函数了
  • SpringSecurity配置跨域访问

    说明 java后端web服务有很多种方法可以实现跨域访问 xff0c 配置很简单 xff0c 今天这里我们用SpringSecurity的方式配置跨域访问 xff0c 配置方法如下 xff1a span class token keywor
  • 嵌入式C语言开发---存储器与寄存器

    概述 xff1a 讲述如何使用C语言来对底层寄存器进行封装 内容 xff1a 存储器映射寄存器与寄存器映射C语言访问寄存器 存储器映射 程序存储器 数据存储器 寄存器和I O 端口排列在同一个顺序的4 GB 地 址空间内 存储器映射 xff
  • httplib用法

    httplib的内容上是很多 xff0c 也比较简单 以下是一个非常简单的例子 xff0c 使用httplib获取google首页的html xff1a import httplib conn 61 httplib HTTPConnecti
  • HTTP认证之摘要认证——Digest(一)

    导航 HTTP认证之基本认证 Basic xff08 一 xff09 HTTP认证之基本认证 Basic xff08 二 xff09 HTTP认证之摘要认证 Digest xff08 一 xff09 HTTP认证之摘要认证 Digest x
  • Linux 文件名和路径的最大长度

    在x86 64 Linux下 xff0c 文件名的最大长度是255个字符 characters xff0c 文件路径的最大长度是4096字符 characters xff0c 即可以包含16级的最大文件长度的路径 在 lt limits h
  • Django之auth

    一 xff1a auth基础 xff08 1 xff09 作用 xff1a django提供给开发人员 对用户进行操作的模块的 例如 xff1a 登录 注册 认证 注销等等 xff08 2 xff09 使用方式 from django co
  • [JavaSE 源码分析] 关于HashMap的个人理解

    目录 HashMap是什么 HashMap的底层数据结构是什么 table容量为什么必须是二的倍数 table容量怎么做到二的倍数 Entry是怎样的结构 Node Entry在HashMap中的具体实现处理hash冲突的方法HashMap
  • HIS(LIS、PACS、RIS、EMR)系统简介

    HIS xff08 LIS PACS RIS EMR xff09 系统简介 HIS xff1a 医院信息系统 Hospital Information System HIS xff0c 利用电子计算机和通讯设备 xff0c 为医院所属各部
  • jackson使用问题:mapper.readValue()将JSON字符串转反序列化为对象失败或异常

    问题根源 xff1a 转化目标实体类的属性要与被转JSON字符串总的字段 一 一对应 xff01 字符串里可以少字段 xff0c 但绝对不能多字段 先附上我这段出现了问题的源码 xff1a 1 接收并转化相应的参数 需要在pom xml中引
  • SpringSecurity集成oauth2(jwt)

    版本 springboot版本 xff1a 2 2 7 RELEASE spring security oauth2版本 xff1a 2 3 6 RELEASE 主要依赖 span class token tag span class to