SpringBoot入门建站全系列(十二)Spring Security使用token做认证

SpringBoot入门建站全系列(十二)Spring Security使用token做认证

Spring 是一个非常流行和成功的 Java 应用开发框架。Spring Security 基于 Spring 框架,提供了一套 Web 应用安全性的完整解决方案。一般来说,Web 应用的安全性包括用户认证(Authentication)和用户授权(Authorization)两个部分。用户认证指的是验证某个用户是否为系统中的合法主体,也就是说用户能否访问该系统。用户认证一般要求用户提供用户名和密码。系统通过校验用户名和密码来完成认证过程。用户授权指的是验证某个用户是否有权限执行某个操作。在一个系统中,不同用户所具有的权限是不同的。比如对一个文件来说,有的用户只能进行读取,而有的用户可以进行修改。一般来说,系统会为不同的用户分配不同的角色,而每个角色则对应一系列的权限。

Spring-security其实就是用filter,多请求的路径进行过滤。

如果是基于Session,那么Spring-security会对cookie里的sessionid进行解析,找到服务器存储的sesion信息,然后判断当前用户是否符合请求的要求。

如果是token,则是解析出token,然后将当前请求加入到Spring-security管理的权限信息中去。

上一篇《SpringBoot入门建站全系列(十一)Spring-security进行权限认证》已经介绍了如何使用Spring-security进行form表单的权限控制。

这一篇介绍如何使用token做访问控制,token的访问控制主要是对token的生成和解析,对token的来源并没有强制要求,我们完全可以自己来管理,也可以用jwt token,本篇就以jwt token来讲解如何使用token做访问控制。

**如果大家正在寻找一个java的学习环境,或者在开发中遇到困难,可以<a

href="https://jq.qq.com/?_wv=1027&k=52sgH1J"

target="_blank">

加入我们的java学习圈,点击即可加入

</a>

,共同学习,节约学习时间,减少很多在学习中遇到的难题。**

一、配置

本文假设你已经引入spring-boot-starter-web。已经是个SpringBoot项目了,如果不会搭建,可以打开这篇文章看一看《SpringBoot入门建站全系列(一)项目建立》

1.1 Maven依赖

<dependency>
	<groupId>org.mybatis.spring.boot</groupId>
	<artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>
<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
	<groupId>org.apache.commons</groupId>
	<artifactId>commons-dbcp2</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
	<groupId>io.jsonwebtoken</groupId>
	<artifactId>jjwt</artifactId>
	<version>0.9.0</version>
</dependency>

Spring-security一般需要从数据库中查询用户信息的,所以这里还是要把mybatis引入,以查询用户信息使用。

1.2 配置文件

application.properties 中需要添加下面的配置:

spring.datasource.type=org.apache.commons.dbcp2.BasicDataSource
spring.datasource.dbcp2.max-wait-millis=60000
spring.datasource.dbcp2.min-idle=20
spring.datasource.dbcp2.initial-size=2
spring.datasource.dbcp2.validation-query=SELECT 1
spring.datasource.dbcp2.connection-properties=characterEncoding=utf8
spring.datasource.dbcp2.validation-query=SELECT 1
spring.datasource.dbcp2.test-while-idle=true
spring.datasource.dbcp2.test-on-borrow=true
spring.datasource.dbcp2.test-on-return=false

spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/boot?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
spring.datasource.username=cff
spring.datasource.password=123456

mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

token.expire=3600000
token.key=123456

这里的配置主要就是数据库连接和数据源、mybatis的配置。因为要连接数据库。

另外两个token开发的属性,是对token的配置,一般不怎么变化,写死也可以的。

二、安全控制核心

这个配置的作用和上篇的一致。

Spring Security的核心配置就是继承WebSecurityConfigurerAdapter并注解@EnableWebSecurity的配置。

这个配置指明了用户名密码的处理方式、请求路径的开合、登录登出控制等和安全相关的配置。

TokenWebSecurityConfig :

