当前位置: 首页 > news >正文

iis 5 新建网站确定网站文案

iis 5 新建网站,确定网站文案,全网微商软件激活码货源,家乡介绍网页设计一、背景 随着项目越来越大#xff0c;需要将多个服务拆分成微服务#xff0c;使代码看起来不要过于臃肿#xff0c;庞大。微服务之间通常采取feign交互#xff0c;为了保证不同微服务之间增加授权校验#xff0c;需要增加Spring Security登录验证#xff0c;为了多个服务…一、背景 随着项目越来越大需要将多个服务拆分成微服务使代码看起来不要过于臃肿庞大。微服务之间通常采取feign交互为了保证不同微服务之间增加授权校验需要增加Spring Security登录验证为了多个服务之间session可以共享可以通过数据库实现session共享也可以采用redis-session实现共享。 本文采取Spring security做登录校验用redis做session共享。实现单服务登录可靠性微服务之间调用的可靠性与通用性 二、代码 本文项目采取 主服务一服务、子服务二 来举例 1、服务依赖文件 主服务依赖 implementation group: org.springframework.boot, name: spring-boot-starter-data-redis, version: 2.5.4implementation group: org.springframework.session, name: spring-session-data-redis, version: 2.4.1implementation(group: io.github.openfeign, name: feign-httpclient)implementation org.springframework.boot:spring-boot-starter-security子服务依赖 implementation group: org.springframework.boot, name: spring-boot-starter-data-redis, version: 2.5.4implementation group: org.springframework.session, name: spring-session-data-redis, version: 2.4.1implementation org.springframework.boot:spring-boot-starter-security2、服务配置文件 主服务配置文件 #redis连接 spring.redis.host1.2.3.4 #Redis服务器连接端口 spring.redis.port6379 #Redis服务器连接密码 spring.redis.passwordpassword #连接池最大连接数使用负值表示没有限制 spring.redis.pool.max-active8 #连接池最大阻塞等待时间使用负值表示没有限制 spring.redis.pool.max-wait-1 #连接池中的最大空闲连接 spring.redis.pool.max-idle8 #连接池中的最小空闲连接 spring.redis.pool.min-idle0 #连接超时时间毫秒 spring.redis.timeout30000 #数据库 spring.redis.database0 #redis-session配置 spring.session.store-typeredis #部分post请求过长会报错需加配置 server.tomcat.max-http-header-size65536 子服务配置文件 #单独登录秘钥 micService.usernameservice micService.passwordaaaaaaaaaaaaa #登录白名单 micService.ipList1.2.3.4,1.2.3.5,127.0.0.1,0:0:0:0:0:0:0:1 spring.redis.host1.2.3.4 #Redis服务器连接端口 spring.redis.port6379 #Redis服务器连接密码 spring.redis.passwordpassword #连接池最大连接数使用负值表示没有限制 spring.redis.pool.max-active8 #连接池最大阻塞等待时间使用负值表示没有限制 spring.redis.pool.max-wait-1 #连接池中的最大空闲连接 spring.redis.pool.max-idle8 #连接池中的最小空闲连接 spring.redis.pool.min-idle0 #连接超时时间毫秒 spring.redis.timeout30000 #数据库 spring.redis.database0 #最大请求头限制 server.maxPostSize-1 server.maxHttpHeaderSize102400 #redis session缓存 spring.session.store-typeredis server.servlet.session.timeout30m 3、登录校验文件 主服务SecurityConfig.java Configuration EnableWebSecurity EnableGlobalMethodSecurity(prePostEnabled true) public class SecurityConfig extends WebSecurityConfigurerAdapter {//注入密码加密的类Beanpublic AuthenticationProvider authenticationProvider() {AuthenticationProvider authenticationProvider new EncoderProvider();return authenticationProvider;}Autowiredpublic void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {auth.userDetailsService(userDetailsService);auth.authenticationProvider(authenticationProvider());}public static final Logger logger LoggerFactory.getLogger(SecurityConfig.class);Overrideprotected void configure(HttpSecurity http) throws Exception {http.formLogin().successHandler((request,response,authentication) - {HttpSession session request.getSession();session.setAttribute(TaobaoUser,authentication.getPrincipal());ObjectMapper mapper new ObjectMapper();response.setContentType(application/json;charsetutf-8);PrintWriter out response.getWriter();TaobaoUser user (CurrentUser)session.getAttribute(TaobaoUser);out.write(mapper.writeValueAsString(user));out.flush();out.close();}).failureHandler((request,response,authentication) - {ObjectMapper mapper new ObjectMapper();response.setContentType(application/json;charsetutf-8);PrintWriter out response.getWriter();out.write(mapper.writeValueAsString(new ExceptionMessage(400,authentication.getMessage())));out.flush();out.close();}).loginPage(/Login.html).loginProcessingUrl(/login).and().authorizeRequests().antMatchers(/api/common/invalidUrl,/**/*.css, /**/*.js, /**/*.gif , /**/*.png , /**/*.jpg, /webjars/**, **/favicon.ico, /guestAccess, /Login.html,/v2/api-docs,/configuration/security,/configuration/ui,/api/common/CheckLatestVersionInfo).permitAll().anyRequest()//任何请求.authenticated().and().sessionManagement().maximumSessions(-1).sessionRegistry(sessionRegistry());;http.csrf().disable();}Autowiredprivate FindByIndexNameSessionRepository sessionRepository;Beanpublic SpringSessionBackedSessionRegistry sessionRegistry(){return new SpringSessionBackedSessionRegistry(sessionRepository);}} EncoderProvider.java Service public class EncoderProvider implements AuthenticationProvider {public static final Logger logger LoggerFactory.getLogger(EncoderProvider.class);/*** 自定义验证方式*/Overridepublic Authentication authenticate(Authentication authentication) throws AuthenticationException {try {//支持用户名和员工号登录 可能为用户名或员工号String username authentication.getName();String credential (String) authentication.getCredentials();//加密过程在这里体现TaobaoUser user userService.getUserData(username);//校验用户名是否存在if(usernull){throw new DisabledException(用户名或密码错误);}//校验登录状态checkPassword()CollectionGrantedAuthority authorities new ArrayList();return new UsernamePasswordAuthenticationToken(userCurrent, credential, authorities);} catch (Exception ex) {ex.printStackTrace();throw new DisabledException(登录发生错误 : ex.getMessage());}}Overridepublic boolean supports(Class? arg0) {return true;}子服务SecurityConfig.java Configuration EnableWebSecurity EnableGlobalMethodSecurity(prePostEnabled true) public class SecurityConfig extends WebSecurityConfigurerAdapter {//注入密码加密的类Beanpublic AuthenticationProvider authenticationProvider() {AuthenticationProvider authenticationProvider new EncoderProvider();return authenticationProvider;}Autowiredpublic void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {auth.authenticationProvider(authenticationProvider());}public static final Logger logger LoggerFactory.getLogger(SecurityConfig.class);Overrideprotected void configure(HttpSecurity http) throws Exception {logger.info(用户登录日志test1 username:http.toString());http.formLogin().loginProcessingUrl(/login).successHandler((request,response,authentication) - {HttpSession session request.getSession();session.setAttribute(TaobaoUser,authentication.getPrincipal());ObjectMapper mapper new ObjectMapper();response.setContentType(application/json;charsetutf-8);PrintWriter out response.getWriter();TaobaoUser user (TaobaoUser )session.getAttribute(TaobaoUser);out.write(mapper.writeValueAsString(user));out.flush();out.close();}).failureHandler((request,response,authentication) - {ObjectMapper mapper new ObjectMapper();response.setContentType(application/json;charsetutf-8);PrintWriter out response.getWriter();out.write(mapper.writeValueAsString(new ExceptionMessage(400,authentication.getMessage())));out.flush();out.close();}).loginPage(/Login.html).and().authorizeRequests().antMatchers(/**/*.css, /**/*.js, /**/*.gif , /**/*.png ,/**/*.jpg, /webjars/**, **/favicon.ico, /Login.html,/v2/api-docs,/configuration/security,/configuration/ui).permitAll().anyRequest().authenticated().and().sessionManagement().maximumSessions(-1).sessionRegistry(sessionRegistry());http.csrf().disable();}Autowiredprivate FindByIndexNameSessionRepository sessionRepository;Beanpublic SpringSessionBackedSessionRegistry sessionRegistry(){return new SpringSessionBackedSessionRegistry(sessionRepository);}}EncoderProvider.java Service public class EncoderProvider implements AuthenticationProvider {public static final Logger logger LoggerFactory.getLogger(EncoderProvider.class);Value(${service.username})private String userName1;Value(${service.ipList})private String ipList;/*** 自定义验证方式*/Overridepublic Authentication authenticate(Authentication authentication) throws AuthenticationException {try {//支持用户名和员工号登录 可能为用户名或员工号String username authentication.getName();String credential (String)authentication.getCredentials();TaobaoUser usernew TaobaoUser();if(username.equals(userName1)){ListString ips Arrays.asList(ipList.split(,));WebAuthenticationDetails details (WebAuthenticationDetails) authentication.getDetails();String remoteIp details.getRemoteAddress();logger.info(ip为{}-通过用户{}调用接口,remoteIp,username);if(!ips.contains(remoteIp)){throw new DisabledException(无权登陆);}}else{throw new DisabledException(账户不存在);}user.setA(A);CollectionGrantedAuthority authorities new ArrayList();return new UsernamePasswordAuthenticationToken(currentUser, credential, authorities);} catch (Exception ex) {ex.printStackTrace();throw new DisabledException(登录发生错误 : ex.getMessage());}}Overridepublic boolean supports(Class? arg0) {return true;}} 4、主服务feign配置 FeignManage.java #url ${file.client.url}, FeignClient(namefile-service,fallback FeignFileManageFallback.class,configuration FeignConfiguration.class) public interface FeignFileManage {RequestMapping(value /file/upload, method {RequestMethod.POST}, consumes MediaType.MULTIPART_FORM_DATA_VALUE)ApiBaseMessage fileUpload(RequestPart(file) MultipartFile file, RequestParam(fileName) String fileName) ;}public class FeignManageFallback implements FeignManage{Overridepublic ApiBaseMessage fileUpload(MultipartFile file, String type) {return ApiBaseMessage.getOperationSucceedInstance(400,失败);}} FeignFileManageFallback.java FeignConfiguration.java Configuration Import(FeignClientsConfiguration.class) public class FeignConfiguration {/**删除请求头文件*/final String[] copyHeaders new String[]{transfer-encoding,Content-Length};Beanpublic FeignFileManageFallback echoServiceFallback(){return new FeignFileManageFallback();}Beanpublic FeignBasicAuthRequestInterceptor getFeignBasicAuthRequestInterceptor(){return new FeignBasicAuthRequestInterceptor();}/*** feign 调用添加CurrentUser*/private class FeignBasicAuthRequestInterceptor implements RequestInterceptor {Overridepublic void apply(RequestTemplate template) {//1、使用RequestContextHolder拿到刚进来的请求数据ServletRequestAttributes requestAttributes (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();if (requestAttributes ! null) {HttpServletRequest request requestAttributes.getRequest();EnumerationString headerNames request.getHeaderNames();if (headerNames ! null) {while (headerNames.hasMoreElements()) {String name headerNames.nextElement();String values request.getHeader(name);//删除的请求头if (!Arrays.asList(copyHeaders).contains(name)) {template.header(name, values);}}}}else{template.header(Accept, */*);template.header(Accept-Encoding, gzip, deflate, br);template.header(Content-Type, application/json);}//增加用户信息if(requestAttributes!null SessionHelper.getCurrentUser()!null){try {template.header(TaobaoUser, URLEncoder.encode(JSON.toJSONString(SessionHelper.getCurrentUser()),utf-8) );} catch (UnsupportedEncodingException e) {e.printStackTrace();}}}}} 5、主服务session文件 SessionUtil.java public class SessionUtil {public static CurrentUser getCurrentUser() {HttpSession session ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession();CurrentUser user (CurrentUser)session.getAttribute(TaobaoUser);return user;}public static void setCurrentUser(String userName){HttpSession session ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession();CollectionGrantedAuthority authorities new ArrayList();session.setAttribute(TaobaoUser,new CurrentUser(userName, , authorities));} } 三、完成配置后 1、直接访问主服务接口不登录无法访问 2、直接访问自服务不登录无法访问可通过nacos配置用户密码实现登录 3、主服务通过feign调用子服务接口正常(session已共享) 4、子服务登陆之后调用主服务理论也可以需校验下主服务用户侧
http://www.zqtcl.cn/news/663568/

