微服务之间的认证 --- 管理员令牌

本文介绍了在商城项目中,授权服务中心如何在不直接传递令牌的情况下,通过配置Spring Security允许无令牌访问特定资源。当更新配置后,使用Feign拦截器来携带管理员令牌,确保在需要认证时仍能正常访问微服务。文章详细展示了生成JWT管理员令牌的工具类和Feign拦截器的实现,实现了安全的微服务间通信。
摘要由CSDN通过智能技术生成

我们的商城项目中: auth-center 即 授权服务中心使用到了Security中的微服务

 

授权服务中心,没有将令牌交给 security微服务,为什么可以访问微服务呢?

由于在 security中,配置了访问/user的任何信息,都可以直接访问,permitAll,所以说不需要令牌认证

 

 

我们修改 配置

重启之后,测试

现在的授权中心微服务就访问不到 security服务,所以令牌无法颁发

 

接下来我们开始配置管理员令牌

 

第一步 创建出管理员令牌

package com.service.auth.serviceauth.Utils;

import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.jwt.crypto.sign.RsaSigner;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;
import java.io.IOException;
import java.security.KeyPair;
import java.security.interfaces.RSAPrivateKey;
import java.util.HashMap;
import java.util.Map;

/**
 * 产生管理员令牌的工具
 */
public class AdminToken {
    public static String adminToken() throws IOException {
        //证书⽂件
        String key_location = "shiyou.jks";
        //密钥库密码
        String keystore_password = "shiyou";
        //访问证书路径
        ClassPathResource resource = new ClassPathResource(key_location);
        //密钥⼯⼚
        KeyStoreKeyFactory keyStoreKeyFactory = new
                KeyStoreKeyFactory(resource, keystore_password.toCharArray());
        //密钥的密码,此密码和别名要匹配
        String keypassword = "shiyou";
        //密钥别名
        String alias = "shiyou";
        //密钥对(密钥和公钥)
        KeyPair keyPair = keyStoreKeyFactory.getKeyPair(alias,
                keypassword.toCharArray());
        //私钥
        RSAPrivateKey aPrivate = (RSAPrivateKey) keyPair.getPrivate();
        //定义payload信息
        Map<String, Object> tokenMap = new HashMap<String, Object>();
        tokenMap.put("user_name", "admin");
        tokenMap.put("client_id", "client");
        tokenMap.put("authorities", new String[] {"ROLE_ADMIN"});
        //⽣成jwt令牌
        Jwt jwt = JwtHelper.encode(new ObjectMapper().writeValueAsString(tokenMap),
                new RsaSigner(aPrivate));
        //取出jwt令牌
        String token = jwt.getEncoded();
        return token;
    }
}

 

第二步: 创建一个feign的拦截器 将令牌存入到Authorization中,这样在调用feign之前就能得到管理员令牌

拦截器的作用就是 :在调用feign之前执行

 

 

 

重启 auth-center之后,即使是在security的更改为需要认证才能访问,我们的feign拦截器已经携带了令牌的信息,所以说 就可以得到令牌了

 

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

你在狗叫什么、

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值