当前位置:首页 > CN2资讯 > 正文内容

chatgpt 服务器 windows

9小时前CN2资讯


Zuul配置OAuth资源服务器
1.分析
我们都知道Zuul是网关,所有的请求都要经过这里,再到指定的资源服务器,但是经过Zuul之后,你携带的token Zuul是不会携带着去访问 指定的资源服务器的,所以会造成一个你携带了token但是还是显示你没有认证
接下来我将展示我的代码,并解释其中的原理
2.
ResourceServerConfig.java
因为所有请求都要经过网关Zuul,所以这里OAuth配置要配置所有的资源服务器以及认证服务器的资源配置,和安全配置
@Configuration public class ResourceServerConfig { @Autowired private TokenStore tokenStore; @Autowired private AuthExceptionEntryPoint authExceptionEntryPoint; //认证服务器的配置 @Configuration @EnableResourceServer public class AuthorizationServer extends ResourceServerConfigurerAdapter{ public String RESOURCE_ID = "zuul"; //资源服务安全配置 @Override public void configure(ResourceServerSecurityConfigurer resources) throws Exception { resources .tokenStore(tokenStore)//令牌存储验证服务,让资源服务自己验证token .resourceId(RESOURCE_ID)//资源ID .stateless(true);//会话机制stateless开启 } @Override public void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/uaa/**") .permitAll(); } } //emplyee资源服务器的配置 @Configuration @EnableResourceServer public class ResourceServer extends ResourceServerConfigurerAdapter{ public String RESOURCE_ID = "employee"; //资源服务安全配置 @Override public void configure(ResourceServerSecurityConfigurer resources) throws Exception { resources .tokenStore(tokenStore)//令牌存储验证服务,让资源服务自己验证token .resourceId(RESOURCE_ID)//资源ID .authenticationEntryPoint(authExceptionEntryPoint)//配置token异常的处理 .stateless(true);//会话机制stateless开启 } @Override public void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/employee/**").authenticated(); } } /** * ......到时加其他资源服务器 再配置 */ }
AuthFilter.java
当请求携带token经过认证 并放入认证对象中,经过此过滤器,把认证对象的信息明文放入转发给资源服务器请求的请求头中
public class AuthFilter extends ZuulFilter { //filter类型 随便写但是要有意义的 @Override public String filterType() { return "pre"; } //数值越小 越优先 @Override public int filterOrder() { return 0; } //是否过滤 @Override public boolean shouldFilter() { return true; } @Override public Object run() throws ZuulException { RequestContext context = RequestContext.getCurrentContext(); Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); //如果不是 OAuth2Authentication 认证对象 则返回null if(!(authentication instanceof OAuth2Authentication)){ return null; } OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) authentication; Authentication userAuthentication = oAuth2Authentication.getUserAuthentication(); //取出用户名 String principal = userAuthentication.getName(); /** * 组装明文token,转发给微服务,放入header,名称为json-token */ final List<String> authorities = new ArrayList<>(); userAuthentication.getAuthorities().stream().forEach(s -> authorities.add(((GrantedAuthority)s).getAuthority())); OAuth2Request oAuth2Request = oAuth2Authentication.getOAuth2Request(); Map<String, String> requestParameters = oAuth2Request.getRequestParameters(); Map<String, Object> jsonToken = new HashMap<>(requestParameters); if (userAuthentication != null) { jsonToken.put("principal",principal); jsonToken.put("authroities",authorities); } try { String jsonStrToken = new ObjectMapper().writeValueAsString(jsonToken); context.addZuulRequestHeader("json-token", Base64.getEncoder().encodeToString(jsonStrToken.getBytes())); } catch (IOException e) { e.printStackTrace(); } return null; } }
ZuulConfig.java
因为所有请求都要经过网关Zuul,在这里配置支持跨域请求的配置以及,配置上面的过滤器
@Configuration public class ZuulConfig { @Bean public AuthFilter authFilter(){ return new AuthFilter(); } //支持跨域请求配置 @Bean public FilterRegistrationBean filterRegistrationBean(){ final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); final CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.setAllowCredentials(true); corsConfiguration.addAllowedOrigin("*"); corsConfiguration.addAllowedHeader("*"); corsConfiguration.addAllowedMethod("*"); source.registerCorsConfiguration("/**",corsConfiguration); CorsFilter corsFilter = new CorsFilter(source); FilterRegistrationBean<Filter> filterFilterRegistrationBean = new FilterRegistrationBean<>(corsFilter); filterFilterRegistrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE); return filterFilterRegistrationBean; } }
WebSecurityConfig.java
这里将放行所有请求,把认证的功能交由资源服务器的认证
@Configuration public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/**").permitAll() .and() .csrf().disable() .cors().disable(); } }
TokenStoreConfig.java
配置token存储策略和token转换器,以便Zuul将请求头中的token解析出来放入认证对象中
@Configuration public class TokenStoreConfig { private String SIGNING_KEY = "lzj"; @Bean public TokenStore tokenStore(){ //JWT令牌存储方案 return new JwtTokenStore(accessTokenConverter()); } @Bean public JwtAccessTokenConverter accessTokenConverter(){ JwtAccessTokenConverter converter = new JwtAccessTokenConverter(); converter.setSigningKey(SIGNING_KEY); return converter; } }
application.yml
添加以下配置信息到配置文件中
#配置下zuul的超时时间,因zuul启用了ribbon的负载均衡,还需要设置ribbon的超时时间,注意ribbon的超时时间要小于zuul超时时间 。 zuul: host: connect-timeout-millis: 15000 #HTTP连接超时要比Hystrix的大 socket-timeout-millis: 60000 #socket超时 #忽略框架默认的服务映射路径 ignored-services: '*' #不忽略任何头部信息,所有header都转发到下游的资源服务器 sensitive-headers: '*' retryable: true #zuul的重试机制开启 需要spring-retry依赖 add-host-header: true #加上主机头信息 routes: oauth-server: serviceId: oauth-server path: /uaa/** employee: serviceId: employee path: /employee/** ribbon: ReadTimeout: 10000 ConnectTimeout: 10000
可以看到我的配置文件配置了retryable 重试机制,这需要引入一个依赖
<dependency> <groupId>org.springframework.retry</groupId> <artifactId>spring-retry</artifactId> </dependency>
如果没有配置重新机制,在如果Zuul访问的资源服务器宕机,他不会触发Hystrix,而是返回错误页面,这不是我们想看到的,这时候你配置了重试机制,他就会重新连接一次,连接失败换其他的资源服务。
到此你还需要到资源服务器配置一个过滤器
这个过滤器的作用是,第一个过滤请求,把请求中请求头的明文认证信息放入到认证对象中,以完成资源服务器的认证
TokenAuthenticationFilter.java
public class TokenAuthenticationFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException { String token = httpServletRequest.getHeader("json-token"); if(token != null){ String jsonStrToken = Base64.getDecoder().decode(token).toString(); Map map = new ObjectMapper().readValue(jsonStrToken, Map.class); //用户名 String principal = (String) map.get("principal"); //用户权限 List<String> authroities = (List<String>) map.get("authroities"); String[] authroitiesArray = authroities.toArray(new String[authroities.size()]); //创建authenticationtoken对象 UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(principal, null, AuthorityUtils.createAuthorityList(authroitiesArray)); usernamePasswordAuthenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest)); //将对象填充到安全上下文中 SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken); } //放行过滤器 filterChain.doFilter(httpServletRequest, httpServletResponse); } }
大功告成!!!!
测试






 

    你可能想看:

    扫描二维码推送至手机访问。

    版权声明:本文由皇冠云发布,如需转载请注明出处。

    本文链接:https://www.idchg.com/info/29843.html

    分享给朋友:

    “chatgpt 服务器 windows” 的相关文章

    ZGOVPS高性能VPS主机:提升网站速度与跨境访问体验的最佳选择

    ZGOVPS的背景与市场定位 ZGOVPS是一家专注于提供高性能VPS主机服务的商家,凭借其出色的性价比和良好的用户口碑,迅速在站长圈中站稳了脚跟。它的市场定位非常明确,主要服务于那些对网络性能有较高要求的用户,尤其是需要跨境访问的网站。对于国内用户来说,访问国外机房时常常会遇到线路问题,导致访问速...

    如何通过命令行安装DSM软件:步骤与技巧教学

    什么是DSM? DSM,即DiskStation Manager,是为Synology NAS设备设计的一款操作系统。它不仅提供了存储管理的基本功能,还有很多高级应用,像文件共享、备份解决方案以及多媒体服务等。可以说,DSM就像一种灵活的操作平台,让用户能够通过直观的界面轻松管理他们的数据和设备。...

    选择Lisahost VPS服务,提升您海外电商、游戏和流媒体体验

    Lisahost 是一家于 2020 年 1 月成立的 VPS(虚拟专用服务器)提供商,专注于为全球用户提供高质量的云服务。我发现它的目标市场覆盖了包括香港、台湾、韩国、日本、新加坡、美国和英国等多个地区。作为一家新兴企业,lisahost 用创新的服务模式和多样化的产品,为需要高效网络及流畅访问的...

    DMIT测试IP详解及VPS选择指南

    DMIT VPS服务概述 我对DMIT的了解始于他们在2017年的成立,作为一家海外VPS厂商,他们在市场上取得了显著的地位。DMIT提供的VPS服务覆盖多个地区,如中国香港、美国洛杉矶和日本东京。这些服务以对国内用户友好的优化路线而受到好评,尤其是CN2 GIA和CMIN2线路,这些线路减少了延迟...

    选择野草云主机服务,享受高性价比与优质体验

    野草云是一家在2016年成立的主机服务提供商,由国人运营,专注于为中国大陆地区的用户提供优质的服务和产品。作为一家相对年轻的主机商,野草云力求用更贴近用户的方式来满足客户需求,特别是在国内市场需求快速增长的背景下,它的出现让很多用户找到了合适的主机选择。 说到野草云的历史背景,首先让我想起它在竞争激...

    主机论坛:获取信息与交流经验的最佳平台

    主机论坛概述 在当今的数字时代,主机论坛作为一个专注于域名、主机、VPS和服务器的讨论与信息交流平台,显得尤为重要。对于站长、开发者和一般用户来说,它们不仅是资讯获取的渠道,更是一个技术交流和问题解决的空间。主机论坛通过汇聚来自不同背景的用户,形成了一个活跃的社区,每个人都能找到自己感兴趣的话题,分...