用户身份认证一般有5种方式
1.HTTP Basic authentication
在发送请求时在HTTP头中加入authentication字段,将用Base64编码的用户名和密码作为值,每次发送请求的时候都要发送用户名和密码,实现比较简单。
2.Cookies
向后台发送用户名和密码,在用户名和密码通过验证后,保存返回的Cookie作为用户已经登录的凭证,每次请求时附带这个Cookie。
3.Signatures
用户拿到服务器给的私钥,在发送请求前,将整个请求使用私钥来加密,发送的将是一串加密信息,此方式只适用于API。
4.One-Time Passwords
一次一密,每次登录时使用不同的密码,一般由服务端通过邮件将密码发给用户,这种登录方式比较繁琐。
5.JSON Web Token
用户发送按照约定,向服务端发送Header、Payload和Signature,并包含认证信息(密码),验证通过后服务端返回一个token,之后用户使用该token作为登录凭证,适合于移动端和api。
什么是Json Web Token?
JSON Web Token(JWT)是一个非常轻巧的规范。这个规范允许我们使用JWT在用户和服务器之间传递安全可靠的信息。
本文将介绍jwt的具体使用过程,本文将介绍基于jwt的项目最后打成jar,供其他项目引用的过程。
首先pom文件的介绍,如下:
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.7.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.8.9</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.9</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.1_3</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot</artifactId>
<version>1.5.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.31</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-actuator</artifactId>
<version>1.5.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<version>1.5.6.RELEASE</version>
</dependency>
编写一个自定义的注解类
/**
* Created by shieh on 2017/10/25.
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AccessVerify {
}
通过aop实现该注解类
@Around("@annotation(com.mob.annotation.AccessVerify)")
public Object doAccessCheck(ProceedingJoinPoint pjp) throws Throwable{
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
String token = request.getHeader("Authorization");
if (StringUtils.isEmpty(token))
return new ExceptionEntity(401, "Authorization is empty" +
ServerName.message(request.getServerName(), request.getServerPort())).toString();
// parse the token.
try {
String user = Jwts.parser()
.setSigningKey("eyJhbGciOiJIUzUxMiJ9")
.parseClaimsJws(token.replace("jwt ", ""))
.getBody()
.getSubject();
if (StringUtils.isEmpty(user)) {
return new ExceptionEntity(401, "Authorization is empty" +
ServerName.message(request.getServerName(), request.getServerPort())).toString();
}
String[] strings = user.split("\\|");
if (strings.length < 1 || StringUtils.isEmpty(strings[0]))
return new ExceptionEntity(401, "Authorization is empty" +
ServerName.message(request.getServerName(), request.getServerPort())).toString();
List<String> permissionList = new LinkedList<String>();
for (int i = 1;i < strings.length; i++) {
permissionList.add(strings[i]);
}
if (!permissionList.contains(request.getRequestURI()))
return new ExceptionEntity(403, "you don't have this authority of " + request.getRequestURI()).toString();
return pjp.proceed();
} catch (MalformedJwtException e) {
return new ExceptionEntity(402,"Authorization is wrong" +
ServerName.message(request.getServerName(), request.getServerPort())).toString();
} catch (ExpiredJwtException e) {
return new ExceptionEntity(403,"Authorization is expired" +
ServerName.message(request.getServerName(), request.getServerPort())).toString();
}
}
该类的实现就是对客户端过来的请求进行解析,判断用户的请求是否合法。如果客户端的请求中header没有Authorization值则验证不通过,否则将进一步解析jwt,该jwt中包含用户的信息以及具有的权限的信息。
以上就是基于jwt对客户端的请求进行鉴权。
接下来可能你会有疑问,jwt是如何生成的呢?这是接下来将要描述的。
以下就是jwt的具体生成代码
/**
* Created by shieh on 2017/10/26.
*/
public class TokenEndpoint extends AbstractEndpoint{
UserDao userDao;
public TokenEndpoint(UserDao userDao){
super(ServerName.SERVER_NAME, false);
this.userDao = userDao;
}
public TokenDetail invoke() {
TokenDetail tokenDetail = new TokenDetail();
try {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
String account = request.getParameter("account");
if (StringUtils.isEmpty(account)) throw new AccountNullPointException("account is empty");
List<UserPermission> urlList = userDao.queryUrlByAccount(account);
StringBuffer sb = new StringBuffer();
if (!CollectionUtils.isEmpty(urlList)) {
for (UserPermission userPermission : urlList) {
sb.append("|");
sb.append(userPermission.getUrl());
}
}
Date expiredDate = new Date(System.currentTimeMillis() + 30 * 60 * 1000);
String token = Jwts.builder()
.setSubject(account + sb.toString())
.setExpiration(expiredDate)
.signWith(SignatureAlgorithm.HS512, "eyJhbGciOiJIUzUxMiJ9")
.compact();
Map<String, Object> detail = new HashMap<String, Object>();
detail.put("account", account);
detail.put("expiration", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(expiredDate));
detail.put("authorization", "jwt " + token);
tokenDetail.setDetails(detail);
tokenDetail.setStatus(new Status(200, "success"));
} catch (AccountNullPointException e) {
tokenDetail.setStatus(new Status(100, "account is empty"));
} catch (Exception e) {
tokenDetail.setStatus(new Status(100, e.getMessage()));
}
return tokenDetail;
}
通过依赖注入的方式注入到容器中,以下是具体的代码实现
/**
* Created by shieh on 2017/10/26.
*/
@Configuration
public class EndPointConfig {
@Autowired
UserDao userDao;
@Bean
@ConditionalOnMissingBean
public TokenEndpoint EndPointConfig() {
return new TokenEndpoint(userDao);
}
}
/**
* Created by shieh on 2017/10/27.
*/
public class ServerName {
public static final String SERVER_NAME = "generateToken";
public static String message(String server, int port) {
return " ,please visit http://" + server + ":" + port + "/" + SERVER_NAME;
}
}
通过actuator在jar包中设置endpoint,从而实现,项目引入该jar后将自动对外提供相对应的endpoint服务,从而实现jwt的生成。只需访问http://ip:port/generateToken即可实现jwt的生成。
以上就是对于jwt+actuator的简单应用。如有不妥之处,望大神指点一二,小弟在此感激不尽。