电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

您的位置:首頁技術文章
文章詳情頁

Spring Boot 2結合Spring security + JWT實現微信小程序登錄

瀏覽:148日期:2022-06-25 08:45:35

項目源碼:https://gitee.com/tanwubo/jwt-spring-security-demo

登錄

通過自定義的WxAppletAuthenticationFilter替換默認的UsernamePasswordAuthenticationFilter,在UsernamePasswordAuthenticationFilter中可任意定制自己的登錄方式。

用戶認證

需要結合JWT來實現用戶認證,第一步登錄成功后如何頒發token。

public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler { @Autowired private JwtTokenUtils jwtTokenUtils; @Override public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException { // 使用jwt管理,所以封裝用戶信息生成jwt響應給前端 String token = jwtTokenUtils.generateToken(((WxAppletAuthenticationToken)authentication).getOpenid()); Map<String, Object> result = Maps.newHashMap(); result.put(ConstantEnum.AUTHORIZATION.getValue(), token); httpServletResponse.setContentType(ContentType.JSON.toString()); httpServletResponse.getWriter().write(JSON.toJSONString(result)); }}

第二步,棄用spring security默認的session機制,通過token來管理用戶的登錄狀態。這里有倆段關鍵代碼。

@Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable().sessionManagement()// 不創建Session, 使用jwt來管理用戶的登錄狀態.sessionCreationPolicy(SessionCreationPolicy.STATELESS)......; }

第二步,添加token的認證過濾器。

public class JwtAuthenticationTokenFilter extends OncePerRequestFilter { @Autowired private AuthService authService; @Autowired private JwtTokenUtils jwtTokenUtils; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { log.debug('processing authentication for [{}]', request.getRequestURI()); String token = request.getHeader(ConstantEnum.AUTHORIZATION.getValue()); String openid = null; if (token != null) { try {openid = jwtTokenUtils.getUsernameFromToken(token); } catch (IllegalArgumentException e) {log.error('an error occurred during getting username from token', e);throw new BasicException(ExceptionEnum.JWT_EXCEPTION.customMessage('an error occurred during getting username from token , token is [%s]', token)); } catch (ExpiredJwtException e) {log.warn('the token is expired and not valid anymore', e);throw new BasicException(ExceptionEnum.JWT_EXCEPTION.customMessage('the token is expired and not valid anymore, token is [%s]', token)); }catch (SignatureException e) {log.warn('JWT signature does not match locally computed signature', e);throw new BasicException(ExceptionEnum.JWT_EXCEPTION.customMessage('JWT signature does not match locally computed signature, token is [%s]', token)); } }else { log.warn('couldn’t find token string'); } if (openid != null && SecurityContextHolder.getContext().getAuthentication() == null) { log.debug('security context was null, so authorizing user'); Account account = authService.findAccount(openid); List<Permission> permissions = authService.acquirePermission(account.getAccountId()); List<SimpleGrantedAuthority> authorities = permissions.stream().map(permission -> new SimpleGrantedAuthority(permission.getPermission())).collect(Collectors.toList()); log.info('authorized user [{}], setting security context', openid); SecurityContextHolder.getContext().setAuthentication(new WxAppletAuthenticationToken(openid, authorities)); } filterChain.doFilter(request, response); }}接口鑒權

第一步,開啟注解@EnableGlobalMethodSecurity。

@SpringBootApplication@EnableGlobalMethodSecurity(prePostEnabled = true)public class JwtSpringSecurityDemoApplication { public static void main(String[] args) { SpringApplication.run(JwtSpringSecurityDemoApplication.class, args); }}

第二部,在需要鑒權的接口上添加@PreAuthorize注解。

@RestController@RequestMapping('/test')public class TestController { @GetMapping @PreAuthorize('hasAuthority(’user:test’)') public String test(){ return 'test success'; } @GetMapping('/authority') @PreAuthorize('hasAuthority(’admin:test’)') public String authority(){ return 'test authority success'; }}

到此這篇關于Spring Boot 2結合Spring security + JWT實現微信小程序登錄的文章就介紹到這了,更多相關Spring Boot Spring security JWT微信小程序登錄內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: 微信
相關文章:
主站蜘蛛池模板: 瑞典Blueair空气净化器租赁服务中心-专注新装修办公室除醛去异味服务! | 2-羟基泽兰内酯-乙酰蒲公英萜醇-甘草查尔酮A-上海纯优生物科技有限公司 | 刚性-柔性防水套管-橡胶伸缩接头-波纹管补偿器-启腾供水材料有限公司 | 深圳激光打标机_激光打标机_激光焊接机_激光切割机_同体激光打标机-深圳市创想激光科技有限公司 深圳快餐店设计-餐饮设计公司-餐饮空间品牌全案设计-深圳市勤蜂装饰工程 | YT保温材料_YT无机保温砂浆_外墙保温材料_南阳银通节能建材高新技术开发有限公司 | 楼承板-开闭口楼承板-无锡海逵楼承板 | 发电机价格|发电机组价格|柴油发电机价格|柴油发电机组价格网 | 阿里巴巴诚信通温州、台州、宁波、嘉兴授权渠道商-浙江联欣科技提供阿里会员办理 | 全自动包衣机-无菌分装隔离器-浙江迦南科技股份有限公司 | 广西资质代办_建筑资质代办_南宁资质代办理_新办、增项、升级-正明集团 | 卷筒电缆-拖链电缆-特种柔性扁平电缆定制厂家「上海缆胜」 | 防爆大气采样器-防爆粉尘采样器-金属粉尘及其化合物采样器-首页|盐城银河科技有限公司 | 方源木业官网-四川木门-全国木门专业品牌 | 芝麻黑-芝麻黑石材厂家-永峰石业 | 石牌坊价格石牌坊雕刻制作_石雕牌坊牌楼石栏杆厂家_山东嘉祥石雕有限公司 | 半容积式换热器_北京浮动盘管换热器厂家|北京亿丰上达 | 高通量组织研磨仪-多样品组织研磨仪-全自动组织研磨仪-研磨者科技(广州)有限公司 | 网站建设-网站制作-网站设计-网站开发定制公司-网站SEO优化推广-咏熠软件 | 通信天线厂家_室分八木天线_对数周期天线_天线加工厂_林创天线源头厂家 | 农业四情_农业气象站_田间小型气象站_智慧农业气象站-山东风途物联网 | 布袋除尘器-单机除尘器-脉冲除尘器-泊头市兴天环保设备有限公司 布袋除尘器|除尘器设备|除尘布袋|除尘设备_诺和环保设备 | 骨灰存放架|骨灰盒寄存架|骨灰架厂家|智慧殡葬|公墓陵园管理系统|网上祭奠|告别厅智能化-厦门慈愿科技 | 不锈钢列管式冷凝器,换热器厂家-无锡飞尔诺环境工程有限公司 | 龙门加工中心-数控龙门加工中心厂家价格-山东海特数控机床有限公司_龙门加工中心-数控龙门加工中心厂家价格-山东海特数控机床有限公司 | 杭州成人高考_浙江省成人高考网上报名 | 河南正规膏药生产厂家-膏药贴牌-膏药代加工-修康药业集团官网 | 小程序开发公司-小程序制作-微信小程序开发-小程序定制-咏熠软件 | 碳化硅,氮化硅,冰晶石,绢云母,氟化铝,白刚玉,棕刚玉,石墨,铝粉,铁粉,金属硅粉,金属铝粉,氧化铝粉,硅微粉,蓝晶石,红柱石,莫来石,粉煤灰,三聚磷酸钠,六偏磷酸钠,硫酸镁-皓泉新材料 | 土壤水分自动监测站-SM150便携式土壤水分仪-铭奥仪器 | 烘干设备-热泵烘干机_广东雄贵能源设备有限公司 | 消泡剂-水处理消泡剂-涂料消泡剂-切削液消泡剂价格-东莞德丰消泡剂厂家 | 防火门|抗爆门|超大门|医疗门|隔声门-上海加汇门业生产厂家 | 东莞动力锂电池保护板_BMS智能软件保护板_锂电池主动均衡保护板-东莞市倡芯电子科技有限公司 | 工业雾炮机_超细雾炮_远程抑尘射雾器-世纪润德环保设备 | 天津散热器_天津暖气片_天津安尼威尔散热器制造有限公司 | 液压油缸-液压站生产厂家-洛阳泰诺液压科技有限公司 | 纸张环压仪-纸张平滑度仪-杭州纸邦自动化技术有限公司 | 哈尔滨发电机,黑龙江柴油发电机组-北方星光 | B2B网站_B2B免费发布信息网站_B2B企业贸易平台 - 企资网 | 柔性测斜仪_滑动测斜仪-广州杰芯科技有限公司 | 福州仿石漆加盟_福建仿石漆厂家-外墙仿石漆加盟推荐铁壁金钢(福建)新材料科技有限公司有保障 |