Spring Boot 2结合Spring security + JWT实现微信小程序登录

项目源码: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微信小程序登录内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • SpringBoot集成Spring Security用JWT令牌实现登录和鉴权的方法

    最近在做项目的过程中 需要用JWT做登录和鉴权 查了很多资料 都不甚详细 有的是需要在application.yml里进行jwt的配置 但我在导包后并没有相应的配置项 因而并不适用 在踩过很多坑之后 稍微整理了一下 做个笔记 一.概念 1.什么是JWT Json Web Token (JWT)是为了在网络应用环境间传递声明而执行的一种基于JSON的开放标准(RFC 7519) 该token被设计为紧凑且安全的 特别适用于分布式站点的单点登录(SSO)场景 随着JWT的出现 使得校验方式更加简单便

  • springboot+jwt+springSecurity微信小程序授权登录问题

    场景重现:1.微信小程序向后台发送请求 --而后台web采用的springSecuriry没有token生成,就会拦截请求,,所以小编记录下这个问题 微信小程序授权登录问题 思路 参考网上一大堆资料 核心关键字: 自定义授权+鉴权 (说的通俗就是解决办法就是改造springSecurity的过滤器) 参考文章 https://www.jb51.net/article/204704.htm 总的来说的 通过自定义的WxAppletAuthenticationFilter替换默认的UsernameP

  • Springboot+SpringSecurity+JWT实现用户登录和权限认证示例

    如今,互联网项目对于安全的要求越来越严格,这就是对后端开发提出了更多的要求,目前比较成熟的几种大家比较熟悉的模式,像RBAC 基于角色权限的验证,shiro框架专门用于处理权限方面的,另一个比较流行的后端框架是Spring-Security,该框架提供了一整套比较成熟,也很完整的机制用于处理各类场景下的可以基于权限,资源路径,以及授权方面的解决方案,部分模块支持定制化,而且在和oauth2.0进行了很好的无缝连接,在移动互联网的授权认证方面有很强的优势,具体的使用大家可以结合自己的业务场景进行选

  • Spring Boot(四)之使用JWT和Spring Security保护REST API

    通常情况下,把API直接暴露出去是风险很大的,不说别的,直接被机器攻击就喝一壶的.那么一般来说,对API要划分出一定的权限级别,然后做一个用户的鉴权,依据鉴权结果给予用户开放对应的API.目前,比较主流的方案有几种: 用户名和密码鉴权,使用Session保存用户鉴权结果. 使用OAuth进行鉴权(其实OAuth也是一种基于Token的鉴权,只是没有规定Token的生成方式) 自行采用Token进行鉴权 第一种就不介绍了,由于依赖Session来维护状态,也不太适合移动时代,新的项目就不要采用了.

  • SpringBoot+Spring Security+JWT实现RESTful Api权限控制的方法

    摘要:用spring-boot开发RESTful API非常的方便,在生产环境中,对发布的API增加授权保护是非常必要的.现在我们来看如何利用JWT技术为API增加授权保护,保证只有获得授权的用户才能够访问API. 一:开发一个简单的API 在IDEA开发工具中新建一个maven工程,添加对应的依赖如下: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-b

  • Spring Boot 2结合Spring security + JWT实现微信小程序登录

    项目源码:https://gitee.com/tanwubo/jwt-spring-security-demo 登录 通过自定义的WxAppletAuthenticationFilter替换默认的UsernamePasswordAuthenticationFilter,在UsernamePasswordAuthenticationFilter中可任意定制自己的登录方式. 用户认证 需要结合JWT来实现用户认证,第一步登录成功后如何颁发token. public class CustomAuthe

  • Java中基于Shiro,JWT实现微信小程序登录完整例子及实现过程

    小程序官方流程图如下,官方地址 : https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/login.html : 本文是对接微信小程序自定义登录的一个完整例子实现 ,技术栈为 : SpringBoot+Shiro+JWT+JPA+Redis. 如果对该例子比较感兴趣或者觉得言语表达比较啰嗦,可查看完整的项目地址 : https://github.com/EalenXie/shiro-jwt-applet

  • Spring Boot实现微信小程序登录

    使用Spring Boot完成微信小程序登录 由于微信最近的版本更新,wx.getUserInfo()的这个接口即将失效,将用wx.getUserProfile()替换,所以近期我也对自己的登录进行更新,并且为了巩固学习到的知识,我自己做了一个小demo,在此分享给大家,希望能对大家有所帮助.废话不多说,直接上代码. 前端 .wxml <button class="r" bindtap="bindGetUserInfo">同意</button>

  • 微信小程序登录对接Django后端实现JWT方式验证登录详解

    先上效果图 点击授权按钮后可以显示部分资料和头像,点击修改资料可以修改部分资料. 流程 1.使用微信小程序登录和获取用户信息Api接口 2.把Api获取的用户资料和code发送给django后端 3.通过微信接口把code换取成openid 4.后端将openid作为用户名和密码 5.后端通过JSON web token方式登录,把token和用户id传回小程序 6.小程序将token和用户id保存在storage中 下次请求需要验证用户身份的页面时,在header中加入token这个字段 微信

  • Spring Security组件一键接入验证码登录和小程序登录的详细过程

    目录 DSL配置风格 为什么这么灵活? 使用方法 普通登录 验证码登录 小程序登录 最近实现了一个多端登录的Spring Security组件,用起来非常丝滑,开箱即用,可插拔,而且灵活性非常强.我觉得能满足大部分场景的需要.目前完成了手机号验证码和微信小程序两种自定义登录,加上默认的Form登录,一共三种,现在开源分享给大家,接下来简单介绍一下这个插件包. DSL配置风格 切入正题,先来看看配置: @Bean SecurityFilterChain defaultSecurityFilterC

  • Spring Boot中使用 Spring Security 构建权限系统的示例代码

    Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架.它提供了一组可以在Spring应用上下文中配置的Bean,为应用系统提供声明式的安全访问控制功能,减少了为企业系统安全控制编写大量重复代码的工作. 权限控制是非常常见的功能,在各种后台管理里权限控制更是重中之重.在Spring Boot中使用 Spring Security 构建权限系统是非常轻松和简单的.下面我们就来快速入门 Spring Security .在开始前我们需要一对

  • spring boot(三)之Spring Boot中Redis的使用

    spring boot对常用的数据库支持外,对nosql 数据库也进行了封装自动化. redis介绍 Redis是目前业界使用最广泛的内存数据存储.相比memcached,Redis支持更丰富的数据结构,例如hashes, lists, sets等,同时支持数据持久化.除此之外,Redis还提供一些类数据库的特性,比如事务,HA,主从库.可以说Redis兼具了缓存系统和数据库的一些特性,因此有着丰富的应用场景.本文介绍Redis在Spring Boot中两个典型的应用场景. 如何使用 1.引入

  • 微信小程序 websocket 实现SpringMVC+Spring+Mybatis

    微信小程序实现websocket步骤: 后台: 1. 添加maven依赖 2. 创建握手 3. 创建处理器 4. spring配置(xml配置或javabean方式配置任选一种) 微信小程序: 1. 书写连接 java后台 1.添加maven依赖 <!-- websocket --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-websocket&l

  • springboot+jwt+微信小程序授权登录获取token的方法实例

    目录 前言 配置 XcxAuthenticationProvider XcxAuthenticationToken 小程序授权登录 前言 我们有时候在开发中,遇到这样的问题,就是我们需要小程序授权登录我们自己的后台,通过小程序的信息换取我们自己后台的token,实现账号密码.小程序授权登录的多种登录方式. 配置 在 SecurityConfig文件中配置 XcxAuthenticationProvider public class XcxAuthenticationProvider implem

随机推荐