您的位置:首页 > 编程语言 > Java开发

使用SpringBoot + Ignite + JWT实现用户认证

2018-03-02 16:35 871 查看

使用JWT实现用户认证

本文用一个简单的例子来使用Json Web Token (JWT)实现用户登陆以及认证的功能Github源码

采用了RESTful的设计方式,采用Spring Boot + Ignite + JWT的技术,使用Postman对API进行测试

API接口如下:

用户注册:
/register
使用POST方式请求

用户登陆:
/login
使用POST方式请求

用户认证测试接口:
/secure/users/user
使用POST方式请求

其中用户注册与登陆的请求JSON格式如下:

{
"username":"XXX",
"password":"XXX"
}


JWT概念解析

关于JWT相关的概念网上有很多的文章可以参考,这里附上几个感觉讲的很好的文章12

JWT与Spring Boot的整合

1.配置JWT过滤器信息,将请求头部中
authorization
的信息提取出来,并通过签名的Key进行比对,判断是否是合法的JWT token

public class JwtFilter extends GenericFilterBean {

public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain)
throws IOException, ServletException {

final HttpServletRequest request = (HttpServletRequest) req;
final HttpServletResponse response = (HttpServletResponse) res;
final String authHeader = request.getHeader("authorization");

if ("OPTIONS".equals(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);

chain.doFilter(req, res);
} else {

if (authHeader == null || !authHeader.startsWith("Bearer ")) {
throw new ServletException("Missing or invalid Authorization header");
}

final String token = authHeader.substring(7);

try {
final Claims claims = Jwts.parser().setSigningKey("secretkey").parseClaimsJws(token).getBody();
request.setAttribute("claims", claims);
} catch (final SignatureException e) {
throw new ServletException("Invalid token");
}

chain.doFilter(req, res);
}
}
}


2.在Spring Boot主方法中添加
@Bean
配置需要认证的接口信息,并启动JwtFIlter

@SpringBootApplication
@EnableIgniteRepositories
public class UsersApplication {

@Bean
public FilterRegistrationBean jwtFilter() {
final<
b227
/span> FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(new JwtFilter());
registrationBean.addUrlPatterns("/secure/*");

return registrationBean;
}

public static void main(String[] args) {
SpringApplication.run(UsersApplication.class, args);
}
}


3.在用户进行登陆的过程中,将用户的用户名作为JWT的一个属性进行编码生成JWT token

@RestController
public class PersonController {

@Autowired
private PersonService personService;

/**
* Check user`s login info, then create a jwt token returned to front end
* @param reqPerson
* @return jwt token
* @throws ServletException
*/
@PostMapping
public String login(@RequestBody() ReqPerson reqPerson) throws ServletException {
// Check if username and password is null
if (reqPerson.getUsername() == "" || reqPerson.getUsername() == null
|| reqPerson.getPassword() == "" || reqPerson.getPassword() == null)
throw new ServletException("Please fill in username and password");

// Check if the username is used
if(personService.findPersonByUsername(reqPerson.getUsername()) == null
|| !reqPerson.getPassword().equals(personService.findPersonByUsername(reqPerson.getUsername()).getPassword())){
throw new ServletException("Please fill in username and password");
}

// Create Twt token
String jwtToken = Jwts.builder().setSubject(reqPerson.getUsername()).claim("roles", "member").setIssuedAt(new Date())
.signWith(SignatureAlgorithm.HS256, "secretkey").compact();

return jwtToken;
}
}


测试结果

注册用户,添加用户到数据库



在进行用户的登陆,登陆成功后获得Web Service返回的Jwt token信息



在不使用或使用错误的Jwt token信息访问测试接口
/secure/users/user
时认证失败



在使用正确的token信息访问测试接口时认证成功



John Wu: JSON Web Token-在Web应用间安全地传递信息[EB/OL].[2018-03-02].http://blog.leapoahead.com/2015/09/06/understanding-jwt/
Aboullaite Mohammed: Spring Boot token authentication using JWT[EB/OL]. [2018-03-02].https://aboullaite.me/spring-boot-token-authentication-using-jwt/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: