最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

登錄

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

用戶(hù)認(rèn)證

需要結(jié)合JWT來(lái)實(shí)現(xiàn)用戶(hù)認(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管理,所以封裝用戶(hù)信息生成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ī)制,通過(guò)token來(lái)管理用戶(hù)的登錄狀態(tài)。這里有倆段關(guān)鍵代碼。

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

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

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)

第一步,開(kāi)啟注解@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)文章

  • java實(shí)現(xiàn)遍歷Map的方法

    java實(shí)現(xiàn)遍歷Map的方法

    這篇文章主要介紹了java實(shí)現(xiàn)遍歷Map的方法,以簡(jiǎn)單實(shí)例形式分析了java針對(duì)HashMap的遍歷技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下
    2015-09-09
  • 全網(wǎng)最全Mybatis-Plus詳解

    全網(wǎng)最全Mybatis-Plus詳解

    Mybatis-Plus是一個(gè)Mybatis(opens?new?window)的增強(qiáng)工具,在Mybatis的基礎(chǔ)上只做增強(qiáng)不做改變,為簡(jiǎn)化開(kāi)發(fā),這篇文章主要介紹了全網(wǎng)最全Mybatis-Plus詳解,需要的朋友可以參考下
    2024-05-05
  • idea運(yùn)行vue項(xiàng)目設(shè)置自定義瀏覽器方式

    idea運(yùn)行vue項(xiàng)目設(shè)置自定義瀏覽器方式

    這篇文章主要介紹了idea運(yùn)行vue項(xiàng)目設(shè)置自定義瀏覽器方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-08-08
  • SpringMVC文件上傳請(qǐng)求問(wèn)題分析

    SpringMVC文件上傳請(qǐng)求問(wèn)題分析

    這篇文章主要介紹了SpringMVC文件上傳請(qǐng)求,我們發(fā)的請(qǐng)求默認(rèn)都是由DispatcherServlet類(lèi)的doDispatch()來(lái)處理,這個(gè)方法的邏輯處理的第一步就是處理文件上傳的請(qǐng)求,我們一起來(lái)看看是怎么處理的吧
    2024-07-07
  • 帶你入門(mén)Java的泛型

    帶你入門(mén)Java的泛型

    這篇文章主要給大家介紹了關(guān)于Java中泛型使用的簡(jiǎn)單方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用Java具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2021-07-07
  • eclipse怎么引入spring boot項(xiàng)目插件的方法

    eclipse怎么引入spring boot項(xiàng)目插件的方法

    這篇文章主要介紹了eclipse怎么引入spring boot項(xiàng)目插件的方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-06-06
  • java中split()方法以及常見(jiàn)算法經(jīng)典案例

    java中split()方法以及常見(jiàn)算法經(jīng)典案例

    這篇文章主要介紹了java中split()方法以及常見(jiàn)算法的相關(guān)資料,split()方法可以根據(jù)指定的正則表達(dá)式將字符串分割成多個(gè)子字符串,并返回一個(gè)字符串?dāng)?shù)組,文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2025-04-04
  • Spring?注入集合實(shí)現(xiàn)過(guò)程示例詳解

    Spring?注入集合實(shí)現(xiàn)過(guò)程示例詳解

    這篇文章主要為大家介紹了Spring?注入集合實(shí)現(xiàn)過(guò)程示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-09-09
  • Java數(shù)據(jù)結(jié)構(gòu)之Map與Set專(zhuān)篇講解

    Java數(shù)據(jù)結(jié)構(gòu)之Map與Set專(zhuān)篇講解

    這篇文章通過(guò)實(shí)例面試題目來(lái)講解Java中Map和Set之間的關(guān)系,具有很好的參考價(jià)值,Map與Set在面試中經(jīng)常會(huì)遇到。一起跟隨小編過(guò)來(lái)看看吧
    2022-01-01
  • 使用Java實(shí)現(xiàn)接口攔截器來(lái)監(jiān)控接口的執(zhí)行情況

    使用Java實(shí)現(xiàn)接口攔截器來(lái)監(jiān)控接口的執(zhí)行情況

    在排查問(wèn)題的時(shí)候,由于沒(méi)有對(duì)接口的執(zhí)行情況,以及入?yún)⑦M(jìn)行監(jiān)控,所以排查起問(wèn)題就特別費(fèi)勁,今天我們就一起來(lái)寫(xiě)一個(gè)接口的攔截器來(lái)監(jiān)控接口的執(zhí)行情況吧
    2024-01-01

最新評(píng)論

和林格尔县| 库尔勒市| 南康市| 罗山县| 广州市| 化隆| 建昌县| 清流县| 安达市| 滁州市| 鄂托克旗| 闻喜县| 镇宁| 岢岚县| 桐梓县| 平邑县| 嵊泗县| 唐山市| 富宁县| 蓬莱市| 昂仁县| 黄梅县| 宝坻区| 营山县| 葫芦岛市| 志丹县| 自贡市| 云林县| 和平县| 开远市| 邮箱| 惠州市| 榆林市| 广宗县| 永寿县| 巢湖市| 巧家县| 宜宾县| 兴义市| 张掖市| 芜湖市|