提交 f271e5a1 authored 作者: 吴德鹏's avatar 吴德鹏

优化权限,设置token失效时间为1年

上级 3661ae7f
...@@ -191,6 +191,7 @@ public class AuthController extends Controller { ...@@ -191,6 +191,7 @@ public class AuthController extends Controller {
Authentication authentication; Authentication authentication;
try { try {
authentication = authenticationManager.authenticate( authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(userInfo.getUserId(), loginRequest.getPassword())); new UsernamePasswordAuthenticationToken(userInfo.getUserId(), loginRequest.getPassword()));
} catch (BadCredentialsException e) { } catch (BadCredentialsException e) {
...@@ -226,6 +227,7 @@ public class AuthController extends Controller { ...@@ -226,6 +227,7 @@ public class AuthController extends Controller {
return new Result<>(userInfo); return new Result<>(userInfo);
} }
//Verify sent user code //Verify sent user code
@GetMapping("/verifyCode/{account}/{code}") @GetMapping("/verifyCode/{account}/{code}")
public Result<Boolean> validateCode(@PathVariable("account") String account, public Result<Boolean> validateCode(@PathVariable("account") String account,
......
...@@ -65,6 +65,7 @@ public class TbCfUserInfo { ...@@ -65,6 +65,7 @@ public class TbCfUserInfo {
/** /**
* 密码 * 密码
*/ */
@JsonIgnore
private String password; private String password;
/** /**
* 上一次登录时间 * 上一次登录时间
......
...@@ -71,7 +71,7 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter { ...@@ -71,7 +71,7 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
"/goodsType/**", "/home/**", "/spider/**", "/store/**", "/shopify/**", "/community/**", "/version/**", "/goodsType/**", "/home/**", "/spider/**", "/store/**", "/shopify/**", "/community/**", "/version/**",
"/flutterwave/notify/**", "/dpo/notify/**", "/advertisement/**", "/website/**", "/paypal/**", "/discover/bonus/**", "/flutterwave/notify/**", "/dpo/notify/**", "/advertisement/**", "/website/**", "/paypal/**", "/discover/bonus/**",
"/problem/**", "/cube/**", "/activity/**", "/attributes/**", "/stripe/**", "/coupon/**", "/logistics/freeShippingThreshold", "/problem/**", "/cube/**", "/activity/**", "/attributes/**", "/stripe/**", "/coupon/**", "/logistics/freeShippingThreshold",
"/visit/**", "/search/**", "/country/**", "/term/**", "/order/**", "/api/upload", "/cart/**", "/address/**").permitAll() "/visit/**", "/search/**", "/country/**", "/term/**", "/api/upload", "/cart/**", "/address/**").permitAll()
.antMatchers("/api/test/**").permitAll() .antMatchers("/api/test/**").permitAll()
.anyRequest().authenticated(); .anyRequest().authenticated();
......
package com.example.afrishop_v3.security.jwt; package com.example.afrishop_v3.security.jwt;
import java.io.IOException; import java.io.IOException;
import java.util.Date;
import javax.crypto.SecretKey;
import javax.servlet.FilterChain; import javax.servlet.FilterChain;
import javax.servlet.ServletException; import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import com.example.afrishop_v3.security.services.UserDetailsServiceImpl; import com.example.afrishop_v3.security.services.UserDetailsServiceImpl;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetails;
...@@ -23,6 +30,9 @@ public class AuthTokenFilter extends OncePerRequestFilter { ...@@ -23,6 +30,9 @@ public class AuthTokenFilter extends OncePerRequestFilter {
@Autowired @Autowired
private JwtUtils jwtUtils; private JwtUtils jwtUtils;
@Value("${bezkoder.app.jwtSecret}")
private String jwtSecret;
@Autowired @Autowired
private UserDetailsServiceImpl userDetailsService; private UserDetailsServiceImpl userDetailsService;
...@@ -42,9 +52,12 @@ public class AuthTokenFilter extends OncePerRequestFilter { ...@@ -42,9 +52,12 @@ public class AuthTokenFilter extends OncePerRequestFilter {
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authentication); SecurityContextHolder.getContext().setAuthentication(authentication);
String token = jwtUtils.generateJwtToken(authentication); // String token = jwtUtils.generateJwtToken(authentication);
logger.info("token:==============="+token); // logger.info("token:==============="+token);
response.setHeader("Authorization","Bearer "+token); Date expire = jwtUtils.getExpirationDateFromToken(jwt);
logger.info("token过期时间:==============="+expire);
// response.setHeader("Authorization","Bearer "+token);
} }
} catch (Exception e) { } catch (Exception e) {
logger.error("Cannot set user authentication: {}", e); logger.error("Cannot set user authentication: {}", e);
...@@ -62,4 +75,6 @@ public class AuthTokenFilter extends OncePerRequestFilter { ...@@ -62,4 +75,6 @@ public class AuthTokenFilter extends OncePerRequestFilter {
return null; return null;
} }
} }
...@@ -15,6 +15,8 @@ import org.springframework.stereotype.Component; ...@@ -15,6 +15,8 @@ import org.springframework.stereotype.Component;
import io.jsonwebtoken.*; import io.jsonwebtoken.*;
import javax.crypto.SecretKey;
@Component @Component
public class JwtUtils { public class JwtUtils {
private static final Logger logger = LoggerFactory.getLogger(JwtUtils.class); private static final Logger logger = LoggerFactory.getLogger(JwtUtils.class);
...@@ -32,11 +34,11 @@ public class JwtUtils { ...@@ -32,11 +34,11 @@ public class JwtUtils {
UserDetailsImpl userPrincipal = (UserDetailsImpl) authentication.getPrincipal(); UserDetailsImpl userPrincipal = (UserDetailsImpl) authentication.getPrincipal();
//token设置过期时间为1年 //token设置过期时间为1年 3600l * 1000 * 24 * 365
return Jwts.builder() return Jwts.builder()
.setSubject((userPrincipal.getId())) .setSubject((userPrincipal.getId()))
.setIssuedAt(new Date()) .setIssuedAt(new Date())
.setExpiration(new Date(new Date().getTime() + 3600l * 1000 * 24 * 365)) .setExpiration(new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 ))
.signWith(SignatureAlgorithm.HS512, jwtSecret) .signWith(SignatureAlgorithm.HS512, jwtSecret)
.compact(); .compact();
} }
...@@ -70,4 +72,21 @@ public class JwtUtils { ...@@ -70,4 +72,21 @@ public class JwtUtils {
return false; return false;
} }
/**
* 获取jwt失效时间
*/
public Date getExpirationDateFromToken(String token) {
return getClaimFromToken(token).getExpiration();
}
/**
* 获取jwt的payload部分
*/
public Claims getClaimFromToken(String token) {
return Jwts.parser() //得到DefaultJwtParser
.setSigningKey(jwtSecret) //设置签名的秘钥
.parseClaimsJws(token.replace("jwt_", ""))
.getBody();
}
} }
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论