package com.cff.springbootwork.token.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;

import com.cff.springbootwork.token.filter.TokenAuthenticationFilter;
import com.cff.springbootwork.token.filter.TokenLoginFilter;
import com.cff.springbootwork.token.handler.DefaultPasswordEncoder;
import com.cff.springbootwork.token.handler.TokenLogoutHandler;
import com.cff.springbootwork.token.handler.UnauthorizedEntryPoint;
import com.cff.springbootwork.token.manager.TokenManager;

@Configuration
public class TokenWebSecurityConfig extends WebSecurityConfigurerAdapter {
	private UserDetailsService userDetailsService;
	private TokenManager tokenManager;
	private DefaultPasswordEncoder defaultPasswordEncoder;

	@Autowired
	public TokenWebSecurityConfig(UserDetailsService userDetailsService, DefaultPasswordEncoder defaultPasswordEncoder,
			TokenManager tokenManager) {
		this.userDetailsService = userDetailsService;
		this.defaultPasswordEncoder = defaultPasswordEncoder;
		this.tokenManager = tokenManager;
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.exceptionHandling().authenticationEntryPoint(new UnauthorizedEntryPoint()).and().csrf().disable()
				.authorizeRequests().antMatchers("/login").permitAll().antMatchers("/public/**").permitAll()
				.anyRequest().authenticated().and().logout().logoutUrl("/logout")
				.addLogoutHandler(new TokenLogoutHandler(tokenManager)).and()
				.addFilter(new TokenLoginFilter(authenticationManager(), tokenManager))
				.addFilter(new TokenAuthenticationFilter(authenticationManager(), tokenManager)).httpBasic();
	}

	@Override
	public void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth.userDetailsService(userDetailsService).passwordEncoder(defaultPasswordEncoder);
	}
}

这里:

  • UserDetailsService :用户名密码查询的业务逻辑,实现loadUserByUsername方法。
  • UnauthorizedEntryPoint:未授权的统一处理方式。
  • TokenManager:token管理。
  • DefaultPasswordEncoder:密码的处理方法。
  • TokenLogoutHandler: 登出业务逻辑。
  • TokenLoginFilter:登录过滤器,继承UsernamePasswordAuthenticationFilter,对用户名密码进行登录校验。
  • TokenAuthenticationFilter:访问过滤器。

这里的配置之所以和上篇的略有差别,是因为,

  • 1.本篇未使用AuthenticationProvider,用户名密码的校验由Spring自己完成,我们提供用户名密码的查询和密码的验证规则。
  • 2.TokenLoginFilter过滤器其实和上篇介绍的类似,如果是form表单提交,这个地方其实和上篇的一样,可以用AuthenticationProvider对用户名密码进行校验,只不过校验成功了之后,需要生成token并返回;但是这里是json数据,我们不能像上篇那样通过配置获取到用户名密码,因此需要用filter来获取。
  • 3.TokenAuthenticationFilter访问过滤器对每个请求进行过滤,拿到请求中的token,解析出用户,然后生成UsernamePasswordAuthenticationToken交给Springsecurity进行控制。

三、安全处理逻辑

3.1 用户名密码校验并生成token

TokenLoginFilter过滤器是对登录信息的验证。

如果是form表单提交,这个地方其实和上篇的一样,可以用AuthenticationProvider对用户名密码进行校验,校验成功了之后,需要生成token并返回。

如果是json数据,我们不能通过配置获取到用户名密码,因此需要用TokenLoginFilter来获取。

TokenLoginFilter:

package com.cff.springbootwork.token.filter;

import com.cff.springbootwork.token.manager.TokenManager;
import com.cff.springbootwork.token.model.LoginUserReq;
import com.cff.springbootwork.token.model.LoginUserRes;
import com.cff.springbootwork.token.model.ResultCode;
import com.cff.springbootwork.token.model.ResultModel;
import com.cff.springbootwork.token.model.TokenUserDetails;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.ProviderNotFoundException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

public class TokenLoginFilter extends UsernamePasswordAuthenticationFilter {
	private AuthenticationManager authenticationManager;
	private TokenManager tokenManager;

	public TokenLoginFilter(AuthenticationManager authenticationManager, TokenManager tokenManager) {
		this.authenticationManager = authenticationManager;
		this.tokenManager = tokenManager;
		this.setPostOnly(false);
		this.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/login"));
	}

	@Override
	public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res)
			throws AuthenticationException {
		try {
			LoginUserReq user = new ObjectMapper().readValue(req.getInputStream(), LoginUserReq.class);
			return authenticationManager.authenticate(
					new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword(), new ArrayList<>()));
		} catch (IOException e) {
			throw new RuntimeException(e);
		}

	}

	@Override
	protected void successfulAuthentication(HttpServletRequest req, HttpServletResponse res, FilterChain chain,
			Authentication auth) throws IOException, ServletException {
		TokenUserDetails user = (TokenUserDetails) auth.getPrincipal();

		String token = tokenManager.createToken(user.getUsername());

		LoginUserRes loginUserRes = new LoginUserRes();
		loginUserRes.setUsername(user.getUsername());
		loginUserRes.setToken(token);
		ResultModel rm = new ResultModel(ResultCode.CODE_00000);
		rm.setData(loginUserRes);

		ObjectMapper mapper = new ObjectMapper();
		res.setStatus(HttpStatus.OK.value());
		res.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
		mapper.writeValue(res.getWriter(), rm);
	}

	@Override
	protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException e) throws IOException, ServletException {
		response.setStatus(HttpStatus.OK.value());
		ObjectMapper mapper = new ObjectMapper();
		ResultModel rm = null;
		if (e instanceof BadCredentialsException) {
			rm = new ResultModel(ResultCode.CODE_00001.getCode(), e.getMessage());
		} else if (e instanceof UsernameNotFoundException) {
			rm = new ResultModel(ResultCode.CODE_00011);
		} else if (e instanceof AuthenticationCredentialsNotFoundException) {
			rm = new ResultModel(ResultCode.CODE_00003);
		} else if (e instanceof ProviderNotFoundException) {
			rm = new ResultModel(ResultCode.CODE_10000, e.getMessage());
		} else {
			rm = new ResultModel(ResultCode.CODE_00013);
		}

		response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
		mapper.writeValue(response.getWriter(), rm);

	}
}

这里面的AuthenticationManager 是Spring管理的。

TokenManager是我们自己的,对token进行管理。

3.2 访问控制过滤器

这里假设token字段存在http头中。

从http头中取出token字段,并通过TokenManager解析出用户信息,生成UsernamePasswordAuthenticationToken交给SpringSecurity进行管理。

TokenAuthenticationFilter :

package com.cff.springbootwork.token.filter;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.util.StringUtils;

import com.cff.springbootwork.token.manager.TokenManager;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

public class TokenAuthenticationFilter extends BasicAuthenticationFilter {
	private TokenManager tokenManager;

	public TokenAuthenticationFilter(AuthenticationManager authManager, TokenManager tokenManager) {
		super(authManager);
		this.tokenManager = tokenManager;
	}

	@Override
	protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		String header = req.getHeader("token");

		if (header == null) {
			chain.doFilter(req, res);
			return;
		}

		UsernamePasswordAuthenticationToken authentication = getAuthentication(req);

		if (authentication != null) {
			SecurityContextHolder.getContext().setAuthentication(authentication);
		}
		chain.doFilter(req, res);
	}

	private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
		// token置于header里
		String token = request.getHeader("token");
		if (token != null && !"".equals(token.trim())) {
			// parse the token.
			String userName = tokenManager.getUserFromToken(token);

			if (!StringUtils.isEmpty(userName)) {
				return new UsernamePasswordAuthenticationToken(userName, token, new ArrayList<>());
			}
			return null;
		}
		return null;
	}
}

