Parcourir la source

添加jwt支持

zhh il y a 7 ans
Parent
commit
cd1dd9190a

+ 1 - 0
README.md

@@ -32,6 +32,7 @@ SpringAOP通用日志处理 | ✔
 SpringAOP通用验证失败结果返回 | ✔
 CommonResult对通用返回结果进行封装 | ✔
 SpringSecurity登录改为Restful形式 |
+JWT登录、注册、获取token |
 
 ### 功能完善
 

+ 11 - 3
mall-admin/pom.xml

@@ -55,6 +55,13 @@
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-aop</artifactId>
         </dependency>
+        <!--MyBatis分页插件-->
+        <dependency>
+            <groupId>com.github.pagehelper</groupId>
+            <artifactId>pagehelper-spring-boot-starter</artifactId>
+            <version>1.2.3</version>
+        </dependency>
+        <!--Swagger-UI API文档生产工具-->
         <dependency>
             <groupId>io.springfox</groupId>
             <artifactId>springfox-swagger2</artifactId>
@@ -65,10 +72,11 @@
             <artifactId>springfox-swagger-ui</artifactId>
             <version>2.6.1</version>
         </dependency>
+        <!--JWT(Json Web Token)登录支持-->
         <dependency>
-            <groupId>com.github.pagehelper</groupId>
-            <artifactId>pagehelper-spring-boot-starter</artifactId>
-            <version>1.2.3</version>
+            <groupId>io.jsonwebtoken</groupId>
+            <artifactId>jjwt</artifactId>
+            <version>0.9.0</version>
         </dependency>
     </dependencies>
     <build>

+ 58 - 0
mall-admin/src/main/java/com/macro/mall/component/JwtAuthenticationTokenFilter.java

@@ -0,0 +1,58 @@
+package com.macro.mall.component;
+
+import com.macro.mall.util.JwtTokenUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
+import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.security.core.userdetails.UserDetails;
+import org.springframework.security.core.userdetails.UserDetailsService;
+import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
+import org.springframework.stereotype.Component;
+import org.springframework.web.filter.OncePerRequestFilter;
+
+import javax.servlet.FilterChain;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
+/**
+ * JWT登录授权过滤器
+ */
+@Component
+public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
+    private static final Logger LOGGER = LoggerFactory.getLogger(JwtAuthenticationTokenFilter.class);
+    @Autowired
+    private UserDetailsService userDetailsService;
+    @Autowired
+    private JwtTokenUtil jwtTokenUtil;
+    @Value("${jwt.tokenHeader}")
+    private String tokenHeader;
+    @Value("${jwt.tokenHead}")
+    private String tokenHead;
+
+    @Override
+    protected void doFilterInternal(HttpServletRequest request,
+                                    HttpServletResponse response,
+                                    FilterChain chain) throws ServletException, IOException {
+        String authHeader = request.getHeader(this.tokenHeader);
+        if (authHeader != null && authHeader.startsWith(this.tokenHead)) {
+            String authToken = authHeader.substring(this.tokenHead.length());// The part after "Bearer "
+            String username = jwtTokenUtil.getUserNameFromToken(authToken);
+            LOGGER.info("checking username:{}", username);
+            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
+                UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
+                if (jwtTokenUtil.validateToken(authToken, userDetails)) {
+                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
+                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
+                    LOGGER.info("authenticated user:{}", username);
+                    SecurityContextHolder.getContext().setAuthentication(authentication);
+                }
+            }
+        }
+        chain.doFilter(request, response);
+    }
+}

+ 2 - 5
mall-admin/src/main/java/com/macro/mall/component/WebLogAspect.java

@@ -1,7 +1,7 @@
 package com.macro.mall.component;
 
 import com.macro.mall.bo.WebLog;
-import com.macro.mall.util.JsonUtils;
+import com.macro.mall.util.JsonUtil;
 import com.macro.mall.util.RequestUtil;
 import io.swagger.annotations.ApiOperation;
 import org.aspectj.lang.JoinPoint;
@@ -13,16 +13,13 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.core.annotation.Order;
 import org.springframework.stereotype.Component;
-import org.springframework.util.ObjectUtils;
 import org.springframework.util.StringUtils;
-import org.springframework.validation.BindingResult;
 import org.springframework.web.bind.annotation.RequestBody;
 import org.springframework.web.bind.annotation.RequestParam;
 import org.springframework.web.context.request.RequestContextHolder;
 import org.springframework.web.context.request.ServletRequestAttributes;
 
 import javax.servlet.http.HttpServletRequest;
-import java.lang.annotation.Annotation;
 import java.lang.reflect.Method;
 import java.lang.reflect.Parameter;
 import java.util.*;
@@ -75,7 +72,7 @@ public class WebLogAspect {
         webLog.setStartTime(startTime.get());
         webLog.setUri(request.getRequestURI());
         webLog.setUrl(request.getRequestURL().toString());
-        LOGGER.info("{}", JsonUtils.objectToJson(webLog));
+        LOGGER.info("{}", JsonUtil.objectToJson(webLog));
         return result;
     }
 

