oauth2+JWT实现oauth2服务

介绍

在这一章节中。 https://blog.csdn.net/baidu_34389984/article/details/85249733 实现了简单的oauth2服务。返回的token是oauth2自生成的token。但有时候,我们希望能在token中加些参数,这时候我们可以用jwt生成token。关于什么是jwt的概念,笔者给出一份资料。https://baijiahao.baidu.com/s?id=1608021814182894637&wfr=spider&for=pc

实现功能

结合jwt+oauth2。返回基于jwt的token。

开发步骤
引用jar包

jar不用引入。oauth2包自导有jwt包。

认证服务器

在之前的认证服务器MyAuthorizationServerConfig类上,添加jwt的配置,并且在jwt中添加用户主键uin。配置如下:

    /**
     * 定义jwt的生成方式
     *
     * @return JwtAccessTokenConverter
     */
    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter() {
            @Override
            public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
                final Map<String, Object> additionalInformation = new HashMap<>();
                UserModel userModel = (UserModel) authentication.getUserAuthentication().getPrincipal();
                //把用户的主键uin放进去
                additionalInformation.put("uin", userModel.getUin());
                ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInformation);
                return super.enhance(accessToken, authentication);
            }
        };
        //非对称加密,但jwt长度过长
//        KeyPair keyPair = new KeyStoreKeyFactory(new ClassPathResource("kevin_key.jks"), "123456".toCharArray())
//                .getKeyPair("kevin_key");
//        converter.setKeyPair(keyPair);
//        return converter;
        //对称加密
        converter.setSigningKey("123");
        return converter;
    }
    
        /**
     * 定义授权和令牌端点以及令牌服务
     *
     * @param endpoints defines the authorization and token endpoints and the token services.
     * @throws Exception exception
     */
    @Override
    public void configure(final AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                //指定认证管理器
                .authenticationManager(authenticationManager)
                //用户账号密码认证
                .userDetailsService(userDetailsService)
                // refresh_token
                .reuseRefreshTokens(false)
                //指定token存储位置
                .tokenStore(tokenStore())
                // 配置JwtAccessToken转换器
                .accessTokenConverter(accessTokenConverter());
    }

首先就是定义JWT的生成方式。然后在endpoints上添加自己的JwtAccessToken转换器。

测试

关于如何访问,请参照上一章节的测试。这里直接给出得到token的结果:

在这里插入图片描述

把拿到的jwt放到网站上解除来如下:

在这里插入图片描述

项目源码

https://gitee.com/lvhaibao/spring-lhbauth/tree/13b4e27357411de0c8a81ba1397f87e1a32919c7/

  • 6
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值