当前位置:   article > 正文

基于token身份认证的完整实例_token案例

token案例


前言

基于Token的身份认证是无状态的,服务器或者Session中不会存储任何用户信息。


一、基于Token的身份认证工作流程

1.用户通过用户名和密码请求访问

2.服务器验证用户,通过校验则向客户端返回一个token

3.客户端存储token,并且在随后的每一次请求中都带着它

4.服务器校验token并返回数据

每一次请求都需要token -Token应该放在请求header中 -我们还需要将服务器设置为接受来自所有域的请求,用Access-Control-Allow-Origin: *

二、实现步骤

1.配置过滤请求

在web-xml中配置需要认证的请求

<filter>
		<filter-name>authFilter</filter-name>
		<filter-class>com.demo.filter.AuthFilter</filter-class>
		<init-param>
			<param-name>ignore</param-name>
			<param-value>
				/**
			</param-value>
		</init-param>
		<init-param>
			<param-name>noIgnore</param-name>
			<param-value>
				/**/userApi/**/**
			</param-value>
		</init-param>
	</filter>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

2.实现过滤器

代码如下(示例):

public class AuthFilter implements Filter {
    protected Pattern[] ignorePattern = null;
    PathMatcher matcher = new AntPathMatcher();
    // 不用过滤的请求
    String[] ignoreStrs = null;
    // 需要过滤的请求
    String[] noIgnoreStrs = null;