相关文章:

  • 网站建设和维护要点网站建设完提交百度
  • app开发人员网站上海保洁服务网站建设
  • 周口网站制作公司哪家好苏州高新区住建局官网
  • 建设特效网站自助网站建设系统
  • 用软件做的网站权限管理如何让自己的网站被百度收录
  • 简历做的很棒的网站杭州公司网站建设电话
  • 购买腾讯云主机可以直接做网站舒兰网站建设
  • 环保主题静态网站php 手机网站源码
  • 做网站找哪家好要钱吗小程序开发合同
  • 速成美站东莞网站建设 包装材料
  • 丹阳网站建设案例自己做个网站怎么赚钱
  • 净水机企业网站源码浏览器下载安装2022最新版
  • 高端网站建设四川网页版微信怎么下载
  • 青岛做网站皆赴青岛博采wordpress怎么改密码忘记
  • 深圳最好的网站建设广西论坛网站建设
  • html5网站设计网站建设 广西
  • 顺德手机网站设计价位网站开发学习流程图
  • 班级网站设计合肥蜀山网站开发
  • 杭州网站建设培训ck播放器整合WordPress
  • 网站建设是什么软件品牌策划公司哪家好推荐
  • 网站转跳怎么做餐饮vi设计
  • 刘连康seo培训哪家强网站优化推广平台
  • 网站推广内容滁州做网站的
  • 黄山做网站公司山东省住房和城乡建设厅举报电话
  • 中医科网站建设素材上海文明城市建设网站
  • html课程教学网站模板手机微信小程序开发教程
  • 用电脑做兼职的网站比较好食品网站建设网站定制开发
  • 网站开发 加密保护小程序制作开发进度表
  • 深圳坪山站外贸展示型网站建设
  • 手机端自定义做链接网站济南网站制作方案