3.3 token管理

将TokenManager定义为接口,我们使用jwt token来实现它。当然也可以用其他方式实现,比如将token和用户信息作为对应存储在redis中。

TokenManager:

package com.cff.springbootwork.token.manager;

public interface TokenManager {

	public String createToken(String username);

	public String getUserFromToken(String token);

	public void removeToken(String token);

}

JwtTokenManager:

package com.cff.springbootwork.token.manager;

import java.util.Date;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import io.jsonwebtoken.CompressionCodecs;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

@Component
public class JwtTokenManager implements TokenManager{
	@Value("${token.expire}")
	private long tokenExpiration = 3600;
	@Value("${token.key}")
	private String tokenSignKey;

	@Override
	public String createToken(String username) {
		String token = Jwts.builder().setSubject(username)
				.setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
				.signWith(SignatureAlgorithm.HS512, tokenSignKey).compressWith(CompressionCodecs.GZIP).compact();
		return token;
	}

	@Override
	public String getUserFromToken(String token) {
		String user = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token).getBody().getSubject();
		return user;
	}

	@Override
	public void removeToken(String token) {
		//jwttoken无需删除,客户端扔掉即可。
	}

}

四、安全处理的一些handler

UnauthorizedEntryPoint:

package com.cff.springbootwork.token.handler;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import com.cff.springbootwork.token.model.ResultCode;
import com.cff.springbootwork.token.model.ResultModel;
import com.fasterxml.jackson.databind.ObjectMapper;

public class UnauthorizedEntryPoint implements AuthenticationEntryPoint {

	@Override
	public void commence(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException authException) throws IOException, ServletException {
		ResultModel rm = new ResultModel(ResultCode.CODE_00005, "401未授权!");

		ObjectMapper mapper = new ObjectMapper();
		response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
		mapper.writeValue(response.getWriter(), rm);
	}

}

TokenLogoutHandler, jwt token没有删除选项,主要客户端遗弃即可,如果token是自己管理的,这个地方要将token移除。

TokenLogoutHandler :

package com.cff.springbootwork.token.handler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;

import com.cff.springbootwork.token.manager.TokenManager;
import com.cff.springbootwork.token.model.ResultCode;
import com.cff.springbootwork.token.model.ResultModel;
import com.fasterxml.jackson.databind.ObjectMapper;

public class TokenLogoutHandler implements LogoutHandler {
	private TokenManager tokenManager;

	public TokenLogoutHandler(TokenManager tokenManager) {
		this.tokenManager = tokenManager;
	}

	@Override
	public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
		String token = request.getHeader("token");
		if (token != null) {
			tokenManager.removeToken(token);
		}
		ResultModel rm = new ResultModel(ResultCode.CODE_00000);

		ObjectMapper mapper = new ObjectMapper();
		response.setStatus(HttpStatus.OK.value());
		response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
		try {
			mapper.writeValue(response.getWriter(), rm);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

DefaultPasswordEncoder, 密码的处理规则, 因为用户名密码的校验过程交给Spring Security来管理了,因为要给它说明密码是经过怎样的处理了,如果传输过来的密码跟数据库里的密码一致,就可以啥也不做,下面的这个就是啥也不做。

DefaultPasswordEncoder:

package com.cff.springbootwork.token.handler;

import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

@Component
public class DefaultPasswordEncoder implements PasswordEncoder {

	public DefaultPasswordEncoder() {
		this(-1);
	}

	/**
	 * @param strength
	 *            the log rounds to use, between 4 and 31
	 */
	public DefaultPasswordEncoder(int strength) {

	}

	public String encode(CharSequence rawPassword) {
		return rawPassword.toString();
	}

	public boolean matches(CharSequence rawPassword, String encodedPassword) {
		return rawPassword.toString().equals(encodedPassword);
	}
}

五、用户信息查询

TokenUserDetailsService调用了UserInfoService进行查询,并将查询后的结果转换为Spring的UserDetails,以供Spring使用。

TokenUserDetailsService:

package com.cff.springbootwork.token.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.cff.springbootwork.mybatis.domain.UserInfo;
import com.cff.springbootwork.mybatis.service.UserInfoService;
import com.cff.springbootwork.token.model.TokenUserDetails;

@Service("formUserDetailsService")
public class TokenUserDetailsService implements UserDetailsService {
	@Autowired
	private UserInfoService userInfoService;

	@Override
	public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
		UserInfo user;
		try {
			user = userInfoService.getUserInfoByUserName(userName);
		} catch (Exception e) {
			throw new UsernameNotFoundException("user select fail");
		}
		if (user == null) {
			throw new UsernameNotFoundException("no user found");
		} else {
			try {
				return new TokenUserDetails(user);
			} catch (Exception e) {
				throw new UsernameNotFoundException("user role select fail");
			}
		}
	}

}

UserInfoService:

package com.cff.springbootwork.mybatis.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cff.springbootwork.mybatis.dao.UserInfoDao;
import com.cff.springbootwork.mybatis.domain.UserInfo;

@Service
public class UserInfoService {
	@Autowired
	UserInfoDao userInfoDao;
	public UserInfo getUserInfoByUserName(String userName){
		return userInfoDao.findByUserName(userName);
	}
}

UserInfoDao:

package com.cff.springbootwork.mybatis.dao;

import java.util.List;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import com.cff.springbootwork.mybatis.domain.UserInfo;

@Mapper
public interface UserInfoDao {
	@Select({
		"<script>",
	        "SELECT ",
	        "user_name as userName,passwd,name,mobile,valid, user_type as userType",
	        "FROM user_info",
	        "WHERE user_name = #{userName,jdbcType=VARCHAR}",
	   "</script>"})
	UserInfo findByUserName(@Param("userName") String userName);
	
	
}

六、过程中用到的实体

UserInfo:

package com.cff.springbootwork.mybatis.domain;

public class UserInfo {
	private String userName;
	private String passwd;
	private String name;
	private String mobile;
	private Integer valid;
	private String userType;

	public UserInfo() {

	}

	public UserInfo(UserInfo src) {
		this.userName = src.userName;
		this.passwd = src.passwd;
		this.name = src.name;
		this.mobile = src.mobile;
		this.valid = src.valid;
	}

