Advertisement
Guest User

Untitled

a guest
Jan 19th, 2017
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.71 KB | None | 0 0
  1. LoginController :
  2.  
  3. //package controller;
  4. import java.security.Key;
  5. import java.util.Date;
  6. import java.util.concurrent.TimeUnit;
  7. import javax.crypto.spec.SecretKeySpec;
  8. import javax.ws.rs.Consumes;
  9. import javax.ws.rs.FormParam;
  10. import javax.ws.rs.POST;
  11. import javax.ws.rs.Path;
  12. import javax.ws.rs.Produces;
  13. import javax.ws.rs.core.MediaType;
  14. import javax.ws.rs.core.Response;
  15. import javax.ws.rs.core.Response.Status;
  16. import javax.xml.bind.DatatypeConverter;
  17. import org.hibernate.SessionFactory;
  18. import dao.UtilisateurDAO;
  19. import io.jsonwebtoken.JwtBuilder;
  20. import io.jsonwebtoken.Jwts;
  21. import model.Utilisateur;
  22.  
  23. @Path("/login")
  24. public class LoginController {
  25.  
  26. SessionFactory sessionFactory = SessionConfig.getSessionFactory();
  27. UtilisateurDAO uDAO = new UtilisateurDAO(sessionFactory);
  28. String key = "pyviJ5z14Lcvb0qG6jcnmA==";
  29.  
  30.  
  31. @POST
  32. @Produces(MediaType.APPLICATION_JSON)
  33. @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
  34. public Response login(@FormParam("username") String username, @FormParam("password") String password)
  35. //throws JsonGenerationException, JsonMappingException, IOException {
  36. {
  37. if (username == null) {
  38. return Response.status(
  39. Status.PRECONDITION_FAILED.getStatusCode())
  40. .build();
  41. }
  42.  
  43. if (password == null) {
  44. return Response.status(
  45. Status.PRECONDITION_FAILED.getStatusCode())
  46. .build();
  47. }
  48.  
  49. Utilisateur user = uDAO.getUserAuthenticated(username,password);
  50. if (user == null) {
  51. return Response.status(Status.FORBIDDEN.getStatusCode())
  52. .build();
  53. }
  54.  
  55. String token = createJWT(user.getId()+"","http://vm-11.iutrs.unistra.fr:8080/TrocTonSavoir/api/",user.getPseudo(),TimeUnit.DAYS.toMillis(365));
  56. return Response.status(200).entity(token).build();
  57. }
  58.  
  59. private String createJWT(String id, String issuer, String subject, long ttlMillis) {
  60.  
  61. //The JWT signature algorithm we will be using to sign the token
  62. io.jsonwebtoken.SignatureAlgorithm signatureAlgorithm = io.jsonwebtoken.SignatureAlgorithm.HS256;
  63.  
  64. long nowMillis = System.currentTimeMillis();
  65. Date now = new Date(nowMillis);
  66.  
  67.  
  68. //We will sign our JWT with our ApiKey secret
  69. byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(key);
  70. Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
  71.  
  72. //Let's set the JWT Claims
  73. JwtBuilder builder = Jwts.builder().setId(id)
  74. .setIssuedAt(now)
  75. .setSubject(subject)
  76. .setIssuer(issuer)
  77. .signWith(signatureAlgorithm, signingKey);
  78.  
  79. //if it has been specified, let's add the expiration
  80. if (ttlMillis >= 0) {
  81. long expMillis = nowMillis + ttlMillis;
  82. Date exp = new Date(expMillis);
  83. builder.setExpiration(exp);
  84. }
  85.  
  86. //Builds the JWT and serializes it to a compact, URL-safe string
  87. return builder.compact();
  88. }
  89.  
  90. // @POST
  91. // @Path("/logout")
  92. // @Produces(MediaType.APPLICATION_JSON)
  93. // public Login logout(Login login){
  94. // login.setSuccess(false);
  95. // login.setUname("");
  96. // return login;
  97. // }
  98.  
  99. }
  100.  
  101.  
  102.  
  103.  
  104.  
  105. LoginFilter :
  106.  
  107.  
  108.  
  109. import java.io.IOException;
  110. import java.util.Enumeration;
  111. import java.util.logging.Level;
  112. import java.util.logging.Logger;
  113.  
  114. import javax.servlet.Filter;
  115. import javax.servlet.FilterChain;
  116. import javax.servlet.FilterConfig;
  117. import javax.servlet.ServletException;
  118. import javax.servlet.ServletRequest;
  119. import javax.servlet.ServletResponse;
  120. import javax.servlet.annotation.WebFilter;
  121. import javax.servlet.http.HttpServletRequest;
  122. import javax.servlet.http.HttpServletResponse;
  123. import javax.servlet.http.HttpSession;
  124. import javax.ws.rs.core.HttpHeaders;
  125. import javax.xml.bind.DatatypeConverter;
  126.  
  127. import io.jsonwebtoken.Claims;
  128. import io.jsonwebtoken.Jwts;
  129.  
  130. public class LoginFilter implements Filter {
  131.  
  132. String key = "pyviJ5z14Lcvb0qG6jcnmA==";
  133.  
  134. /**
  135. * Default constructor.
  136. */
  137. public LoginFilter() {
  138. // TODO Auto-generated constructor stub
  139. }
  140.  
  141. /**
  142. * @see Filter#destroy()
  143. */
  144. public void destroy() {
  145. // TODO Auto-generated method stub
  146. }
  147.  
  148. /**
  149. * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
  150. */
  151. public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
  152.  
  153. // Get the HTTP Authorization header from the request
  154. // TODO Auto-generated method stub
  155. HttpServletRequest httpRequest = (HttpServletRequest) request;
  156. HttpServletResponse res = (HttpServletResponse) response;
  157. Logger LOGGER = Logger.getLogger( LoginFilter.class.getName() );
  158. String path = httpRequest.getRequestURI();
  159. // if (path.equals("/TrocTonSavoir/api/login")) {
  160. chain.doFilter(httpRequest, res);
  161. // }
  162. // else {
  163. // Enumeration<String> headerNames = httpRequest.getHeaderNames();
  164. // boolean error = false;
  165. // boolean trouve = false;
  166. // if (headerNames != null) {
  167. // while (headerNames.hasMoreElements() && !trouve) {
  168. // String headerName = headerNames.nextElement();
  169. // String header = httpRequest.getHeader(headerName);
  170. // if(headerName.equals("bearer")){
  171. // String token = httpRequest.getHeader(headerName);
  172. // Claims claims = null;
  173. // try{
  174. // //This line will throw an exception if it is not a signed JWS (as expected)
  175. // claims = Jwts.parser()
  176. // .setSigningKey(DatatypeConverter.parseBase64Binary(key))
  177. // .parseClaimsJws(token).getBody();
  178. // }
  179. // catch(Exception e){
  180. // error = true;
  181. // }
  182. // if(null != claims){
  183. // trouve = true;
  184. // }
  185. // }
  186. // }
  187. // if(error){
  188. // res.sendError(403,"Please login before going anywhere else!");
  189. // }
  190. // else if(trouve){
  191. // chain.doFilter(httpRequest, res);
  192. // }
  193. // else{
  194. // res.sendError(403,"Please login before going anywhere else!");
  195. // }
  196. // }
  197. // else{
  198. // res.sendError(403,"Please login before going anywhere else!");
  199. // }
  200. // }
  201.  
  202. }
  203.  
  204. /**
  205. * @see Filter#init(FilterConfig)
  206. */
  207. public void init(FilterConfig fConfig) throws ServletException {
  208. // TODO Auto-generated method stub
  209. }
  210.  
  211. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement