您好,登錄后才能下訂單哦!
怎么在springboot中使用jwt與springSecurity實(shí)現(xiàn)一個(gè)微信小程序授權(quán)登錄功能?相信很多沒有經(jīng)驗(yàn)的人對(duì)此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個(gè)問題。
通過自定義的WxAppletAuthenticationFilter替換默認(rèn)的
UsernamePasswordAuthenticationFilter
,在UsernamePasswordAuthenticationFilter中可任意定制自己的登錄方式。
springSecurity的原來的登錄過濾器UsernamePasswordAuthenticationFilter
采用賬戶+密碼的形式
說明我微信小程序這里很有可能不適用要升級(jí),因?yàn)槲⑿判〕绦虿捎胦penid的形式登錄,而沒有password
需要結(jié)合JWT來實(shí)現(xiàn)用戶認(rèn)證,第一步登錄成功后如何頒發(fā)token。
使用cn.hutool.http請(qǐng)求第三方數(shù)據(jù)
<dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>4.5.16</version> </dependency>
說明:請(qǐng)求第三方數(shù)據(jù)時(shí),需要授權(quán)。
第三方(微信小程序)會(huì)給到appid和secret,請(qǐng)求攜帶appid和secret獲取一個(gè)token和expires,又了token就又了操作第三方數(shù)據(jù)的權(quán)限。
每次操作第三方數(shù)據(jù)時(shí)就需要攜帶token。
package com.shbykj.springboot.wx.security.handler; import cn.hutool.http.ContentType; import com.alibaba.fastjson.JSON; import com.shbykj.springboot.wx.enums.ConstantEnum; import com.shbykj.springboot.wx.security.WxAppletAuthenticationToken; import com.shbykj.springboot.wx.util.JwtTokenUtils; import org.apache.http.entity.ContentType; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.HashMap; import java.util.Map; /** * 用戶認(rèn)證通過的處理handler */ 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 = new HashMap<>(); result.put(ConstantEnum.AUTHORIZATION.getValue(), token); httpServletResponse.setContentType(ContentType.JSON.toString()); httpServletResponse.getWriter().write(JSON.toJSONString(result)); } }
看完上述內(nèi)容,你們掌握怎么在springboot中使用jwt與springSecurity實(shí)現(xiàn)一個(gè)微信小程序授權(quán)登錄功能的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。