使用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相关的概念网上有很多的文章可以参考,这里附上几个感觉讲的很好的文章12JWT与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/ ↩
相关文章推荐
- Spring Boot实战之Filter实现使用JWT进行接口认证 jwt(json web token) 用户发送按照约定,向服务端发送 Header、Payload 和 Signature,
- Spring Boot整合JWT实现用户认证
- Spring Boot实战之Filter实现使用JWT进行接口认证
- 详解Spring Boot实战之Filter实现使用JWT进行接口认证
- Spring Boot实战之Filter实现使用JWT进行接口认证
- 使用Spring3 实现用户登录以及权限认证
- spring boot-使用Filter实现Header认证
- laravel 使用JWT实现用户认证
- 使用Spring3 实现用户登录以及权限认证
- 详解使用Spring3 实现用户登录以及权限认证
- Sprint Boot使用OAuth和JWT实现身份认证【二】
- SpringBoot使用JWT实现登录验证
- Laravel 5 中使用 JWT(Json Web Token) 实现基于API的用户认证
- spring boot 使用拦截器 实现 用户登录拦截
- Sprint Boot使用OAuth和JWT实现身份认证【一】
- 56. spring boot中使用@Async实现异步调用【从零开始学Spring Boot】
- 使用tornado实现用户认证
- ubuntu中使用mysql实现opensips用户认证
- 使用tornado实现用户认证
- myeclipse 实现框架 spring+springmvc+springsecurity+myibatis+mysql用户认证和人员增删改查