前言
基于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>
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;
}
}
简单认证的实现类
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();
}
}
}
if (!request.getMethod().equals("OPTIONS")) {...}
这段代码主要是解决后端接收不到前端传入的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);
}
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();
}
4.登录之后获取用户信息
通过扩展工具类获取信息。
代码如下(示例):
String userId = AuthSessionContext.getLoginUserId();
User userInfo = AuthSessionContext.getLoginUser();
总结
基于token最直观的好处就是无状态和可扩展性,token可以设置过期时间,超过时间之后,用户将重新登录。还可以根据相同的授权许可使特定的token甚至一组token无效来实现用户退出登录。
创作不易,关注、点赞就是对作者最大的鼓励,欢迎在下方评论留言
求关注,定期分享Java知识,一起学习,共同成长。