获取nacos配置中心文件值_Spring Cloud 使用 Nacos 做配置中心,读取多个配制文件的方式...

本文介绍如何在已有的Spring Security OAuth2 + JWT认证基础上,通过扩展自定义TokenGranter实现登录逻辑。主要涉及到Spring Security OAuth2的CompositeTokenGranter,以及配置Nacos作为配置中心获取文件值。
摘要由CSDN通过智能技术生成

本篇重点讨论如何实现自定义的登录方式,所以如何配制 spring-security-oauth2 就不说了.

一些说明之前已经配好使用 spring-security-oauth2 + JWT 的认证方式,这次仅是改造

本篇部分涉及的代码都是认证服务器的代码跟踪spring的登录逻辑发现,帐号密码的验证是在 tokenGranter 中完成的, 帐号密码对应的是 org.springframework.security.oauth2.provider.password.ResourceOwnerPasswordTokenGranter;

而spring找到对应的 tokenGranter 是通过登录时的一个表单参数"grant_type" 来找到的,这样的话,那我是不是可以通过扩展一个 TokenGranter 来达成我要的效果呢?spring 默认是同时支持多重 grant_type 的(根据客户端的配制决定特定客户端支持特定的 grant_type), 而AuthorizationServerConfigurerAdapter 的配制中 tokenGranter 又只能设置一个,那么spirng是怎么实现多个的呢?经过折腾我发现了一个 org.springframework.security.oauth2.provider.CompositeTokenGranter , 原来是通过它来实现的. 那么又有思路了.接下来研究如何向 CompositeTokenGranter  中增加我自定义的 TokenGranter , 结果发现spring在创建 CompositeTokenGranter 的时候已经把内置的 TokenGranter  写死了,没法通过它的机制扩展.唯一的方法就是我直接使用 CompositeTokenGranter . 那么我还是想要内置的 TokenGranter  也一起工作怎么办...?最后我无奈的选侧了把创建内置 TokenGranter  的代码copy了出来并修改了能用...不说了,直接上代码,有些需要注意的地方我会通过注释来描述.由于是已有项目的改造,所以怎么配制 spring-security-oauth2 + JWT ,怎么配制认证服务器和资源服务器,甚至oauth2 是什么?我就不多说了,网上一搜一大把.如果有同学实在需要的话,我再另开一篇来写吧import java.util.ArrayList;import java.util.Arrays;import java.util.HashMap;import java.util.List;import java.util.Map;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.Primary;import org.springframework.core.io.ClassPathResource;import org.springframework.http.HttpMethod;import org.springframework.security.authentication.AuthenticationManager;import org.springframework.security.core.authority.AuthorityUtils;import org.springframework.security.core.userdetails.UserDetailsService;import org.springframework.security.oauth2.common.OAuth2AccessToken;import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;import org.springframework.security.oauth2.provider.ClientDetails;import org.springframework.security.oauth2.provider.ClientDetailsService;import org.springframework.security.oauth2.provider.CompositeTokenGranter;import org.springframework.security.oauth2.provider.OAuth2RequestFactory;import org.springframework.security.oauth2.provider.TokenGranter;import org.springframework.security.oauth2.provider.TokenRequest;import org.springframework.security.oauth2.provider.client.BaseClientDetails;import org.springframework.security.oauth2.provider.client.ClientCredentialsTokenGranter;import org.springframework.security.oauth2.provider.client.InMemoryClientDetailsService;import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;import org.springframework.security.oauth2.provider.code.AuthorizationCodeTokenGranter;import org.springframework.security.oauth2.provider.code.InMemoryAuthorizationCodeServices;import org.springframework.security.oauth2.provider.implicit.ImplicitTokenGranter;import org.springframework.security.oauth2.provider.password.ResourceOwnerPasswordTokenGranter;import org.springframework.security.oauth2.provider.refresh.RefreshTokenGranter;import org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory;import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;import org.springframework.security.oauth2.provider.token.DefaultTokenServices;import org.springframework.security.oauth2.provider.token.TokenEnhancer;import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;import org.springframework.security.oauth2.provider.token.TokenStore;import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;/**

* @ClassName: OAuth2AuthorizationServerConfig

* @Description: spring-security OAuth2 配制,使用 jwt

*/@Configuration@EnableAuthorizationServerpublic class OAuth2AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {    @Autowired

private AuthenticationManager authenticationManager;

@Autowired

private UserDetailsService userDetailsService;  // 这是提供根据用户名查用户的方式给spring使用的

@Bean

/**

之前有个  public void configure(ClientDetailsServiceConfigurer clients) 配制客户端的方法,但是因为直接使

用 CompositeTokenGranter ,所以它不生效了,就在这里配制,同时使用这样的配制方式,后面可以改成从库里获取,自己实现一个 ClientDetailsService 就行

由于之前的 Builder方式只能在 ClientDetailsServiceConfigurer 中使用,所以这里暂时先这样了,后面我要改为从库里获取

*/

public ClientDetailsService clientDetailsService() {

BaseClientDetails result = new BaseClientDetails();

result.setClientId("weixin_client");

List authorizedGrantTypes = new ArrayList<>();

authorizedGrantTypes.add("password");

authorizedGrantTypes.add("refresh_token");

result.setAuthorizedGrantTypes(authorizedGrantTypes);  // 这个 client 支持的 grant_type

result.setClientSecret("$2a$10$9s0p62wfKh7WT64a/VYFpOAk19GsrHh5C7Ty9.wPRWX40cjq7Rmu."); // 这个密码是用  org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder 搞出来的,明文是 123456

List scopes = new ArrayList<>();

scopes.add("select");

result.setScope(scopes);

result.setAuthorities(AuthorityUtils.createAuthorityList("client"));

Map clientDetails = new HashMap();

clientDetails.put(result.getClientId(), result);

InMemoryClientDetailsService clientDetailsService = new InMemoryClientDetailsService();

clientDetailsService.setClientDetailsStore(clientDetails);    return clientDetailsService;

}    private AuthorizationCodeServices authorizationCodeServices() {      return new InMemoryAuthorizationCodeServices();  //使用默认

}    private OAuth2RequestFactory requestFactory() {      return new DefaultOAuth2RequestFactory(clientDetailsService());  //使用默认

}/**

这是从spring 的代码中 copy出来的,默认的几个 TokenGranter, 我们自定义的就加到这里就行了,目前我还没有加

*/

private List getDefaultTokenGranters() {

ClientDetailsService clientDetails = clientDetailsService();

AuthorizationServerTokenServices tokenServices = tokenServices();

AuthorizationCodeServices authorizationCodeServices = authorizationCodeServices();

OAuth2RequestFactory requestFactory = requestFactory();

List tokenGranters = new ArrayList();

tokenGranters.add(new AuthorizationCodeTokenGranter(tokenServices,

authorizationCodeServices, clientDetails, requestFactory));

tokenGranters.add(new RefreshTokenGranter(tokenServices, clientDetails, requestFactory));

ImplicitTokenGranter implicit = new ImplicitTokenGranter(tokenServices, clientDetails,

requestFactory);

tokenGranters.add(implicit);

tokenGranters.add(        new ClientCredentialsTokenGranter(tokenServices, clientDetails, requestFactory));    if (authenticationManager != null) {

tokenGranters.add(new ResourceOwnerPasswordTokenGranter(authenticationManager,

tokenServices, clientDetails, requestFactory));

}    return tokenGranters;

}/**

通过 tokenGranter 塞进去的就是它了

*/

private TokenGranter tokenGranter() {

TokenGranter tokenGranter = new TokenGranter() {        private CompositeTokenGranter delegate;        @Override

public OAuth2AccessToken grant(String grantType, TokenRequest tokenRequest) {        if (delegate == null) {

delegate = new CompositeTokenGranter(getDefaultTokenGranters());

}        return delegate.grant(grantType, tokenRequest);

}

};    return tokenGranter;

}

@Override

public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {

endpoints.tokenStore(tokenStore())//      .accessTokenConverter(accessTokenConverter())

.tokenGranter(tokenGranter())//      .tokenEnhancer(tokenEnhancerChain)  // 设了 tokenGranter 后该配制失效,需要在 tokenServices() 中设置

.authenticationManager(authenticationManager)

.userDetailsService(userDetailsService)  //refresh_token 需要配制它,否则会 UserDetailsService is required

.allowedTokenEndpointRequestMethods(HttpMethod.POST);

}

@Bean

public TokenEnhancer tokenEnhancer() {

TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();

tokenEnhancerChain.setTokenEnhancers(Arrays.asList(new CustomTokenEnhancer(), accessTokenConverter()));   // CustomTokenEnhancer 是我自定义一些数据放到token里用的

return tokenEnhancerChain;

}

@Override

public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {        //允许表单认证

oauthServer.allowFormAuthenticationForClients();//        .checkTokenAccess("permitAll()");  // 允许 check_token, 因为用了JWT,客户端可以验证签名,生产中可以不用

}

@Bean

public TokenStore tokenStore() {        return new JwtTokenStore(accessTokenConverter());

}    @Bean

public JwtAccessTokenConverter accessTokenConverter() {

JwtAccessTokenConverter converter = new JwtAccessTokenConverter();

KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("authorizationKey.jks"), "123456".toCharArray());

converter.setKeyPair(keyStoreKeyFactory.getKeyPair("klw"));    return converter;

}    @Bean

@Primary

public DefaultTokenServices tokenServices() {

DefaultTokenServices defaultTokenServices = new DefaultTokenServices();

defaultTokenServices.setTokenStore(tokenStore());

defaultTokenServices.setSupportRefreshToken(true);

defaultTokenServices.setTokenEnhancer(tokenEnhancer());   // 如果没有设置它,JWT就失效了.

return defaultTokenServices;

}

}

作者:邪影oO

链接:https://www.jianshu.com/p/99552e456311

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值