亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Spring Boot 2結(jié)合Spring security + JWT實(shí)現(xiàn)微信小程序登錄

 更新時(shí)間:2021年01月25日 10:24:20   作者:tanwubo  
這篇文章主要介紹了Spring Boot 2結(jié)合Spring security + JWT實(shí)現(xiàn)微信小程序登錄,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

項(xiàng)目源碼:https://gitee.com/tanwubo/jwt-spring-security-demo

登錄

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

用戶認(rèn)證

需要結(jié)合JWT來實(shí)現(xiàn)用戶認(rèn)證,第一步登錄成功后如何頒發(fā)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響應(yīng)給前端
    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默認(rèn)的session機(jī)制,通過token來管理用戶的登錄狀態(tài)。這里有倆段關(guān)鍵代碼。

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

第二步,添加token的認(rèn)證過濾器。

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);
  }
}

接口鑒權(quán)

第一步,開啟注解@EnableGlobalMethodSecurity

@SpringBootApplication
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class JwtSpringSecurityDemoApplication {

  public static void main(String[] args) {
    SpringApplication.run(JwtSpringSecurityDemoApplication.class, args);
  }

}

第二部,在需要鑒權(quán)的接口上添加@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";
  }

}

到此這篇關(guān)于Spring Boot 2結(jié)合Spring security + JWT實(shí)現(xiàn)微信小程序登錄的文章就介紹到這了,更多相關(guān)Spring Boot Spring security JWT微信小程序登錄內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • SpringCloud Alibaba微服務(wù)實(shí)戰(zhàn)之遠(yuǎn)程Feign請(qǐng)求頭丟失問題解決方案

    SpringCloud Alibaba微服務(wù)實(shí)戰(zhàn)之遠(yuǎn)程Feign請(qǐng)求頭丟失問題解決方案

    這篇文章主要介紹了SpringCloud Alibaba微服務(wù)實(shí)戰(zhàn)之遠(yuǎn)程Feign請(qǐng)求頭丟失問題,對(duì)SpringCloud Alibaba Feign請(qǐng)求頭問題感興趣的朋友跟隨小編一起看看吧
    2024-02-02
  • 解決grails服務(wù)端口沖突的辦法(grails修改端口號(hào))

    解決grails服務(wù)端口沖突的辦法(grails修改端口號(hào))

    grails中默認(rèn)的服務(wù)端口為8080,當(dāng)本機(jī)中需要同時(shí)啟動(dòng)兩個(gè)不同的項(xiàng)目時(shí),就會(huì)造成端口沖突,下面給出解決方法
    2013-12-12
  • java獲取properties屬性文件示例

    java獲取properties屬性文件示例

    Properties類表示了一個(gè)持久的屬性集。Properties可保存在流中或從流中加載。屬性列表中每個(gè)鍵及其對(duì)應(yīng)值都是一個(gè)字符串。本文使用java讀取這些屬性,看下面詳細(xì)介紹吧
    2014-01-01
  • java基礎(chǔ)的詳細(xì)了解第二天

    java基礎(chǔ)的詳細(xì)了解第二天

    這篇文章對(duì)Java編程語(yǔ)言的基礎(chǔ)知識(shí)作了一個(gè)較為全面的匯總,在這里給大家分享一下。需要的朋友可以參考,希望能給你帶來幫助
    2021-08-08
  • java單點(diǎn)登錄(SSO)的實(shí)現(xiàn)

    java單點(diǎn)登錄(SSO)的實(shí)現(xiàn)

    SSO是指在多個(gè)應(yīng)用系統(tǒng)中個(gè),用戶只需要登陸一次就可以訪問所有相互信任的應(yīng)用系統(tǒng),本文主要介紹了java單點(diǎn)登錄的實(shí)現(xiàn),具有一定的參考價(jià)值,感興趣的可以了解一下
    2021-07-07
  • java判斷字符串是否為數(shù)字的方法小結(jié)

    java判斷字符串是否為數(shù)字的方法小結(jié)

    這篇文章主要介紹了java判斷字符串是否為數(shù)字的方法,分別講述了使用Java自帶函數(shù)、正則表達(dá)式及ascii碼三種方法進(jìn)行字符串判斷的相關(guān)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下
    2015-11-11
  • Java 繼承原理與用法實(shí)例分析

    Java 繼承原理與用法實(shí)例分析

    這篇文章主要介紹了Java 繼承原理與用法,結(jié)合實(shí)例形式分析了java面向?qū)ο蟪绦蛟O(shè)計(jì)中繼承的概念、原理、用法及操作注意事項(xiàng),需要的朋友可以參考下
    2019-06-06
  • 解決調(diào)用ftpClient.retrieveFileStream(String?remoteFilePath)第二次讀取為空問題

    解決調(diào)用ftpClient.retrieveFileStream(String?remoteFilePath)第二次讀

    這篇文章主要給大家介紹了關(guān)于如何解決調(diào)用ftpClient.retrieveFileStream(String?remoteFilePath)第二次讀取為空問題的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2023-08-08
  • Hadoop 中 HBase Shell命令的詳解

    Hadoop 中 HBase Shell命令的詳解

    這篇文章主要介紹了Hadoop 中 HBase Shell命令的詳解的相關(guān)資料,需要的朋友可以參考下
    2017-10-10
  • Java簡(jiǎn)明解讀代碼塊的應(yīng)用

    Java簡(jiǎn)明解讀代碼塊的應(yīng)用

    所謂代碼塊是指用"{}"括起來的一段代碼,根據(jù)其位置和聲明的不同,可以分為普通代碼塊、構(gòu)造塊、靜態(tài)塊、和同步代碼塊。如果在代碼塊前加上 synchronized關(guān)鍵字,則此代碼塊就成為同步代碼塊
    2022-07-07

最新評(píng)論