+ 37 - 27
mall-admin/src/main/java/com/macro/mall/config/SecurityConfig.java

@@ -1,19 +1,23 @@
 package com.macro.mall.config;
 
 import com.macro.mall.bo.AdminUserDetails;
+import com.macro.mall.component.JwtAuthenticationTokenFilter;
 import com.macro.mall.model.UmsAdmin;
 import com.macro.mall.service.UmsAdminService;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.Configuration;
+import org.springframework.http.HttpMethod;
 import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
 import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
 import org.springframework.security.config.annotation.web.builders.HttpSecurity;
 import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
 import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
+import org.springframework.security.config.http.SessionCreationPolicy;
 import org.springframework.security.core.userdetails.UserDetails;
 import org.springframework.security.core.userdetails.UserDetailsService;
 import org.springframework.security.core.userdetails.UsernameNotFoundException;
+import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
 
 
 /**
@@ -26,37 +30,38 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
     private UmsAdminService adminService;
 
     @Override
-    protected void configure(HttpSecurity http) throws Exception {
-        http.authorizeRequests()//配置权限
-//                .antMatchers("/").access("hasRole('TEST')")//该路径需要TEST角色
-                .antMatchers("/").authenticated()//该路径需要登录认证
-//                .antMatchers("/brand/getList").hasAuthority("TEST")//该路径需要TEST权限
-                .antMatchers("/**").permitAll()
-                .and()//启用基于http的认证
-                .httpBasic()
-                .realmName("/")
-                .and()//配置登录页面
-                .formLogin()
-                .loginPage("/login")
-                .failureUrl("/login?error=true")
-                .and()//配置退出路径
-                .logout()
-                .logoutSuccessUrl("/")
-//                .and()//记住密码功能
-//                .rememberMe()
-//                .tokenValiditySeconds(60*60*24)
-//                .key("rememberMeKey")
-                .and()//关闭跨域伪造
-                .csrf()
-                .disable()
-                .headers()//去除X-Frame-Options
-                .frameOptions()
-                .disable();
+    protected void configure(HttpSecurity httpSecurity) throws Exception {
+       httpSecurity.csrf()// 由于使用的是JWT,我们这里不需要csrf
+               .disable()
+               .sessionManagement()// 基于token,所以不需要session
+               .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
+               .and()
+               .authorizeRequests()
+               .antMatchers(HttpMethod.GET, // 允许对于网站静态资源的无授权访问
+                       "/",
+                       "/*.html",
+                       "/favicon.ico",
+                       "/**/*.html",
+                       "/**/*.css",
+                       "/**/*.js",
+                       "/swagger-resources/**",
+                       "/v2/api-docs/**"
+                       )
+               .permitAll()
+               .antMatchers("/auth/**")// 对于获取token的rest api要允许匿名访问
+               .permitAll()
+               .anyRequest()// 除上面外的所有请求全部需要鉴权认证
+               .authenticated();
+        // 禁用缓存
+       httpSecurity.headers().cacheControl();
+        // 添加JWT filter
+       httpSecurity.addFilterBefore(jwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);
     }
 
     @Override
     protected void configure(AuthenticationManagerBuilder auth) throws Exception {
-        auth.userDetailsService(userDetailsService()).passwordEncoder(new Md5PasswordEncoder());
+        auth.userDetailsService(userDetailsService())
+                .passwordEncoder(new Md5PasswordEncoder());
     }
 
     @Bean
@@ -73,4 +78,9 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
             }
         };
     }
+
+    @Bean
+    public JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter(){
+        return new JwtAuthenticationTokenFilter();
+    }
 }

+ 2 - 2
mall-admin/src/main/java/com/macro/mall/dto/CommonResult.java

@@ -1,7 +1,7 @@
 package com.macro.mall.dto;
 
 import com.github.pagehelper.PageInfo;
-import com.macro.mall.util.JsonUtils;
+import com.macro.mall.util.JsonUtil;
 import org.springframework.validation.BindingResult;
 
 import java.util.HashMap;
