https://blog.csdn.net/qq_23250633/article/details/81063762
當我們要把服務器做成無狀態(tài)時(即服務器端不會保存session),這里我們就可以用到JWT。
為什么使用JWT?
1.簡潔(Compact): 可以通過URL,POST參數(shù)或者在HTTP header發(fā)送,因為數(shù)據(jù)量小,傳輸速度也很快。
2.自包含(Self-contained):負載中包含了所有用戶所需要的信息,避免了多次查詢數(shù)據(jù)庫。
3.安全(security): 與簡單的JSON相比,XML和XML數(shù)字簽名會引入復雜的安全漏洞。
認證原理
1.用戶登陸之后,使用密碼對賬號進行簽名生成并返回token并設置過期時間;
2.將token保存到本地,并且每次發(fā)送請求時都在header上攜帶token。
3.shiro過濾器攔截到請求并獲取header中的token,并提交到自定義realm的doGetAuthenticationInfo方法。
4.通過jwt解碼獲取token中的用戶名,從數(shù)據(jù)庫中查詢到密碼之后根據(jù)密碼生成jwt效驗器并對token進行驗證。
OK,介紹完后上代碼。
JWT
引入pom
? ? <!--JWT-->
? ? <dependency>
? ? <groupId>com.auth0</groupId>
? ? <artifactId>java-jwt</artifactId>
? ? <version>3.4.0</version>
? ? </dependency>
首先我們需要自定義一個對象用來包裝token。
JwtToken
? ? package com.style.orange.shiro;
? ? import org.apache.shiro.authc.AuthenticationToken;
? ? /**
? ? * @author Mr.Li
? ? * @create 2018-07-12 15:19
? ? * @desc
? ? **/
? ? public class JwtToken implements AuthenticationToken {
? ? ? ? private String token;
? ? ? ? public JwtToken(String token) {
? ? ? ? ? ? this.token = token;
? ? ? ? }
? ? ? ? @Override
? ? ? ? public Object getPrincipal() {
? ? ? ? ? ? return token;
? ? ? ? }
? ? ? ? @Override
? ? ? ? public Object getCredentials() {
? ? ? ? ? ? return token;
? ? ? ? }
? ? }
再寫一個工具類用來進行簽名和效驗Token
JwtToken
? ? package com.style.orange.utils;
? ? import com.auth0.jwt.JWT;
? ? import com.auth0.jwt.JWTVerifier;
? ? import com.auth0.jwt.algorithms.Algorithm;
? ? import com.auth0.jwt.exceptions.JWTDecodeException;
? ? import com.auth0.jwt.interfaces.DecodedJWT;
? ? import java.util.Date;
? ? /**
? ? * @author Mr.Li
? ? * @create 2018-07-12 14:23
? ? * @desc JWT工具類
? ? **/
? ? public class JwtUtil {
? ? ? ? private static final long EXPIRE_TIME = 5 * 60 * 1000;
? ? ? ? /**
? ? ? ? * 校驗token是否正確
? ? ? ? *
? ? ? ? * @param token? 密鑰
? ? ? ? * @param secret 用戶的密碼
? ? ? ? * @return 是否正確
? ? ? ? */
? ? ? ? public static boolean verify(String token, String username, String secret) {
? ? ? ? ? ? try {
? ? ? ? ? ? ? ? //根據(jù)密碼生成JWT效驗器
? ? ? ? ? ? ? ? Algorithm algorithm = Algorithm.HMAC256(secret);
? ? ? ? ? ? ? ? JWTVerifier verifier = JWT.require(algorithm)
? ? ? ? ? ? ? ? ? ? ? ? .withClaim("username", username)
? ? ? ? ? ? ? ? ? ? ? ? .build();
? ? ? ? ? ? ? ? //效驗TOKEN
? ? ? ? ? ? ? ? DecodedJWT jwt = verifier.verify(token);
? ? ? ? ? ? ? ? return true;
? ? ? ? ? ? } catch (Exception exception) {
? ? ? ? ? ? ? ? return false;
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? /**
? ? ? ? * 獲得token中的信息無需secret解密也能獲得
? ? ? ? *
? ? ? ? * @return token中包含的用戶名
? ? ? ? */
? ? ? ? public static String getUsername(String token) {
? ? ? ? ? ? try {
? ? ? ? ? ? ? ? DecodedJWT jwt = JWT.decode(token);
? ? ? ? ? ? ? ? return jwt.getClaim("username").asString();
? ? ? ? ? ? } catch (JWTDecodeException e) {
? ? ? ? ? ? ? ? return null;
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? /**
? ? ? ? * 生成簽名,5min后過期
? ? ? ? *
? ? ? ? * @param username 用戶名
? ? ? ? * @param secret? 用戶的密碼
? ? ? ? * @return 加密的token
? ? ? ? */
? ? ? ? public static String sign(String username, String secret) {
? ? ? ? ? ? Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
? ? ? ? ? ? Algorithm algorithm = Algorithm.HMAC256(secret);
? ? ? ? ? ? // 附帶username信息
? ? ? ? ? ? return JWT.create()
? ? ? ? ? ? ? ? ? ? .withClaim("username", username)
? ? ? ? ? ? ? ? ? ? .withExpiresAt(date)
? ? ? ? ? ? ? ? ? ? .sign(algorithm);
? ? ? ? }
? ? }
前面認證原理說到我們要使用shiro來攔截token,那就需要我們自己寫一個jwt過濾器來作為shiro的過濾器。
JwtFilter
? ? import com.style.orange.shiro.JwtToken;
? ? import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
? ? import org.springframework.http.HttpStatus;
? ? import org.springframework.web.bind.annotation.RequestMethod;
? ? import javax.servlet.ServletRequest;
? ? import javax.servlet.ServletResponse;
? ? import javax.servlet.http.HttpServletRequest;
? ? import javax.servlet.http.HttpServletResponse;
? ? /**
? ? * @author Mr.Li
? ? * @create 2018-07-12 15:56
? ? * @desc
? ? **/
? ? public class JwtFilter extends BasicHttpAuthenticationFilter {
? ? ? ? /**
? ? ? ? * 執(zhí)行登錄認證
? ? ? ? *
? ? ? ? * @param request
? ? ? ? * @param response
? ? ? ? * @param mappedValue
? ? ? ? * @return
? ? ? ? */
? ? ? ? @Override
? ? ? ? protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
? ? ? ? ? ? try {
? ? ? ? ? ? ? ? executeLogin(request, response);
? ? ? ? ? ? ? ? return true;
? ? ? ? ? ? } catch (Exception e) {
? ? ? ? ? ? ? ? return false;
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? /**
? ? ? ? *
? ? ? ? */
? ? ? ? @Override
? ? ? ? protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
? ? ? ? ? ? HttpServletRequest httpServletRequest = (HttpServletRequest) request;
? ? ? ? ? ? String token = httpServletRequest.getHeader("Authorization");
? ? ? ? ? ? JwtToken jwtToken = new JwtToken(token);
? ? ? ? ? ? // 提交給realm進行登入,如果錯誤他會拋出異常并被捕獲
? ? ? ? ? ? getSubject(request, response).login(jwtToken);
? ? ? ? ? ? // 如果沒有拋出異常則代表登入成功,返回true
? ? ? ? ? ? return true;
? ? ? ? }
? ? ? ? /**
? ? ? ? * 對跨域提供支持
? ? ? ? */
? ? ? ? @Override
? ? ? ? protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
? ? ? ? ? ? HttpServletRequest httpServletRequest = (HttpServletRequest) request;
? ? ? ? ? ? HttpServletResponse httpServletResponse = (HttpServletResponse) response;
? ? ? ? ? ? httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
? ? ? ? ? ? httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
? ? ? ? ? ? httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
? ? ? ? ? ? // 跨域時會首先發(fā)送一個option請求,這里我們給option請求直接返回正常狀態(tài)
? ? ? ? ? ? if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
? ? ? ? ? ? ? ? httpServletResponse.setStatus(HttpStatus.OK.value());
? ? ? ? ? ? ? ? return false;
? ? ? ? ? ? }
? ? ? ? ? ? return super.preHandle(request, response);
? ? ? ? }
? ? }
Shiro
引入pom
? ? <!--shiro-->
? ? <dependency>
? ? <groupId>org.apache.shiro</groupId>
? ? <artifactId>shiro-spring</artifactId>
? ? <version>1.4.0</version>
? ? </dependency>
準備自定義Realm
MyRealm
? ? package com.style.orange.shiro;
? ? import com.style.orange.model.SysUser;
? ? import com.style.orange.service.SysUserService;
? ? import com.style.orange.utils.JwtUtil;
? ? import org.apache.shiro.authc.AuthenticationException;
? ? import org.apache.shiro.authc.AuthenticationInfo;
? ? import org.apache.shiro.authc.AuthenticationToken;
? ? import org.apache.shiro.authc.SimpleAuthenticationInfo;
? ? import org.apache.shiro.authz.AuthorizationInfo;
? ? import org.apache.shiro.authz.SimpleAuthorizationInfo;
? ? import org.apache.shiro.realm.AuthorizingRealm;
? ? import org.apache.shiro.subject.PrincipalCollection;
? ? import org.springframework.beans.factory.annotation.Autowired;
? ? import org.springframework.stereotype.Component;
? ? /**
? ? * @author Mr.Li
? ? * @create 2018-07-12 15:23
? ? * @desc
? ? **/
? ? @Component
? ? public class MyRealm extends AuthorizingRealm {
? ? ? ? @Autowired
? ? ? ? private SysUserService sysUserService;
? ? ? ? /**
? ? ? ? * 必須重寫此方法,不然Shiro會報錯
? ? ? ? */
? ? ? ? @Override
? ? ? ? public boolean supports(AuthenticationToken token) {
? ? ? ? ? ? return token instanceof JwtToken;
? ? ? ? }
? ? ? ? /**
? ? ? ? * 只有當需要檢測用戶權限的時候才會調用此方法,例如checkRole,checkPermission之類的
? ? ? ? */
? ? ? ? @Override
? ? ? ? protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
? ? ? ? ? ? String username = JwtUtil.getUsername(principals.toString());
? ? ? ? ? ? SysUser user = sysUserService.findByUserName(username);
? ? ? ? ? ? SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
? ? ? ? ? ? return simpleAuthorizationInfo;
? ? ? ? }
? ? ? ? /**
? ? ? ? * 默認使用此方法進行用戶名正確與否驗證,錯誤拋出異常即可。
? ? ? ? */
? ? ? ? @Override
? ? ? ? protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
? ? ? ? ? ? String token = (String) auth.getCredentials();
? ? ? ? ? ? // 解密獲得username,用于和數(shù)據(jù)庫進行對比
? ? ? ? ? ? String username = JwtUtil.getUsername(token);
? ? ? ? ? ? if (username == null) {
? ? ? ? ? ? ? ? throw new AuthenticationException("token無效");
? ? ? ? ? ? }
? ? ? ? ? ? SysUser userBean = sysUserService.findByUserName(username);
? ? ? ? ? ? if (userBean == null) {
? ? ? ? ? ? ? ? throw new AuthenticationException("用戶不存在!");
? ? ? ? ? ? }
? ? ? ? ? ? if (!JwtUtil.verify(token, username, userBean.getPassword())) {
? ? ? ? ? ? ? ? throw new AuthenticationException("用戶名或密碼錯誤");
? ? ? ? ? ? }
? ? ? ? ? ? return new SimpleAuthenticationInfo(token, token, "my_realm");
? ? ? ? }
? ? }
ShiroConfig
? ? package com.style.orange.shiro;
? ? import com.style.orange.filter.JwtFilter;
? ? import org.apache.shiro.mgt.DefaultSessionStorageEvaluator;
? ? import org.apache.shiro.mgt.DefaultSubjectDAO;
? ? import org.apache.shiro.mgt.SecurityManager;
? ? import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
? ? import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
? ? import org.springframework.context.annotation.Bean;
? ? import org.springframework.context.annotation.Configuration;
? ? import javax.servlet.Filter;
? ? import java.util.HashMap;
? ? import java.util.LinkedHashMap;
? ? import java.util.Map;
? ? /**
? ? * @author: PENG
? ? * @date: 2018/2/7
? ? * @description: shiro 配置類
? ? */
? ? @Configuration
? ? public class ShiroConfig {
? ? ? ? @Bean("shiroFilter")
? ? ? ? public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) {
? ? ? ? ? ? ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
? ? ? ? ? ? shiroFilterFactoryBean.setSecurityManager(securityManager);
? ? ? ? ? ? //攔截器
? ? ? ? ? ? Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
? ? ? ? ? ? // 配置不會被攔截的鏈接 順序判斷
? ? ? ? ? ? filterChainDefinitionMap.put("/login/**", "anon");
? ? ? ? ? ? filterChainDefinitionMap.put("/**.js", "anon");
? ? ? ? ? ? filterChainDefinitionMap.put("/druid/**", "anon");
? ? ? ? ? ? filterChainDefinitionMap.put("/swagger**/**", "anon");
? ? ? ? ? ? filterChainDefinitionMap.put("/webjars/**", "anon");
? ? ? ? ? ? filterChainDefinitionMap.put("/v2/**", "anon");
? ? ? ? ? ? // 添加自己的過濾器并且取名為jwt
? ? ? ? ? ? Map<String, Filter> filterMap = new HashMap<String, Filter>(1);
? ? ? ? ? ? filterMap.put("jwt", new JwtFilter());
? ? ? ? ? ? shiroFilterFactoryBean.setFilters(filterMap);
? ? ? ? ? ? //<!-- 過濾鏈定義,從上向下順序執(zhí)行,一般將/**放在最為下邊
? ? ? ? ? ? filterChainDefinitionMap.put("/**", "jwt");
? ? ? ? ? ? //未授權界面;
? ? ? ? ? ? shiroFilterFactoryBean.setUnauthorizedUrl("/403");
? ? ? ? ? ? shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
? ? ? ? ? ? return shiroFilterFactoryBean;
? ? ? ? }
? ? ? ? @Bean("securityManager")
? ? ? ? public SecurityManager securityManager(MyRealm myRealm) {
? ? ? ? ? ? DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
? ? ? ? ? ? securityManager.setRealm(myRealm);
? ? ? ? ? ? /*
? ? ? ? ? ? * 關閉shiro自帶的session,詳情見文檔
? ? ? ? ? ? * http://shiro.apache.org/session-management.html#SessionManagement-StatelessApplications%28Sessionless%29
? ? ? ? ? ? */
? ? ? ? ? ? DefaultSubjectDAO subjectDAO = new DefaultSubjectDAO();
? ? ? ? ? ? DefaultSessionStorageEvaluator defaultSessionStorageEvaluator = new DefaultSessionStorageEvaluator();
? ? ? ? ? ? defaultSessionStorageEvaluator.setSessionStorageEnabled(false);
? ? ? ? ? ? subjectDAO.setSessionStorageEvaluator(defaultSessionStorageEvaluator);
? ? ? ? ? ? securityManager.setSubjectDAO(subjectDAO);
? ? ? ? ? ? return securityManager;
? ? ? ? }
? ? }
OK,接下來我們進行測試,我這里集成了swagger2,測試起來比較方便。
如圖紅色標注就是返回的token,之后我把token放到請求的header中訪問就可以了通過了。
---------------------
作者:小陽style
來源:CSDN
原文:https://blog.csdn.net/qq_23250633/article/details/81063762
版權聲明:本文為博主原創(chuàng)文章,轉載請附上博文鏈接!