	public UserInfo(String userName, String passwd, String name, String mobile, Integer valid) {
		super();
		this.userName = userName;
		this.passwd = passwd;
		this.name = name;
		this.mobile = mobile;
		this.valid = valid;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getUserName() {
		return userName;
	}

	public void setPasswd(String passwd) {
		this.passwd = passwd;
	}

	public String getPasswd() {
		return passwd;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public void setMobile(String mobile) {
		this.mobile = mobile;
	}

	public String getMobile() {
		return mobile;
	}

	public void setValid(Integer valid) {
		this.valid = valid;
	}

	public Integer getValid() {
		return valid;
	}

	public String getUserType() {
		return userType;
	}

	public void setUserType(String userType) {
		this.userType = userType;
	}

	public String getIdentifyTable(){
		return "user_info";
	}
}

LoginUserReq:

package com.cff.springbootwork.token.model;

public class LoginUserReq {
	String userName;
	String password;

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

}

LoginUserRes:

package com.cff.springbootwork.token.model;

public class LoginUserRes {
	String token;
	String username;

	public String getToken() {
		return token;
	}

	public void setToken(String token) {
		this.token = token;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

}

TokenUserDetails:

package com.cff.springbootwork.token.model;

import java.util.Collection;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;

import com.cff.springbootwork.mybatis.domain.UserInfo;


public class TokenUserDetails extends UserInfo implements UserDetails {

	public TokenUserDetails(UserInfo appUser) {
		super(appUser);
	}

	/**
	 * 
	 */
	private static final long serialVersionUID = 6272869114201567325L;

	@Override
	public Collection<? extends GrantedAuthority> getAuthorities() {
		return AuthorityUtils.createAuthorityList("USER");
	}
	
	@Override
	public String getUsername() {
		return super.getUserName();
	}

	@Override
	public boolean isAccountNonExpired() {
		return true;
	}

	@Override
	public boolean isAccountNonLocked() {
		return true;
	}

	@Override
	public boolean isCredentialsNonExpired() {
		return true;
	}

	@Override
	public boolean isEnabled() {
		return true;
	}

	@Override
	public String getPassword() {
		return super.getPasswd();
	}

}

ResultCode:

package com.cff.springbootwork.security.model;

/**
 * 响应码及其描述 Created by txl on 15/7/9.
 */
public enum ResultCode {

	/**
	 * 通用
	 */
	CODE_00000("00000", "操作成功"),
	CODE_00001("00001", "请求失败"),
	CODE_00002("00002", "错误的请求方法"),
	CODE_00003("00003", "非法的参数字段"),
	CODE_00004("00004", "异常抛出"),
	CODE_00005("00005", "权限不足"),
	CODE_00006("00006", "分页limit参数错误"),
	CODE_00007("00007", "分页offset参数错误"),
	CODE_00009("00009", "请求过于频繁"),
	CODE_00010("00010", "数据已存在"),
	CODE_00011("00011", "数据不存在"),
	CODE_00012("00012", "参数缺失"),
	CODE_00013("00013", "系统维护中"),
	CODE_00014("00014", "token缺失"),
	CODE_00015("00015", "token失效"),
	CODE_00016("00016", "签名错误"),

	CODE_10000("10000", "操作部分成功"),
	/**
	 * 系统
	 */
	CODE_30000("30000", "系统ID错误"),

	/**
	 * 授权
	 */
	CODE_40001("40001", "用户未找到"),
	CODE_40002("40002", "该用户状态异常"),
	CODE_40003("40003", "该用户已被删除"),
	CODE_40004("40004", "授权异常"),

	CODE_99999("99999", "签名无效");

	private String code;
	private String desc;

	ResultCode(String code, String desc) {
		this.code = code;
		this.desc = desc;
	}

	public String getCode() {
		return code;
	}

	public String getDesc() {
		return desc;
	}

	/**
	 * 根据code匹配枚举
	 * 
	 * @param code
	 * @return
	 */
	public static ResultCode getResultCodeByCode(String code) {
		for (ResultCode resultCode : ResultCode.values()) {
			if (code.equals(resultCode.getCode())) {
				return resultCode;
			}
		}
		return null;
	}

	public static ResultCode getResultCodeByDesc(String desc) {
		for (ResultCode resultCode : ResultCode.values()) {
			if (desc.equals(resultCode.getDesc())) {
				return resultCode;
			}
		}
		return null;
	}
}

ResultModel:

package com.cff.springbootwork.security.model;

/**
 */
public class ResultModel {

	private String errorCode;
	private String message;
	private Object data;

	public ResultModel(String errorCode, String message) {
		this.errorCode = errorCode;
		this.message = message;
	}

	public ResultModel(String errorCode, String message, Object data) {
		this.errorCode = errorCode;
		this.message = message;
		this.data = data;
	}

	public ResultModel(ResultCode resultCodeEnum, Object data) {
		this.errorCode = resultCodeEnum.getCode();
		this.message = resultCodeEnum.getDesc();
		this.data = data;
	}

	public ResultModel(ResultCode resultCodeEnum) {
		this.errorCode = resultCodeEnum.getCode();
		this.message = resultCodeEnum.getDesc();
	}

	public String geterrorCode() {
		return errorCode;
	}

	public void seterrorCode(String errorCode) {
		this.errorCode = errorCode;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public Object getData() {
		return data;
	}

	public void setData(Object data) {
		this.data = data;
	}
}

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

扫码关注云+社区

领取腾讯云代金券