java权限统一认证中心_微服务权限终极解决方案,SpringCloudGateway+O。。。

更新时间:2023-06-25 17:49:48 阅读: 评论:0

java权限统⼀认证中⼼_微服务权限终极解决⽅
案,SpringCloudGateway+O。。。
SpringBoot实战电商项⽬mall(35k+star)地址:/macrozheng/…
摘要
最近发现了⼀个很好的微服务权限解决⽅案,可以通过认证服务进⾏统⼀认证,然后通过⽹关来统⼀校验认证和鉴权。此⽅案为⽬前最新⽅案,仅⽀持Spring Boot 2.2.0、Spring Cloud Hoxton 以上版本,本⽂将详细介绍该⽅案的实现,希望对⼤家有所帮助!
前置知识
我们将采⽤Nacos作为注册中⼼,Gateway作为⽹关,使⽤nimbus-jo-jwtJWT库操作JWT令牌,对这些技术不了解的朋友可以看下下⾯的⽂章。
应⽤架构
我们理想的解决⽅案应该是这样的,认证服务负责认证,⽹关负责校验认证和鉴权,其他API服务负责处
理⾃⼰的业务逻辑。安全相关的逻辑只存在于认证服务和⽹关服务中,其他服务只是单纯地提供服务⽽没有任何安全相关逻辑。
相关服务划分:
micro-oauth2-gateway:⽹关服务,负责请求转发和鉴权功能,整合Spring Security+Oauth2;
micro-oauth2-auth:Oauth2认证服务,负责对登录⽤户进⾏认证,整合Spring Security+Oauth2;
micro-oauth2-api:受保护的API服务,⽤户鉴权通过后可以访问该服务,不整合Spring Security+Oauth2。
⽅案实现
下⾯介绍下这套解决⽅案的具体实现,依次搭建认证服务、⽹关服务和API服务。
micro-oauth2-auth
我们⾸先来搭建认证服务,它将作为Oauth2的认证服务使⽤,并且⽹关服务的鉴权功能也需要依赖它。
在l中添加相关依赖,主要是Spring Security、Oauth2、JWT、Redis相关依赖;
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-curity
org.springframework.cloud
spring-cloud-starter-oauth2
com.nimbusds
nimbus-jo-jwt
8.16
org.springframework.boot
spring-boot-starter-data-redis
在l中添加相关配置,主要是Nacos和Redis相关配置;
rver:
port: 9401
spring:
profiles:
active: dev
application:
name: micro-oauth2-auth
cloud:
nacos:
discovery:
rver-addr: localhost:8848
jackson:
date-format: yyyy-MM-dd HH:mm:ss
redis:
databa: 0
port: 6379
host: localhost
password:
management:
endpoints:
web:
exposure:
include: "*"
使⽤keytool⽣成RSA证书jwt.jks,复制到resource⽬录下,在JDK的bin⽬录下使⽤如下命令即可;keytool -genkey -alias jwt -keyalg RSA -keystore jwt.jks
创建UrServiceImpl类实现Spring Security的UrDetailsService接⼝,⽤于加载⽤户信息;
/**
* ⽤户管理业务类
盘门三景* Created by macro on 2020/6/19.
*/
@Service
public class UrServiceImpl implements UrDetailsService{
龙的五行属性private List urList;
@Autowired
private PasswordEncoder passwordEncoder;
@PostConstruct
public void initData(){
String password = de("123456");
urList = new ArrayList<>();
urList.add(new UrDTO(1L,"macro", password,1, List("ADMIN")));
urList.add(new UrDTO(2L,"andy", password,1, List("TEST")));
}
@Override
public UrDetails loadUrByUrname(String urname) throws UrnameNotFoundException{
List findUrList = urList.stream().filter(item -> Urname().equals(urname)).List()); if (CollUtil.isEmpty(findUrList)) {
throw new UrnameNotFoundException(MessageConstant.USERNAME_PASSWORD_ERROR);
}
SecurityUr curityUr = new (0));
离婚起诉书范本if (!curityUr.isEnabled()) {
throw new DisabledException(MessageConstant.ACCOUNT_DISABLED);
} el if (!curityUr.isAccountNonLocked()) {
throw new LockedException(MessageConstant.ACCOUNT_LOCKED);
} el if (!curityUr.isAccountNonExpired()) {
throw new AccountExpiredException(MessageConstant.ACCOUNT_EXPIRED);
} el if (!curityUr.isCredentialsNonExpired()) {
throw new CredentialsExpiredException(MessageConstant.CREDENTIALS_EXPIRED);
}
return curityUr;
}
主题展开}
添加认证服务相关配置Oauth2ServerConfig,需要配置加载⽤户信息的服务UrServiceImpl及RSA的钥匙对KeyPair;
/**
* 认证服务器配置
* Created by macro on 2020/6/19.
*/
@AllArgsConstructor
@Configuration
@EnableAuthorizationServer
中医治疗肝public class Oauth2ServerConfig extends AuthorizationServerConfigurerAdapter{
private final PasswordEncoder passwordEncoder;
private final UrServiceImpl urDetailsService;
private final AuthenticationManager authenticationManager;
private final JwtTokenEnhancer jwtTokenEnhancer;
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception{
clients.inMemory()
.withClient("client-app")
.de("123456"))
.scopes("all")
.authorizedGrantTypes("password", "refresh_token")
.accessTokenValiditySeconds(3600)
.refreshTokenValiditySeconds(86400);
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception{ TokenEnhancerChain enhancerChain = new TokenEnhancerChain();
List delegates = new ArrayList<>();
delegates.add(jwtTokenEnhancer);
delegates.add(accessTokenConverter());
enhancerChain.tTokenEnhancers(delegates); //配置JWT的内容增强器
endpoints.authenticationManager(authenticationManager)
包菜做法.urDetailsService(urDetailsService) //配置加载⽤户信息的服务
.accessTokenConverter(accessTokenConverter())
.tokenEnhancer(enhancerChain);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer curity) throws Exception{ curity.allowFormAuthenticationForClients();
}
@Bean
public JwtAccessTokenConverter accessTokenConverter(){小隐静脉曲张
JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
jwtAccessTokenConverter.tKeyPair(keyPair());
return jwtAccessTokenConverter;
}
@Bean
public KeyPair keyPair(){
//从classpath下的证书中获取秘钥对
KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("jwt.jks"), "123456".toCharArray());
KeyPair("jwt", "123456".toCharArray());
}
}
如果你想往JWT中添加⾃定义信息的话,⽐如说登录⽤户的ID,可以⾃⼰实现TokenEnhancer接⼝;
/**
* JWT内容增强器
* Created by macro on 2020/6/19.
*/
@Component
public class JwtTokenEnhancer implements TokenEnhancer{
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication){
SecurityUr curityUr = (SecurityUr) Principal();
Map info = new HashMap<>();
//把⽤户ID设置到JWT中
贡献近义词
info.put("id", Id());
((DefaultOAuth2AccessToken) accessToken).tAdditionalInformation(info);
return accessToken;
}
}
由于我们的⽹关服务需要RSA的公钥来验证签名是否合法,所以认证服务需要有个接⼝把公钥暴露出来;
/**
* 获取RSA公钥接⼝
* Created by macro on 2020/6/19.
*/
@RestController

本文发布于:2023-06-25 17:49:48,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/fan/89/1054590.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:服务   认证   相关   配置
相关文章
留言与评论(共有 0 条评论)
   
验证码:
推荐文章
排行榜
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图