    public AuthFilter() {
    }

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        String uri = request.getRequestURI();
        // 判断是否需要认证
        if (this.checkIgnore(uri) && !this.checkNoIgnore(uri)) {
            chain.doFilter(request, response);
        } else {
        	// 用户认证
            Author.checkAuthorLocal(request, response, chain);
        }
    }

    @Override
    public void init(FilterConfig config) throws ServletException {
        String ignore = config.getInitParameter("ignore");
        String noIgnore = config.getInitParameter("noIgnore");
        ignore = StringUtils.defaultIfEmpty(ignore, "");
        this.ignoreStrs = ignore.replaceAll("\\s", "").split(",");
        this.noIgnoreStrs = noIgnore.replaceAll("\\s", "").split(",");
    }

    public boolean checkIgnore(String requestUrl) {
        boolean flag = false;
        String[] var6 = this.ignoreStrs;
        int var5 = this.ignoreStrs.length;
        for(int var4 = 0; var4 < var5; ++var4) {
            String pattern = var6[var4];
            if (flag = this.matcher.match(pattern, requestUrl)) {
                break;
            }
        }
        return flag;
    }

    public boolean checkNoIgnore(String requestUrl) {
        boolean flag = false;
        String[] var6 = this.noIgnoreStrs;
        int var5 = this.noIgnoreStrs.length;
        for(int var4 = 0; var4 < var5; ++var4) {
            String pattern = var6[var4];
            if (flag = this.matcher.match(pattern, requestUrl)) {
                break;
            }
        }
        return flag;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64

简单认证的实现类

public class Author {

    public Author() {
    }

    public static void checkAuthorLocal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        if (!request.getMethod().equals("OPTIONS")) {
        	// 获取token
            String token = request.getHeader("oauth_token");
            if (!StringUtil.hasText(token)) {
                token = request.getParameter("oauth_token");
            }
            String loginUserId;
            if (StringUtil.hasText(token)) {
            	// 判断token有效性
                loginUserId = getLoginUserId(token);
                if (StringUtil.hasText(loginUserId)) {
                    setLoginUserId(token, loginUserId);
                    chain.doFilter(request, response);
                } else {
                    response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
                    PrintWriter writer = response.getWriter();
                    writer.print("no access");
                    return;
                }
            } else {
                response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
                PrintWriter writer = response.getWriter();
                writer.print("no access");
                return;
            }
        }
    }

    private static String getLoginUserId(String accessToken) {
        String userId = RedisClient.get(accessToken);
        return userId;
    }

    public static void setLoginUserId(String accessToken, String userId) {
        try {
            RedisClient.set(accessToken, userId, Cluster.getTimeoutSecond());
        } catch (Exception var3) {
            var3.printStackTrace();
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
 if (!request.getMethod().equals("OPTIONS")) {...}
  • 1

这段代码主要是解决后端接收不到前端传入的header参数信息的问题,前面也提过。

用户存储的工具类
代码如下(示例):

public class AuthSessionContext extends UserSessionContext {

    public static String USER_KEY = "userKey";
    public static String CACHE_KEY_USER_IDENTITY = "USER_IDENTITY_DATA";
    public static String CACHE_KEY_USER_IDENTITY_ID = "USER_IDENTITY_ID";
    //private static ICaheManager RedisClient = CacheManagerFactory.getCentralizedCacheManager();


    public static UserSessionContextService getContextService() {
        return (UserSessionContextService) BeanManager.getBean(UserSessionContextService.class);
    }

    /** @deprecated */
    @Deprecated
    public static String getLoginPersonKey(HttpServletRequest request) {
        return getLoginUserId(request);
    }

    public static String getLoginIdentityId(HttpServletRequest request) {
        String loginUserId = getLoginUserId(request);
        String loginIdentityId = (String) RedisClient.get(CACHE_KEY_USER_IDENTITY_ID + loginUserId);
        if (!StringUtil.hasText(loginIdentityId)) {
            UserIdentityVO identity = getIdentity();
            if (identity != null) {
                loginIdentityId = identity.getId();
                RedisClient.set(CACHE_KEY_USER_IDENTITY_ID + loginUserId, loginIdentityId, 60);
            }
        }

        return loginIdentityId;
    }

    public static String getLoginIdentityId() {
        HttpServletRequest request = WsbpWebContextListener.getRequest();
        return getLoginIdentityId(request);
    }



    public static String getIdentityId() {
        UserIdentityVO identity = getIdentity();
        return identity != null ? identity.getId() : "";
    }

    public static void setLoginIdentityId(String loginUserId, String loginIdentityId) {
        RedisClient.set(CACHE_KEY_USER_IDENTITY_ID + loginUserId, loginIdentityId, Cluster.getTimeoutMillisecond());
    }

    public static String getLoginUserId(HttpServletRequest request) {
        String token = request.getHeader("oauth_token");
        String userId = null;
        if (token != null && !token.isEmpty()) {
            userId = (String)RedisClient.get(token);
        }
        return userId;
    }

    public static String getLoginUserId() {
        HttpServletRequest request = WsbpWebContextListener.getRequest();
        return getLoginUserId(request);
    }

    public static String getLoginUserName() {
        UserVO loginUser = getLoginUser();
        return loginUser != null ? loginUser.getUserName() : "";
    }

    public static UserVO getLoginUser() {
        return getContextService().getUserByUserId(getLoginUserId());
    }

    public static String getLoginDepartment(HttpServletRequest request) {
        String identityId = getLoginIdentityId(request);
        return getContextService().getLoginDepartment(identityId);
    }

    public static String getDeptId() {
        HttpServletRequest request = WsbpWebContextListener.getRequest();
        String identityId = getLoginIdentityId(request);
        return getContextService().getLoginDepartment(identityId);
    }

    public static DepartmentVO getDept() {
        return getContextService().getDepartment(getDeptId());
    }

    public static String getDeptName() {
        DepartmentVO department = getDept();
        return department != null ? department.getName() : "";
    }

    public static String getLoginOrganization(HttpServletRequest request) {
        String identityId = getLoginIdentityId(request);
        return getContextService().getLoginOrganization(identityId);
    }

    public static String getOrgId() {
        HttpServletRequest request = WsbpWebContextListener.getRequest();
        String identityId = getLoginIdentityId(request);
        return getContextService().getLoginOrganization(identityId);
    }

    public static OrganizationVO getOrg() {
        DepartmentVO dept = getDept();
        return dept != null ? dept.getOrg() : null;
    }

    public static String getOrgName() {
        OrganizationVO org = getOrg();
        return org != null ? org.getName() : "";
    }

    public static boolean isInAnyRole(HttpServletRequest request, String roles) {
        String identityId = getLoginIdentityId(request);
        return getContextService().checkIsInAnyRole(identityId, roles);
    }

    public static boolean isInRole(HttpServletRequest request, String roles) {
        String identityId = getLoginIdentityId(request);
        return getContextService().checkIsInRole(identityId, roles);
    }

    public static List<RoleVO> getRoleListInRoles(HttpServletRequest request, String roles) {
        String identityId = getLoginIdentityId(request);
        return getContextService().getRoleListInRoles(identityId, roles);
    }

    public static boolean isInAnyCase(HttpServletRequest request, String cases) {
        String identityId = getLoginIdentityId(request);
        return getContextService().checkIsInAnyCase(identityId, cases);
    }

    public static boolean isInCase(HttpServletRequest request, String cases) {
        String identityId = getLoginIdentityId(request);
        boolean checkIsInCase = getContextService().checkIsInCase(identityId, cases);
        return checkIsInCase;
    }

    public static List<RoleVO> getmyUserRoleList(HttpServletRequest request) {
        String identityId = getLoginIdentityId(request);
        return getContextService().getmyUserRoleList(identityId);
    }

    public static RoleVO getmyUserhighestRole(HttpServletRequest request) {
        String identityId = getLoginIdentityId(request);
        return getContextService().getmyUserhighestRole(identityId);
    }

    public static String getmyTenementIdByUserId(HttpServletRequest request) {
        String userId = getLoginUserId(request);
        return getContextService().getLoginTenementId(userId);
    }


    public static void setLoginUser(HttpServletResponse response, TsysUserVO user, String userKey) {
        try {
            String userId = user.getId();
            addCookie(response, USER_KEY, userKey, "/", getSessionTimeout());//单位分钟
            addCookie(response, Cluster.SESSION_KEY, userKey, "/", getSessionTimeout());//单位分钟
            RedisClient.set(userKey, userId, Cluster.getTimeoutSecond());//单位秒
            RedisClient.set(userKey+"Username", user.getUserName(), Cluster.getTimeoutSecond());//单位秒
            RedisClient.set(user.getUserName(), user.getPasswd(), Cluster.getTimeoutSecond());//单位秒
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void addCookie(HttpServletResponse response, String name, String value, String path, int maxAge) {
        Cookie cookie = new Cookie(name, value);
        cookie.setPath(path);
        cookie.setMaxAge(maxAge);
        response.addCookie(cookie);
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173

3.登录接口

登录逻辑判断用户名密码,通过则将用户信息返回,同时将用户信息存在Redis中,向前端返回token
代码如下(示例):

	@RequestMapping(value = "/login", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    @ResponseBody
    public String login(@RequestBody String jsonStr, HttpServletResponse response) {
        JSONObject object = JSON.parseObject(jsonStr);
        String account = object.getString("account");
        String password = object.getString("password");
        JSONObject result = new JSONObject(3);
        if (StringUtils.isEmpty(account) || StringUtils.isEmpty(password)) {
        	result .put("state", false);
            result .put("msg", "账号或密码不能为空");
            return result.toString();
        }
        // 判断用户名和密码
        User userInfo = userService.login(account, password);
        if (userInfo instanceof String) {
            return (String) userInfo;
        } else {
            User user = (User) userInfo;
            String id = user.getId();
            String s = id + System.currentTimeMillis();
            String token = MD5Util.MD5(s);
            Author.setLoginUserId(token, user.getId());
            AuthSessionContext.setLoginUser(response, user, token);
            result .put("state", true);
            result .put("oauth_token", token);
        }
        return result.toString();
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

4.登录之后获取用户信息

通过扩展工具类获取信息。
代码如下(示例):

String userId = AuthSessionContext.getLoginUserId();
  • 1
User userInfo = AuthSessionContext.getLoginUser();
  • 1

总结

基于token最直观的好处就是无状态和可扩展性,token可以设置过期时间,超过时间之后,用户将重新登录。还可以根据相同的授权许可使特定的token甚至一组token无效来实现用户退出登录。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/609926
推荐阅读
相关标签
  

闽ICP备14008679号