美文网首页
SpringBoot 整合security 实现自定义Token

SpringBoot 整合security 实现自定义Token

作者: 猫的树 | 来源:发表于2021-06-10 09:49 被阅读0次

    代码写好了,我们可以来测试一下写得是否满足我们的需求
    测试工具:postman


    image

    在登录接口,输入用户名和密码


    image
    发送请求
    image
    获得用户返回的信息

    数据库user_token 新增一条数据(这里就不截图了)

    在新建一个请求

    @RestController
    @RequestMapping(value = "api")
    @SuppressWarnings("all")
    public class UserController {
        @Autowired
        private UserService userService;
        @ResponseBody
        @PostMapping(value = "selectAll")
        public ResultData selectUser() {
            List<UserInfo> userInfos = userService.selectAll();
            ResultData resultData = new ResultData();
            resultData.setCode(1);
            resultData.setMsg("sucess");
            resultData.setData(userInfos);
            return resultData;
        }
    }
    

    发送请求


    image

    在headers 加上登录的clientId 和 accessToken


    image
    成功查询到数据

    最后再创建个退出登录的处理

    package com.example.demo.base.common;
    
    import com.example.demo.base.dto.ResultData;
    import com.example.demo.base.dto.UserDetailsInfo;
    import com.example.demo.base.service.TokenService;
    import com.google.gson.Gson;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.security.core.Authentication;
    import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
    import org.springframework.stereotype.Component;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    
    /**
     * 用户退出登录处理
     */
    @Component
    @SuppressWarnings("all")
    public class DemoLogoutSuccessHandler implements LogoutSuccessHandler {
    
        @Autowired
        private TokenService tokenService;
    
        @Override
        public void onLogoutSuccess(HttpServletRequest httpServletRequest,
                                    HttpServletResponse httpServletResponse,
                                    Authentication authentication) throws IOException, ServletException {
            Gson gson = new Gson();
            ResultData resultData = new ResultData(1, "logout successful", null);
            if (authentication != null && authentication.getPrincipal() != null) {
                String clientId = httpServletRequest.getHeader("clientId");
                // 删除Token
                tokenService.deleteToken(clientId);
            }
            httpServletResponse.getWriter().write(gson.toJson(resultData));
        }
    }
    
    

    退出登录


    image

    使用token再访问时,就会失败


    image

    相关文章

      网友评论

          本文标题:SpringBoot 整合security 实现自定义Token

          本文链接:https://www.haomeiwen.com/subject/brxdsltx.html