technology

Language:JAVA + MySQL

Framework:SpringBoot + MyBatis + MyBatis-Plus + Shiro + JWT

Tools:Maven + IDEA + Navicat + PostMan

Making address:shiro+jwt

Database file

  • Location of file
    • SQL file

code

Create a JWT utility class called JwtUtlis

package com.inet.codebase.utlis;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;

/** * JWT tool class *@author Hcy
 * @sinceThe 2020-10-09 * /
public class JwtUtils {

    private static final String SING = "HCY";

    /** * generates token *@author HCY
     * @sinceThe 2020-10-09 * /
    public static String getToken(Map<String , String> map){
        // Set the expiration time to 7 days
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE , 7);

        / / create a Builder
        JWTCreator.Builder builder = JWT.create();
        // Traverses the map and sets the token parameters
        map.forEach((key,value)->{
            builder.withClaim(key,value);
        });
        // Set the expiration time
        String token = builder.withExpiresAt(instance.getTime())
                // Set the signature
                .sign(Algorithm.HMAC256(SING));

        return token;
    }

    /** * Verify that the token is valid *@author HCY
     * @sinceThe 2020-10-09 * /
    public static Boolean verify(String token){
        try {
            JWT.require(Algorithm.HMAC256(SING))
                    .build()
                    .verify(token);
            return true;
        } catch (JWTVerificationException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
        return false;
    }

    /** * Retrieve a token (String) *@author HCY
     * @sinceThe 2020-10-11 *@param token
     * @param search
     * @return* /
    public static String getString(String token,String search){
        try {
            DecodedJWT decodedJWT = JWT.decode(token);
            String data = decodedJWT.getClaim(search).asString();
            return data;
        } catch (JWTDecodeException e) {
            return null; }}/** * Obtain a certain token data (Integer) *@author HCY
     * @sinceThe 2020-10-11 *@param token
     * @param search
     * @return* /
    public static Integer getInteger(String token,String search){
        try {
            DecodedJWT decodedJWT = JWT.decode(token);
            Integer data = decodedJWT.getClaim(search).asInt();
            return data;
        } catch (JWTDecodeException e) {
            return null; }}/** * Retrieve one of the tokens (Double) *@author HCY
     * @sinceThe 2020-10-11 *@param token
     * @param search
     * @return* /
    public static Double getDouble(String token,String search){
        try {
            DecodedJWT decodedJWT = JWT.decode(token);
            Double data = decodedJWT.getClaim(search).asDouble();
            return data;
        } catch (JWTDecodeException e) {
            return null; }}/** * Obtain token information *@author HCY
     * @sinceThe 2020-10-09 * /
    public static DecodedJWT getTokenInfo(String token){
        //获取 token 得 DecodedJWT
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(SING))
                .build()
                .verify(token);

        returnverify; }}Copy the code

Create an encrypted string

package com.inet.codebase.utlis;

import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;

/**
 * ShiroMd5Utlis
 *
 * @author HCY
 * @since2020/10/11 * /
public class ShiroMd5Utlis {

    /** * encryption salt */
    private static final String SIGN = "HCY";

    /** * Encryption algorithm */
    private static final String ALG = "MD5";

    /** * hashes */
    private static final int HASH = 1024;

    /** * create an encrypted string *@param password
     * @return* /
    public static String encryption(String password){
        return newSimpleHash(ALG, password, ByteSource.Util.bytes(SIGN), HASH).toString(); }}Copy the code

Create a Token class for JWT

package com.inet.codebase.realm;

import org.apache.shiro.authc.AuthenticationToken;

/**
 * JwtToken
 *
 * @author HCY
 * @since2020/10/11 * /
public class JwtToken implements AuthenticationToken {
    /** * key */
    private String token;

    public JwtToken(String token) {
        this.token = token;
    }

    @Override
    public Object getPrincipal(a) {
        return token;
    }

    @Override
    public Object getCredentials(a) {
        returntoken; }}Copy the code

Create a Realm with your own name for the foreground

package com.inet.codebase.realm;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.inet.codebase.entity.User;
import com.inet.codebase.service.UserService;
import com.inet.codebase.utlis.JwtUtils;
import org.apache.ibatis.annotations.Mapper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
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.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * HcyRealm
 *
 * @author HCY
 * @since2020/10/11 * /
@Service
public class HcyRealm extends AuthorizingRealm {
    private static final Logger LOGGER  = LogManager.getLogger(HcyRealm.class);


    private UserService userService;

    @Resource
    public UserService setUserService(UserService userService) {
        return this.userService = userService;
    }

    /** ** /** *@param token
     * @return* /
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    /** * Permission authentication *@author HCY
     * @sinceThe 2020-10-11 *@param principalCollection
     * @return* /
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        / / to get
        String userId = JwtUtils.getString(principalCollection.toString(), "userId");
        User user = userService.getUserAndRole(userId);
        // Create simpleAuthorizationInfo object
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        // Add role permissions
        simpleAuthorizationInfo.addRole(user.getRoleName());
        // Data conversion
        Set<String> permission = new HashSet<>();
        // Loop insert
        for (com.inet.codebase.entity.Resource resource : user.getResourceList()){
            permission.add(resource.getPermissionName());
        }
        // Add resources
        simpleAuthorizationInfo.addStringPermissions(permission);
        return simpleAuthorizationInfo;
    }

    /** * Authentication *@author HCY
     * @sinceThe 2020-10-11 *@param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String token = (String) authenticationToken.getCredentials();
        // Get the account and password by decrypting
        String userId = JwtUtils.getString(token, "userId");
        // Make a query
        User user = userService.getById(userId);
        if (user == null) {throw new AuthenticationException("User does not exist");
        }
        if(! JwtUtils.verify(token)){throw new AuthenticationException("Token error");
        }
        return new SimpleAuthenticationInfo(token,token,"my_realm"); }}Copy the code

Create a filter for JWT

  1. Verify that the request header has a token((HttpServletRequest) request).getHeader("Token") ! = null
  2. If you have a token, execute Shiro’s login() method to commit the token to a Realm for verification; If there is no token, the current state is tourist state (or some other interface that does not require authentication)
package com.inet.codebase.filter;

import com.inet.codebase.realm.JwtToken;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * JwtFilter
 *
 * @author HCY
 * @since2020/10/11 * /
public class JwtFilter extends BasicHttpAuthenticationFilter {

    private Logger LOGGER = LoggerFactory.getLogger(this.getClass());

    /** * if there is a token, the token is checked; otherwise, the token is directly passed@author HCY
     * @param request
     * @param response
     * @param mappedValue
     * @return
     * @throws UnauthorizedException
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws UnauthorizedException {
        // Check whether the request header has a "Token"
        if (((HttpServletRequest) request).getHeader("Token") != null) {
            // If yes, log in to the executeLogin method to check whether the token is correct
            try {
                executeLogin(request, response);
                return true;
            } catch (Exception e) {
                / / token error
                return false; }}// If there is no Token in the request header, it may be a login operation or a visitor state access, without checking the Token, return true
        return true;
    }

    /** * Perform the login operation *@author HCY
     * @sinceThe 2020-10-11 *@param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String token = httpServletRequest.getHeader("Token");
        JwtToken jwtToken = new JwtToken(token);
        // Submit to realm for login. If it fails, it will throw an exception and be caught
        getSubject(request, response).login(jwtToken);
        // If no exception is thrown, the login is successful and true is returned
        return true;
    }

    /** * Determine whether the user wants to log in. * Check whether the header contains the Token field *@author HCY
     * @sinceThe 2020-10-11 * /
    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        HttpServletRequest req = (HttpServletRequest) request;
        String token = req.getHeader("Token");
        returntoken ! =null;
    }

    /** * cross-domain support */
    @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"));
        // An option request is first sent across domains
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }

    /** * Redirects unauthorized requests to /** */
    private void responseError(ServletResponse response, String message) {
        try {
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;
            // Set the encoding, otherwise Chinese characters will become empty strings when redirected
            message = URLEncoder.encode(message, "UTF-8");
            httpServletResponse.sendRedirect("/unauthorized/" + message);
        } catch(IOException e) { LOGGER.error(e.getMessage()); }}}Copy the code

Create a Shiro configuration file

package com.inet.codebase.config;

import com.inet.codebase.filter.JwtFilter;
import com.inet.codebase.realm.HcyRealm;
import org.apache.shiro.mgt.DefaultSessionStorageEvaluator;
import org.apache.shiro.mgt.DefaultSubjectDAO;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
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;
/**
 * ShiroConfig
 *
 * @author HCY
 * @since2020/10/11 * /
@Configuration
public class ShiroConfig {
    /** * if the request header contains a token, use the token to login and go to Realm to verify */
    @Bean
    public ShiroFilterFactoryBean factory(SecurityManager securityManager) {
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();

        // Add your own filter and name it JWT
        Map<String, Filter> filterMap = new LinkedHashMap<>();
        // Set our custom JWT filter
        filterMap.put("jwt".new JwtFilter());
        factoryBean.setFilters(filterMap);
        factoryBean.setSecurityManager(securityManager);
        // Set the unrestricted jump url;
        factoryBean.setUnauthorizedUrl("/ Unauthorized/No permission");
        Map<String, String> filterRuleMap = new HashMap<>();
        // All requests go through our own JWT Filter
        filterRuleMap.put("/ * *"."jwt");
        // Access/Unauthorized /** Not through JWTFilter
        filterRuleMap.put("/unauthorized/**"."anon");
        factoryBean.setFilterChainDefinitionMap(filterRuleMap);
        return factoryBean;
    }

    /** * inject securityManager */
    @Bean
    public SecurityManager securityManager(HcyRealm hcyRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        // Set a custom realm.
        securityManager.setRealm(hcyRealm);

        /* * Close shiro's built-in session. See the document * 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;
    }

    /** * Add annotation support */
    @Bean
    public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator(a) {
        DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
        // Enforce the use of cglib to prevent duplicate proxies and problems that can cause proxy errors
        // https://zhuanlan.zhihu.com/p/29161098
        defaultAdvisorAutoProxyCreator.setProxyTargetClass(true);
        return defaultAdvisorAutoProxyCreator;
    }

    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
        advisor.setSecurityManager(securityManager);
        return advisor;
    }

    @Bean
    public LifecycleBeanPostProcessor lifecycleBeanPostProcessor(a) {
        return newLifecycleBeanPostProcessor(); }}Copy the code

Create an exception catching class

  • When we write an interface with the above annotations, if the request does not carry a token or carries a token but permission authentication fails, an UnauthenticatedException will be reported. But I handled these exceptions centrally in the ExceptionController class

package com.inet.codebase.config;

import com.inet.codebase.utlis.Result;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/** * ExceptionConfig * Catch exception *@author HCY
 * @since2020/10/11 * /
@RestControllerAdvice
public class ExceptionConfig {

    /** * Catch Shiro's exception *@author HCY
     * @sinceThe 2020-10-11 *@paramException Exception element *@return Result
     */
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(ShiroException.class)
    public Result handle401(ShiroException exception){
        return new Result(exception.getMessage(),"Permission exception".104);
    }

    /** * Catch an UnauthorizedException *@author HCY
     * @sinceThe 2020-10-11 *@return Result
     */
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(UnauthorizedException.class)
    public Result handel401(a){
        return new Result("No permission"."Permission exception".104);
    }

    /** * Catch all other exceptions *@author HCY
     * @sinceThe 2020-10-11 *@return Result
     */
    @ExceptionHandler(Exception.class)
    public Result globalException(HttpServletRequest request, Throwable ex) {
        System.out.println(request);
        return new Result(getStatus(request).value(), ex.getMessage(), 104);
    }

    private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        returnHttpStatus.valueOf(statusCode); }}Copy the code

Control annotations for permissions

// Have the admin role to access
@RequiresRoles("admin")
// The user or admin role can be accessed
@RequiresRoles(logical = Logical.OR, value = {"user", "admin"})
// With VIP and normal permissions
@RequiresPermissions(logical = Logical.AND, value = {"edit", "view"})

// You have the user or admin role and the VIP permission to access it
@GetMapping("/getVipMessage")
@RequiresRoles(logical = Logical.OR, value = {"user", "admin"})
@RequiresPermissions("edit")
public ResultMap getVipMessage(a) {
    return resultMap.success().code(200).message("Edit information obtained successfully!");
}
Copy the code