登录 jwt ,filter

 

 cookie 在请求头中叫做cookie,在响应头中叫set-cookie

 @GetMapping("/c1")
    public Result cookie1(HttpServletResponse resp){
        resp.addCookie(new Cookie("login_name","itheima"));
        return Result.success();
    }
    @GetMapping("/c2")
    public Result cookie2(HttpServletRequest request){
        Cookie [] cookies = request.getCookies();
        for(Cookie cookie : cookies){
            if(cookie.getName().equals("login_username")){
                System.out.println("login_username" + cookie.getValue());
            }
        }
        return Result.success();
    }

 

当前所在位置和请求位置,然后从3维度来判断是否是跨哉请求,只要有一个不同就属于 

 session基于cookie实现

@GetMapping("/s1")
    public Result session1(HttpSession session){
        session.setAttribute("loginUser", "tom");
        return Result.success();
    }

    @GetMapping("/s2")
    public Result session2(HttpServletRequest request){
        HttpSession session = request.getSession();
        Object loginUser = session.getAttribute("loginUser");
        return Result.success(loginUser);
    }

 

 

 

 拦截器

Filter

 

@Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse)servletResponse;
        //获取请求的url
        String url = req.getRequestURL().toString();
        //判断是否包含登录
        if(url.contains("login")){
            filterChain.doFilter(req, resp);
            return;
        }
        //获取请求头中的令牌
        String jwt = req.getHeader("token");
        if(!StringUtils.hasLength(jwt)){ //如果为空
            Result errorRet = Result.error("NOT_LOGIN");
            //阿里巴巴fastJson
            String notLogin = JSONObject.toJSONString(errorRet);
            //将json字符串返回给浏览器
            resp.getWriter().write(notLogin);
        }
        //解析token,如果解析失败,返回错误结果
        try {
            JwtUtils.parseJwt(jwt);
        } catch(Exception e){
            Result errorRet = Result.error("NOT_LOGIN");
            //阿里巴巴fastJson
            String notLogin = JSONObject.toJSONString(errorRet);
            //将json字符串返回给浏览器
            resp.getWriter().write(notLogin);
            return;
        }
        //放行
        filterChain.doFilter(req, resp);
    }

 

 

 

 

在Spring Boot中实现JWT登录验证可以结合Shiro和Redis来实现。下面是一个简单的示例代码: 1. 首先,需要添加相关依赖: ```xml <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring-boot-starter</artifactId> <version>1.7.1</version> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.1</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 2. 创建一个JWT工具类,用于生成和解析JWT: ```java import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import java.util.Date; @Component public class JwtUtils { @Value("${jwt.secret}") private String secret; @Value("${jwt.expiration}") private Long expiration; public String generateToken(String username) { Date now = new Date(); Date expireDate = new Date(now.getTime() + expiration * 1000); return Jwts.builder() .setSubject(username) .setIssuedAt(now) .setExpiration(expireDate) .signWith(SignatureAlgorithm.HS512, secret) .compact(); } public String getUsernameFromToken(String token) { Claims claims = Jwts.parser() .setSigningKey(secret) .parseClaimsJws(token) .getBody(); return claims.getSubject(); } public boolean validateToken(String token) { try { Jwts.parser().setSigningKey(secret).parseClaimsJws(token); return true; } catch (Exception e) { return false; } } } ``` 3. 创建一个自定义的Realm类,用于处理登录验证和权限控制: ```java import org.apache.shiro.authc.*; import org.apache.shiro.realm.AuthenticatingRealm; import org.springframework.beans.factory.annotation.Autowired; public class JwtRealm extends AuthenticatingRealm { @Autowired private JwtUtils jwtUtils; @Override public boolean supports(AuthenticationToken token) { return token instanceof JwtToken; } @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { JwtToken jwtToken = (JwtToken) authenticationToken; String token = jwtToken.getToken(); if (!jwtUtils.validateToken(token)) { throw new IncorrectCredentialsException("Token无效"); } String username = jwtUtils.getUsernameFromToken(token); // TODO: 根据用户名查询用户信息 return new SimpleAuthenticationInfo(username, token, getName()); } } ``` 4. 创建一个自定义的Filter类,用于处理JWT的验证和授权: ```java import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter; import org.springframework.beans.factory.annotation.Autowired; 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; public class JwtFilter extends BasicHttpAuthenticationFilter { @Autowired private JwtUtils jwtUtils; @Override protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) { HttpServletRequest httpServletRequest = (HttpServletRequest) request; String token = httpServletRequest.getHeader("Authorization"); if (token != null && token.startsWith("Bearer ")) { token = token.substring(7); } if (jwtUtils.validateToken(token)) { return true; } throw new UnauthorizedException("Token无效"); } @Override protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception { HttpServletResponse httpServletResponse = (HttpServletResponse) response; httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value()); return false; } } ``` 5. 在Spring Boot的配置文件中配置相关参数: ```properties # JWT配置 jwt.secret=your_secret_key jwt.expiration=3600 ``` 6. 在Spring Boot的配置类中配置Shiro和Redis: ```java import org.apache.shiro.mgt.SecurityManager; import org.apache.shiro.realm.Realm; import org.apache.shiro.session.mgt.SessionManager; import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO; import org.apache.shiro.session.mgt.eis.SessionDAO; import org.apache.shiro.session.mgt.eis.SessionIdGenerator; import org.apache.shiro.session.mgt.eis.SimpleSessionIdGenerator; import org.apache.shiro.session.mgt.eis.SessionIdCookie; import org.apache.shiro.session.mgt.eis.SessionIdCookieEnabled; import org.apache.shiro.session.mgt.eis.SessionIdCookieSessionFactory; import org.apache.shiro.session.mgt.eis.SessionIdUrlRewritingEnabled; import org.apache.shiro.session.mgt.eis.SessionManagerEnabled; import org.apache.shiro.session.mgt.eis.SessionValidationScheduler; import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerEnabled; import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerFactory; import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerSessionFactory; import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerSessionManager; import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerSessionManagerEnabled; import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerSessionFactoryEnabled; import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerSessionFactoryEnabledEnabled; import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerSessionFactoryEnabledEnabledEnabled; import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerSessionFactoryEnabledEnabledEnabledEnabled; import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerSessionFactoryEnabledEnabledEnabledEnabledEnabled; import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerSessionFactoryEnabledEnabledEnabledEnabledEnabledEnabled; import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerSessionFactoryEnabledEnabledEnabledEnabledEnabledEnabledEnabled; import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerSessionFactoryEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabled; import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerSessionFactoryEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabled; import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerSessionFactoryEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabled; import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerSessionFactoryEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabled; import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerSessionFactoryEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabled; import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerSessionFactoryEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabled; import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerSessionFactoryEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabledEnabled; import org.apache.shiro.session.mgt.eis.SessionValidationSchedulerSessionFactoryEnabledEnabledEnabledEnabled
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值