日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

java 用户登录token_Java,SpringBoot采用token方式实现登录认证

發布時間:2025/4/16 java 41 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java 用户登录token_Java,SpringBoot采用token方式实现登录认证 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

IT小奮斗2021-01-13 21:48:33

Token,令牌,訪問資源的憑證,每次訪問帶上這個令牌,就可識別出用戶身份。

JWT (JsonWebToken),是實現token技術的一種解決方案,由三部分組成: header(頭)、payload(載體)、signature(簽名)。

1、頭:HS384 HS512 RS256 RS384 RS512 ES256 ES384 ES512 PS256 PS384

2、載體:

iss:Issuer,發行者sub:Subject,主題aud:Audience,觀眾exp:Expiration time,過期時間nbf:Not beforeiat:Issued at,發行時間jti:JWT ID

3、簽名

代碼案例:importio.jsonwebtoken.Claims;importio.jsonwebtoken.CompressionCodecs;importio.jsonwebtoken.Jwts;importio.jsonwebtoken.SignatureAlgorithm;importjavax.crypto.spec.SecretKeySpec;importjava.security.Key;importjava.util.Date;importjava.util.HashMap;importjava.util.Map;importjava.util.UUID;publicclassJJWTTokenApply{//使用的KeypublicstaticKeyKEY=newSecretKeySpec('密鑰'.getBytes(),SignatureAlgorithm.HS512.getJcaName());/***@paramexpiration==>失效時間*@return*/publicstaticStringgenerateAccessToken(Stringsubject,MapclaimsMap,longexpiration){//生成TokenreturnJwts.builder().setClaims(claimsMap).setSubject(subject).setId(UUID.randomUUID().toString()).setIssuedAt(newDate()).setExpiration(newDate(System.currentTimeMillis()expiration*1000)).compressWith(CompressionCodecs.DEFLATE).signWith(SignatureAlgorithm.HS256,KEY).compact();}/***@paramtoken*@return*/publicstaticMapparseAccessToken(Stringtoken){MapclaimsMap=newHashMap(16);try{Claimsclaims=Jwts.parser().setSigningKey(KEY).parseClaimsJws(token).getBody();//失效時間claimsMap.put('expiration',claims.getExpiration());//簽發者claimsMap.put('created',claims.getIssuedAt());claimsMap.put('subject',claims.getSubject());claimsMap.put('user_id',claims.get('user_id'));claimsMap.put('user_info',claims.get('user_info'));claimsMap.put('user_roles',claims.get('user_roles'));}catch(Exceptione){e.printStackTrace();}returnclaimsMap;}publicstaticvoidmain(String[]args){//主題Stringsubject='zhangsan';//加密數據MapclaimsMap=newHashMap(16);claimsMap.put('user_id',123);claimsMap.put('user_info','用戶信息');claimsMap.put('user_roles','用戶角色');//失效期1天Stringtoken=generateAccessToken(subject,claimsMap,86400);System.out.println('accessToken='token);//解析tokenMapparseMap=parseAccessToken(token);System.out.println('主題='parseMap.get('subject'));System.out.println('user_id='parseMap.get('user_id'));System.out.println('user_info='parseMap.get('user_info'));System.out.println('user_roles='parseMap.get('user_roles'));DateexpirationDate=(Date)parseMap.get('expiration');System.out.println('是否失效='expirationDate.before(newDate()));System.out.println('失效日期='expirationDate);System.out.println('失效時間='(expirationDate.getTime()-System.currentTimeMillis()));}}

SpringBoot采用token方式實現認證

1、SpringSecurity的配置

public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception { CustomAuthenticationProvider customAuthenticationProvider = new CustomAuthenticationProvider(userDetailsService); authenticationManagerBuilder.authenticationProvider(customAuthenticationProvider); }@Overrideprotected void configure(HttpSecurity http) throws Exception { http.cors().and().csrf().disable() .authorizeRequests() // 請求授權// 配置路徑放行.antMatchers('/**').permitAll() .antMatchers(HttpMethod.GET, '/webSocket/**').permitAll()// swagger 文檔.antMatchers('/swagger-ui.html').permitAll() .antMatchers('/swagger-resources/**').permitAll()// druid.antMatchers('/druid/**').permitAll()// 放行OPTIONS請求.antMatchers(HttpMethod.OPTIONS, '/**').permitAll()// 其他都需要驗證.anyRequest().authenticated() .and() .addFilter(new JWTAuthenticationFilter(authenticationManager(), userDetailsService)) .addFilter(new JWTAuthorizationFilter(authenticationManager()))// 不需要session.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); }@BeanCorsConfigurationSource corsConfigurationSource() {final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration('/**', new CorsConfiguration().applyPermitDefaultValues());return source; }}

解析:部分代碼沒貼,實現的類重點包含:JWTAuthenticationFilter、JWTAuthorizationFilter、CustomAuthenticationProvider

2、登錄認證的執行流程

3、代碼實現部分publicclassCustomAuthenticationProviderimplementsAuthenticationProvider{privateUserDetailsServiceuserService;publicCustomAuthenticationProvider(UserDetailsServiceuserService){this.userService=userService;}@OverridepublicAuthenticationauthenticate(Authenticationauthentication)throwsAuthenticationException{Stringusername=authentication.getName();Stringpassword=authentication.getCredentials().toString();//驗證用戶和密碼返回}@Overridepublicbooleansupports(Class>authentication){returnauthentication.equals(UsernamePasswordAuthenticationToken.class);}}

public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter {private AuthenticationManager authenticationManager;private UserDetailsService userDetailsService;private JwtUtils jwtUtils;public JWTAuthenticationFilter(AuthenticationManager authenticationManager, UserDetailsService userDetailsService) {this.authenticationManager = authenticationManager;this.userDetailsService = userDetailsService;// 精確指定認證地址super.setFilterProcessesUrl('/api/authen/login'); }@Overridepublic Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { Authentication returnAuthentication = null;try { AuthenUser loginUser = new ObjectMapper().readValue(request.getInputStream(), AuthenUser.class); Authentication authenticationToken = new UsernamePasswordAuthenticationToken(loginUser.getUsername(), loginUser.getPassword(), new ArrayList<>()); returnAuthentication = authenticationManager.authenticate(authenticationToken);return returnAuthentication; } catch (IOException e) { e.printStackTrace(); }return null; }// 成功驗證后調用該方法@Overrideprotected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authen) throws IOException, ServletException { String username = (String) authen.getPrincipal(); UserDetails userDetail = (UserDetails) userDetailsService.loadUserByUsername(username); String token = jwtUtils.generateAccessToken(userDetail); HashMap resultData = Maps.newHashMap(); resultData.put('token', token); resultData.put('userInfo', userDetail); resultData.put('headerName', JwtUtils.TOKEN_HEADER); resultData.put('prefix', JwtUtils.TOKEN_PREFIX); resultData.put('tokenExpiration', jwtUtils.getExpireTime(jwtUtils.getAccess_token_expiration())); String json = JSONObject.toJSONString(ServerResponse.createBySuccess(resultData)); response.setCharacterEncoding('UTF-8'); response.setContentType('application/json; charset=utf-8'); response.getWriter().write(json); }@Overrideprotected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {if (failed instanceof BadCredentialsException) { response.setCharacterEncoding('utf-8'); response.getWriter().write(JSONUtil.toJsonStr(ServerResponse.createDefaultErrorMessage(failed.getMessage()))); } else if (failed instanceof UsernameNotFoundException) { response.setCharacterEncoding('utf-8'); response.getWriter().write(JSONUtil.toJsonStr(ServerResponse.createDefaultErrorMessage(failed.getMessage()))); } else { response.getWriter().write('authentication failed, reason: ' failed.getMessage()); } }}

認證登錄成功后,返回JSON串,包含token。

3、再次請求

4、代碼處理部分publicclassJWTAuthorizationFilterextendsBasicAuthenticationFilter{publicJWTAuthorizationFilter(AuthenticationManagerauthenticationManager){super(authenticationManager);}@OverrideprotectedvoiddoFilterInternal(HttpServletRequestrequest,HttpServletResponseresponse,FilterChainchain)throwsIOException,ServletException{StringtokenHeader=request.getHeader('Authorization');//HTTP頭中的Authorization信息if(tokenHeader==null||!tokenHeader.startsWith('Bearer')){chain.doFilter(request,response);return;}try{//解析token,并且設置認證信息SecurityContextHolder.getContext().setAuthentication(getAuthentication(tokenHeader));}catch(TokenIsExpiredExceptione){response.setCharacterEncoding('UTF-8');response.setContentType('application/json;charset=utf-8');response.setStatus(HttpServletResponse.SC_FORBIDDEN);Stringreason='錯誤:'e.getMessage();response.getWriter().write(newObjectMapper().writeValueAsString(reason));response.getWriter().flush();return;}super.doFilterInternal(request,response,chain);

《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀

總結

以上是生活随笔為你收集整理的java 用户登录token_Java,SpringBoot采用token方式实现登录认证的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。