我们的商城项目中: 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拦截器已经携带了令牌的信息,所以说 就可以得到令牌了