@@ -79,7 +79,7 @@ public class CommonResult {
 
     @Override
     public String toString() {
-        return JsonUtils.objectToJson(this);
+        return JsonUtil.objectToJson(this);
     }
 
     public int getCode() {

+ 1 - 1
mall-admin/src/main/java/com/macro/mall/util/JsonUtils.java → mall-admin/src/main/java/com/macro/mall/util/JsonUtil.java

@@ -9,7 +9,7 @@ import java.util.List;
 /**
  * 淘淘商城自定义响应结构
  */
-public class JsonUtils {
+public class JsonUtil {
 
     // 定义jackson对象
     private static final ObjectMapper MAPPER = new ObjectMapper();

+ 114 - 0
mall-admin/src/main/java/com/macro/mall/util/JwtTokenUtil.java

@@ -0,0 +1,114 @@
+package com.macro.mall.util;
+
+import io.jsonwebtoken.Claims;
+import io.jsonwebtoken.Jwts;
+import io.jsonwebtoken.SignatureAlgorithm;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.security.core.userdetails.UserDetails;
+import org.springframework.stereotype.Component;
+
+import java.util.Date;
+import java.util.Map;
+
+/**
+ * JwtToken生成的工具类
+ * JWT token的格式:header.payload.signature
+ * header的格式(算法、token的类型):
+ * {"alg": "HS512","typ": "JWT"}
+ * payload的格式(用户名、创建时间、生成时间):
+ * {"sub":"wang","created":1489079981393,"exp":1489684781}
+ * signature的生成算法:
+ * HMACSHA256(base64UrlEncode(header) + "." +base64UrlEncode(payload),secret)
+ */
+@Component
+public class JwtTokenUtil {
+    private static final String CLAIM_KEY_USERNAME = "sub";
+    private static final String CLAIM_KEY_CREATED = "created";
+    @Value("${jwt.secret}")
+    private String secret;
+    @Value("${jwt.expiration}")
+    private Long expiration;
+
+    /**
+     * 根据负责生成JWT的token
+     */
+    String generateToken(Map<String, Object> claims) {
+        return Jwts.builder()
+                .setClaims(claims)
+                .setExpiration(generateExpirationDate())
+                .signWith(SignatureAlgorithm.RS512, secret)
+                .compact();
+    }
+
+    /**
+     * 从token中获取JWT中的负载
+     */
+    Claims getClaimsFromToken(String token) {
+        Claims claims;
+        try {
+            claims = Jwts.parser()
+                    .setSigningKey(secret)
+                    .parseClaimsJws(token)
+                    .getBody();
+        } finally {
+            claims = null;
+        }
+        return claims;
+    }
+
+    /**
+     * 生成token的过期时间
+     */
+    private Date generateExpirationDate() {
+        return new Date(System.currentTimeMillis() + expiration * 1000);
+    }
+
+    /**
+     * 从token中获取登录用户名
+     */
+    public String getUserNameFromToken(String token) {
+        String username;
+        try {
+            Claims claims = getClaimsFromToken(token);
+            username = claims.getSubject();
+        } catch (Exception e) {
+            e.printStackTrace();
+            username = null;
+        }
+        return username;
+    }
+
+    /**
+     * 验证token是否还有效
+     *
+     * @param token       客户端传入的token
+     * @param userDetails 从数据库中查询出来的用户信息
+     */
+    public boolean validateToken(String token, UserDetails userDetails) {
+        String username = getUserNameFromToken(token);
+        return username.equals(userDetails.getUsername()) && !isTokenExpired(token);
+    }
+
+    /**
+     * 判断token是否已经失效
+     */
+    private boolean isTokenExpired(String token) {
+        Date expiredDate = getExpiredDateFromToken(token);
+        return expiredDate.before(new Date());
+    }
+
+    /**
+     * 从token中获取过期时间
+     */
+    private Date getExpiredDateFromToken(String token) {
+        Date expiredDate = null;
+        try {
+            Claims claims = getClaimsFromToken(token);
+            expiredDate = claims.getExpiration();
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return expiredDate;
+    }
+
+}

+ 20 - 3
mall-admin/src/main/resources/application.properties

@@ -1,10 +1,14 @@
+#===datasource start===
 spring.datasource.url=jdbc:mysql://localhost:3306/mall
 spring.datasource.username=root
 spring.datasource.password=root
+#===datasource end===
 
-#mybatis配置
+#===mybatis start===
 mybatis.mapper-locations=classpath:mapper/*.xml,classpath*:com/**/mapper/*.xml
+#===mybatis end===
 
+#===log start===
 #日志配置DEBUG,INFO,WARN,ERROR
 logging.level.root=info
 #单独配置日志级别
@@ -13,10 +17,23 @@ logging.level.com.macro.mall=debug
 #logging.path=/var/logs
 #配置日志文件名称
 #logging.file=demo_log.log
-#thymeleaf start
+#===log end===
+
+#===thymeleaf start===
 spring.thymeleaf.mode=HTML5
 spring.thymeleaf.encoding=UTF-8
 spring.thymeleaf.content-type=text/html
 #开发时关闭缓存,不然没法看到实时页面
 spring.thymeleaf.cache=false
-#thymeleaf end
+#===thymeleaf end==
+
+#===JWT start===
+#JWT存储的请求头
+jwt.tokenHeader=Authorization
+#JWT加解密使用的密钥
+jwt.secret=mySecret
+#JWT的超期限时间
+jwt.expiration=604800
+#JWT负载中拿到开头
+jwt.tokenHead="Bearer "
+#===JWT end===