Spring Security oAuth2基于内存存储令牌实现

题记:本文基于千锋教育李卫民老师讲解的“SpringSecurity oAuth2基于内存存储令牌”,参见https://www.bilibili.com/video/BV1Kb411u7VP?p=9,因此,信服李老师提倡的“有道无术,术尚可求,有术无道 ,止于术”理念,信服其讲课的深入浅出。由于该课程未见配套源码,尝试按图索骥实现,如此,未尝不是另一种学习方式。特此录。

        Spring Security oAuth2原理参见https://www.bilibili.com/video/BV1Kb411u7VP?p=8,强烈建议初学者本着磨刀不误砍柴工之信念,看完该视频, 然后再进入本文学习,相信有事半而功倍之效。

        业务流程见下图:

 

        话不多说,上菜!

        配置文件application.yml

spring:
  application:
    name: oauth2_server

server:
  port: 8080

        springboot启动类

package com.example.springcloudstarteroauth2;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringCloudStarterOauth2Application {
    public static void main(String[] args) {
        SpringApplication.run(SpringCloudStarterOauth2Application.class, args);
    }
}
     

     认证及验证服务器配置AuthorizationServerConfig

package com.example.springcloudstarteroauth2.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
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;

/**
 * 认证及验证服务器配置
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    //加密工具类
    @Autowired
    private BCryptPasswordEncoder bcryptPasswordEncoder;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        //基于内存实现
        clients.inMemory()
                .withClient("client")//采用客户端名称client,相当于appId
                .secret(bcryptPasswordEncoder.encode("secret"))//采用加密串,此处采取对字符串secret进行加密,相当于appSecret
                .scopes("app")//作用域
                .redirectUris("http://blog.csdn.net/mzyp") //回调地址
                //.authorizedGrantTypes("password", "authorization_code", "client_credentials", "refresh_token");//分别对应四种授权类型,这里采用authorization_code
                .authorizedGrantTypes("authorization_code");
    }
}

        

WEB应用安全配置WebSecurityConfig

package com.example.springcloudstarteroauth2.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * WEB应用安全配置
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true, jsr250Enabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 加密工具类
     */
    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    /**
     * 采用基于内存方式验证验证配置
     * @param auth 验证管理器生成器
     * @throws Exception 异常
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("admin").password(passwordEncoder().encode("123456")).roles("ADMIN")
                .and()
                .withUser("user").password(passwordEncoder().encode("123456")).roles("USER");
    }

}

        测试与验证

        浏览器输入http://localhost:8080/oauth/authorize?client_id=client&response_type=code自动切换通用登录界面http://localhost:8080/login:

 在该登录界面分别对应输入用户名admin,密码123456,即上述WebSecurityConfig类对应的配置信息。

选中Approve选项,点击【Authorize】按钮并回车,进入回调地址指向界面

 注意红色箭头所指是返回的授权码,记下该授权码备用。

采用Postman测试获得access_token,见下图:

获得该access_token后再访问对应资源服务器即可完成对应的资源数据提取。

全部源码参见https://gitee.com/mzyp/spring-security-oauth2

收工。

      

        

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot Security OAuth2是基于Spring SecurityOAuth2的框架,用于实现授权服务器和资源服务器。JWT令牌是一个基于JSON的开放标准,用于在各方之间安全地传输信息。 在Spring Boot Security OAuth2中实现支持JWT令牌的授权服务器,可以按照以下步骤进行: 1. 添加依赖:在项目的pom.xml文件中添加Spring Security OAuth2和JWT的相关依赖。 2. 配置授权服务器:在Spring Boot应用程序的配置文件中,配置授权服务器的基本设置,包括端点URL、客户端信息、用户认证信息等。 3. 配置JWT令牌:配置JWT令牌的签名密钥和过期时间等信息。可以使用开源库如jjwt来生成和验证JWT令牌。 4. 创建自定义的认证提供程序:实现自定义的认证提供程序来支持JWT令牌的认证机制。在认证提供程序中,可以使用JWT令牌解析并验证请求中的令牌信息。 5. 创建自定义的用户详细信息服务:实现自定义的用户详细信息服务,用于从数据库或其他存储中获取用户的详细信息。在用户详细信息服务中,可以根据JWT令牌中的信息获取用户信息。 6. 配置授权服务器的访问规则:配置授权服务器的访问规则,包括允许或禁止特定角色或权限的访问。 7. 测试访问授权服务器:使用客户端应用程序发送请求到授权服务器的端点,获取JWT令牌并验证其有效性。 通过以上步骤,可以实现一个支持JWT令牌的授权服务器。该服务器可以提供为客户端应用程序颁发和验证JWT令牌的功能,以实现安全并可靠的用户认证和授权控制。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值