单点登录失败解决措施 单点登录框架有哪些( 三 )


颁发登陆成功令牌构建令牌配置对象本次我们借助JWT(Json Web Token-是一种json格式)方式将用户相关信息进行组织和加密,并作为响应令牌(Token),从服务端响应到客户端,客户端接收到这个JWT令牌之后,将其保存在客户端(例如localStorage),然后携带令牌访问资源服务器,资源服务器获取并解析令牌的合法性,基于解析结果判定是否允许用户访问资源.
package com.jt.auth.config;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;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;@Configurationpublic class TokenConfig {//定义签名key,在执行令牌签名需要这个key,可以自己指定.private String SIGNING_KEY = "auth";//定义令牌生成策略.@Beanpublic TokenStore tokenStore() {return new JwtTokenStore(jwtAccessTokenConverter());}//定义Jwt转换器,负责生成jwt令牌,解析令牌内容@Beanpublic JwtAccessTokenConverter jwtAccessTokenConverter(){JwtAccessTokenConverter converter=new JwtAccessTokenConverter();//设置加密/解密口令converter.setSigningKey(SIGNING_KEY);return converter;}}定义认证授权核心配置第一步:在SecurityConfig中添加如下方法(创建认证管理器对象,后面授权服务器会用到):
@Beanpublic AuthenticationManager authenticationManagerBean()throws Exception {return super.authenticationManagerBean();}第二步:所有零件准备好了开始拼装最后的主体部分,这个主体部分就是授权服务器的核心配置
package com.jt.auth.config;import lombok.AllArgsConstructor;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.http.HttpMethod;import org.springframework.security.authentication.AuthenticationManager;import org.springframework.security.core.userdetails.UserDetailsService;import org.springframework.security.crypto.password.PasswordEncoder;import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;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.token.AuthorizationServerTokenServices;import org.springframework.security.oauth2.provider.token.DefaultTokenServices;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 java.util.Arrays;/** * 完成所有配置的组装,在这个配置类中完成认证授权,JWT令牌签发等配置操作 * 1)SpringSecurity (安全认证和授权) * 2)TokenConfig * 3)Oauth2(暂时不说) */@AllArgsConstructor@Configuration@EnableAuthorizationServer //开启认证和授权服务public class Oauth2Config extends AuthorizationServerConfigurerAdapter {//此对象负责完成认证管理private AuthenticationManager authenticationManager;//TokenStore负责完成令牌创建,信息读取private TokenStore tokenStore;//JWT令牌转换器(基于用户信息构建令牌,解析令牌)private JwtAccessTokenConverter jwtAccessTokenConverter;//密码加密匹配器对象private PasswordEncoder passwordEncoder;//负责获取用户信息信息private UserDetailsService userDetailsService;//设置认证端点的配置(/oauth/token),客户端通过这个路径获取JWT令牌@Overridepublic void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {endpoints//配置认证管理器.authenticationManager(authenticationManager)//验证用户的方法获得用户详情.userDetailsService(userDetailsService)//要求提交认证使用post请求方式,提高安全性.allowedTokenEndpointRequestMethods(HttpMethod.POST,HttpMethod.GET)//要配置令牌的生成,由于令牌生成比较复杂,下面有方法实现.tokenServices(tokenService());//这个不配置,默认令牌为UUID.randomUUID().toString()}//定义令牌生成策略@Beanpublic AuthorizationServerTokenServices tokenService(){//这个方法的目标就是获得一个令牌生成器DefaultTokenServices services=new DefaultTokenServices();//支持令牌刷新策略(令牌有过期时间)services.setSupportRefreshToken(true);//设置令牌生成策略(tokenStore在TokenConfig配置了,本次我们应用JWT-定义了一种令牌格式)services.setTokenStore(tokenStore);//设置令牌增强(允许设置令牌生成策略,默认是非jwt方式,现在设置为jwt方式,并在令牌Payload部分允许添加扩展数据,例如用户权限信息)TokenEnhancerChain chain=new TokenEnhancerChain();chain.setTokenEnhancers(Arrays.asList(jwtAccessTokenConverter));services.setTokenEnhancer(chain);//设置令牌有效期services.setAccessTokenValiditySeconds(3600);//1小时//刷新令牌应用场景:一般在用户登录系统后,令牌快过期时,系统自动帮助用户刷新令牌,提高用户的体验感services.setRefreshTokenValiditySeconds(3600*72);//3天return services;}//设置客户端详情类似于用户详情@Overridepublic void configure(ClientDetailsServiceConfigurer clients) throws Exception {clients.inMemory()//客户端id (客户端访问时需要这个id).withClient("gateway-client")//客户端秘钥(客户端访问时需要携带这个密钥).secret(passwordEncoder.encode("123456"))//设置权限.scopes("all")//all只是个名字而已和写abc效果相同//允许客户端进行的操作这里的认证方式表示密码方式,里面的字符串千万不能写错.authorizedGrantTypes("password","refresh_token");}// 认证成功后的安全约束配置,对指定资源的访问放行,我们登录时需要访问/oauth/token,需要对这样的url进行放行@Overridepublic void configure(AuthorizationServerSecurityConfigurer security) throws Exception {//认证通过后,允许客户端进行哪些操作security//公开oauth/token_key端点.tokenKeyAccess("permitAll()")//公开oauth/check_token端点.checkTokenAccess("permitAll()")//允许提交请求进行认证(申请令牌).allowFormAuthenticationForClients();}}配置网关认证的URL- id: router02uri: lb://sca-authpredicates:#- Path=/auth/login/**#没要令牌之前,以前是这样配置- Path=/auth/oauth/**#微服务架构下,需要令牌,现在要这样配置filters:- StripPrefix=1Postman访问测试第一步:启动服务依次启动sca-auth服务,sca-resource-gateway服务 。


以上关于本文的内容,仅作参考!温馨提示:如遇健康、疾病相关的问题,请您及时就医或请专业人士给予相关指导!

「四川龙网」www.sichuanlong.com小编还为您精选了以下内容,希望对您有所帮助: