shiro、jwt、redis整合

shiro、jwt、redis整合shiro、jwt、redis、SpringBoot整合

shiro、jwt、redis整合

shiro、jwt、redis整合

一、步骤

1.导入坐标

<!--redis-->
<dependency>
    <groupId>org.crazycake</groupId>
    <artifactId>shiro-redis-spring-boot-starter</artifactId>
    <version>3.2.1</version>
</dependency>
 <!-- jwt -->
 <dependency>
     <groupId>io.jsonwebtoken</groupId>
     <artifactId>jjwt</artifactId>
     <version>0.9.1</version>
</dependency>

2.编写ShiroConfig

目的:实现session共享

session共享

HTTP协议(1.1)是无状态的,所以服务器在需要识别用户访问的时候,就要做相应的记录用于跟踪用户操作,这个实现机制就是Session。当一个用户第一次访问服务器的时候,服务器就会为用户创建一个Session,每个Session都有一个唯一的SessionId(应用级别)用于标识用户。

因此要使用shiro继承redis

使用redis管理session能够方便的实现session集群,并且在服务重启(或服务器重启)时不会丢失session。

package com.gyb.config;

import com.gyb.shiro.AccountRealm;
import com.gyb.shiro.JwtFilter;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.crazycake.shiro.RedisCacheManager;
import org.crazycake.shiro.RedisSessionDAO;
import org.springframework.beans.factory.annotation.Autowired;
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;

@Configuration
public class ShiroConfig {

    @Autowired
    JwtFilter jwtFilter;

    @Bean
    public SessionManager sessionManager(RedisSessionDAO redisSessionDAO) {
        DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();

        sessionManager.setSessionDAO(redisSessionDAO);
        return sessionManager;
    }

    @Bean
    public DefaultWebSecurityManager securityManager(AccountRealm accountRealm,
                                                   SessionManager sessionManager,
                                                   RedisCacheManager redisCacheManager) {

        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(accountRealm);

        securityManager.setSessionManager(sessionManager);

        securityManager.setCacheManager(redisCacheManager);
        return securityManager;
    }

    @Bean
    public ShiroFilterChainDefinition shiroFilterChainDefinition() {
        DefaultShiroFilterChainDefinition chainDefinition = new DefaultShiroFilterChainDefinition();

        Map<String, String> filterMap = new LinkedHashMap<>();

        //将所有的过滤交给自定义的jwt来做
        filterMap.put("/**", "jwt");
        chainDefinition.addPathDefinitions(filterMap);
        return chainDefinition;
    }

    @Bean("shiroFilterFactoryBean")
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager,
                                                         ShiroFilterChainDefinition shiroFilterChainDefinition) {
        ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
        shiroFilter.setSecurityManager(securityManager);

        Map<String, Filter> filters = new HashMap<>();
        filters.put("jwt", jwtFilter);
        shiroFilter.setFilters(filters);

        Map<String, String> filterMap = shiroFilterChainDefinition.getFilterChainMap();

        shiroFilter.setFilterChainDefinitionMap(filterMap);
        return shiroFilter;
    }

}

3.解决跨域问题

(后面还要在过滤器解决: 因为过滤器在拦截器之前执行,可能直接被过滤掉)

步骤分析
spring初始化时加载corsMapping的配置信息并注册到实现于IOC容器,具体实例以及信息封装:RequestMappingHandlerMapping -> corsConfigurationSource -> corsConfigurations

接口访问时,在DispatchServlet中doDispatch方法里,通过getHandler拿到HandlerExecutionChain,cors配置信息封装在HandlerExecutionChain实例中,在getHandler方法中的this.handlerMappings集合中可以看到之前注册的RequestMappingHandlerMapping

package com.gyb.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 解决跨域问题
 */
@Configuration
public class CorsConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
                // 允许发送Cookie
                .allowCredentials(true)
                .maxAge(3600)
                .allowedHeaders("*");
    }
}

4.创建shiro包

在包中创建

AccountProfile: 重写doGetAuthenticationInfo认证方法时,返回的第一个参数

AccountRealm: 自定义域类(主要是实现认证和授权两个方法)

*** JwtFifter:** 1.将请求中的token存储,(使用JwtToken类)

​ 2.判断token是否已经失效,没失效则执行executeLogin,然后一步步走到自己编写的域类里实现的两个方法

​ 3.重写登录失败方法,将错误信息返回 :Result result = Result.fail(throwable.getMessage());

​ 4.解决跨域问题

JwtToken:将request域中Authorization的value值封装。

shiro、jwt、redis整合

4.1 创建AccountProfile类

package com.gyb.shiro;

import lombok.Data;

import java.io.Serializable;

@Data
public class AccountProfile implements Serializable {

    private Long id;

    private String username;

    private String avatar;

    private String email;

}

4.2 创建AccountRealm类

package com.gyb.shiro;

import cn.hutool.core.bean.BeanUtil;
import com.gyb.entity.User;
import com.gyb.service.UserService;
import com.gyb.util.JwtUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class AccountRealm extends AuthorizingRealm {

    @Autowired
    JwtUtils jwtUtils;

    @Autowired
    UserService userService;

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

    /**
     * 授权
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    /**
     * 认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        JwtToken jwtToken = (JwtToken) token;

        String userId = jwtUtils.getClaimByToken((String) jwtToken.getPrincipal()).getSubject();

        User user = userService.getById(Long.valueOf(userId));
        if (user == null) {
            throw new UnknownAccountException("账户不存在");
        }

        if (user.getStatus() == -1) {
            throw new LockedAccountException("账户已被锁定");
        }

        AccountProfile profile = new AccountProfile();
        BeanUtil.copyProperties(user, profile);

        return new SimpleAuthenticationInfo(profile, jwtToken.getCredentials(), getName());
    }
}

4.3 创建JwtFifter类

package com.gyb.shiro;

import cn.hutool.json.JSONUtil;
import com.gyb.common.lang.Result;
import com.gyb.util.JwtUtils;
import io.jsonwebtoken.Claims;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExpiredCredentialsException;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
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;

@Component
public class JwtFilter extends AuthenticatingFilter {

    @Autowired
    JwtUtils jwtUtils;

    @Override
    protected AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String jwt = request.getHeader("Authorization");
        if(!StringUtils.hasLength(jwt) ) {
            return null;
        }

        return new JwtToken(jwt);
    }

    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String jwt = request.getHeader("Authorization");
        if(!StringUtils.hasLength(jwt)) {
            return true;
        } else {

            // 校验jwt
            Claims claim = jwtUtils.getClaimByToken(jwt);
            if(claim == null || jwtUtils.isTokenExpired(claim.getExpiration())) {
                throw new ExpiredCredentialsException("token已失效,请重新登录");
            }

            // 执行登录
            return executeLogin(servletRequest, servletResponse);
        }
    }

    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {

        HttpServletResponse httpServletResponse = (HttpServletResponse) response;

        Throwable throwable = e.getCause() == null ? e : e.getCause();
        Result result = Result.fail(throwable.getMessage());
        String json = JSONUtil.toJsonStr(result);

        try {
            httpServletResponse.getWriter().print(json);
        } catch (IOException ioException) {

        }
        return false;
    }

    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {

        HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
        HttpServletResponse httpServletResponse = WebUtils.toHttp(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"));
        // 跨域时会首先发送一个OPTIONS请求,这里我们给OPTIONS请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(org.springframework.http.HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }
}

4.4 创建JwtToken类

package com.gyb.shiro;

import org.apache.shiro.authc.AuthenticationToken;

public class JwtToken implements AuthenticationToken {

    private String token;

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

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

    @Override
    public Object getCredentials() {
        return token;
    }
}

5.创建util包

shiro、jwt、redis整合

JwtUtil: 1.在用户调用登录接口时,生成jwt

​ 2.获取token的Claims对象的方法,Claims大家可以理解为jwt明文的报文体结构,在验证的时候可以通过获取其到当前请求的用 户payload信息。

​ 3.判定token是否过期

ShiroUtil: 只有一行代码,我是为了简便= =,(也可以不写此类)

​ 用于获取当前用户的Principal

5.1 JwtUtil

package com.gyb.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * jwt工具类
 */
@Slf4j
@Data
@Component
@ConfigurationProperties(prefix = "gyb.jwt")
public class JwtUtils {

    private String secret;
    private long expire;
    private String header;

    /**
     * 生成jwt token
     */
    public String generateToken(long userId) {
        Date nowDate = new Date();
        //过期时间
        Date expireDate = new Date(nowDate.getTime() + expire * 1000);

        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(userId+"")
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    public Claims getClaimByToken(String token) {
        try {
            return Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        }catch (Exception e){
            log.debug("validate is token error ", e);
            return null;
        }
    }

    /**
     * token是否过期
     * @return  true:过期
     */
    public boolean isTokenExpired(Date expiration) {
        return expiration.before(new Date());
    }
}

5.2 ShiroUtil

package com.gyb.util;import com.gyb.shiro.AccountProfile;import org.apache.shiro.SecurityUtils;public class ShiroUtil {    public static AccountProfile getProfile() {        return (AccountProfile) SecurityUtils.getSubject().getPrincipal();    }}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
转载请注明出处: https://daima100.com/5828.html

(0)
上一篇 2023-04-23
下一篇 2023-04-23

相关推荐

  • csv批量导入mysql命令「建议收藏」

    csv批量导入mysql命令「建议收藏」参考一下逻辑,最终代码: 需要将csv放到 /var/lib/mysql/你的数据库/ 目录下,否则会报错 ERROR 13 (HY000): Can’t get stat of ‘/root/bb…

    2023-03-22
    147
  • PostgreSQL免费公开课第17期-full-page写操作机制

    PostgreSQL免费公开课第17期-full-page写操作机制十七、PostgreSQL full-page写操作机制 1、阐述full-page写操作特点 2、为什么要full-page写操作 3、什么时候进行full-page写操作 4、与其它数据库类似技…

    2023-03-22
    152
  • Python 变量:用于存储数据的标识符

    Python 变量:用于存储数据的标识符Python 是一种高级编程语言,它提供了丰富的数据类型,其中最基本的就是变量。在Python中,变量用于存储数据,可以是数字、字符串、列表、元组、字典等。变量名需要符合一定的规则,同时一个变量可以赋值为不同的数据类型。

    2024-03-26
    80
  • 数据库(mysql)基础操作「建议收藏」

    数据库(mysql)基础操作「建议收藏」声明: 1)仅作为个人学习,如有冒犯,告知速删! 2)不想误导,如有错误,不吝指教! 分隔符 DDL(数据定义语言) >建库,建表 DML(数据操作语言) >对表中的记录操作增删改查 DQ

    2023-03-12
    162
  • mysql8.0主从_mysql主从搭建

    mysql8.0主从_mysql主从搭建主从原理 master服务器将数据的改变记录二进制binlog日志,当master上的数据发生改变时,则将其改变写入二进制日志中;slave服务器会在一定时间间隔内对master二进制日志进行探测其是

    2023-06-11
    152
  • oracle使用expdp定时备份数据库「建议收藏」

    oracle使用expdp定时备份数据库「建议收藏」在测试环境中我们需要每天备份oracle中的数据,以便错误的操作、测试或者覆盖其中有价值的数据,暂时不考虑生产环境的全量增量备份策略,本文只是简单的oracle数据库使用expdp命令设置定时任务备份

    2023-02-06
    151
  • mysql-备份与恢复-03「建议收藏」

    mysql-备份与恢复-03「建议收藏」1.mysql二进制包安装 二进制包下载 https://downloads.mysql.com/archives/community/ [root@vm1 src]# ll total 62870…

    2023-04-05
    158
  • python越来越火_python一点都不简单

    python越来越火_python一点都不简单学一门语言,可能大部分人还是跟我一样,初衷还是想拿一份不错的收入,从事个朝阳行业。普通python工资在10-13K居多,如果有几年经验,能入行机器学习与数据分析,则工资突破20K还是可以的,将超过很多人的工资。

    2023-08-25
    142

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注