Guest User

Untitled

a guest
Mar 3rd, 2018
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.51 KB | None | 0 0
  1. public class AccountCredentials {
  2.  
  3. private String username;
  4. private String password;
  5. // getters & setters
  6. public String getUsername() {
  7. return username;
  8. }
  9. public void setUsername(String username) {
  10. this.username = username;
  11. }
  12. public String getPassword() {
  13. return password;
  14. }
  15. public void setPassword(String password) {
  16. this.password = password;
  17. }
  18.  
  19.  
  20. }
  21.  
  22. public class JWTAuthenticationFilter extends GenericFilterBean {
  23.  
  24. @Override
  25. public void doFilter(ServletRequest request,
  26. ServletResponse response,
  27. FilterChain filterChain)
  28. throws IOException, ServletException {
  29.  
  30.  
  31. Authentication authentication = TokenAuthenticationService.getAuthentication((HttpServletRequest)request);
  32. SecurityContextHolder.getContext().setAuthentication(authentication);
  33.  
  34. filterChain.doFilter(request,response);
  35.  
  36. }
  37. }
  38.  
  39. public class JWTLoginFilter extends AbstractAuthenticationProcessingFilter {
  40.  
  41. public JWTLoginFilter(String url, AuthenticationManager authManager) {
  42. super(new AntPathRequestMatcher(url));
  43. setAuthenticationManager(authManager);
  44. }
  45.  
  46. @Override
  47. public Authentication attemptAuthentication(
  48. HttpServletRequest req, HttpServletResponse res)
  49. throws AuthenticationException, IOException, ServletException {
  50. AccountCredentials creds = new ObjectMapper()
  51. .readValue(req.getInputStream(), AccountCredentials.class);
  52. return getAuthenticationManager().authenticate(
  53. new UsernamePasswordAuthenticationToken(
  54. creds.getUsername(),
  55. ClavePass.Encriptar(creds.getPassword()),
  56. Collections.emptyList()
  57. )
  58. );
  59. }
  60.  
  61. @Override
  62. protected void successfulAuthentication(
  63. HttpServletRequest req,
  64. HttpServletResponse res, FilterChain chain,
  65. Authentication auth) throws IOException, ServletException {
  66. TokenAuthenticationService
  67. .addAuthentication(res, auth.getName());
  68. }
  69. }
  70.  
  71. class TokenAuthenticationService {
  72. static final long EXPIRATIONTIME = 864_000_000; // 10 days
  73. static final String SECRET = "ThisIsASecret";
  74. static final String TOKEN_PREFIX = "Bearer";
  75. static final String HEADER_STRING = "Authorization";
  76.  
  77. static void addAuthentication(HttpServletResponse res, String username) {
  78. String token = Jwts.builder()
  79. .setSubject(username)
  80.  
  81. // Vamos a asignar un tiempo de expiracion de 1 minuto
  82. // solo con fines demostrativos en el video que hay al final
  83. .setExpiration(new Date(System.currentTimeMillis() + 60000))
  84.  
  85. // Hash con el que firmaremos la clave
  86. .signWith(SignatureAlgorithm.HS512, "nisira")
  87. .compact();
  88.  
  89. //agregamos al encabezado el token
  90. res.addHeader("Authorization", "Bearer " + token);
  91.  
  92. }
  93.  
  94. static Authentication getAuthentication(HttpServletRequest request) {
  95. String token = request.getHeader("Authorization");
  96. // si hay un token presente, entonces lo validamos
  97. if (token != null) {
  98. String user = Jwts.parser()
  99. .setSigningKey("P@tit0")
  100. .parseClaimsJws(token.replace("Bearer", "")) //este metodo es el que valida
  101. .getBody()
  102. .getSubject();
  103.  
  104. // Recordamos que para las demás peticiones que no sean /login
  105. // no requerimos una autenticacion por username/password
  106. // por este motivo podemos devolver un UsernamePasswordAuthenticationToken sin password
  107. return user != null ?
  108. new UsernamePasswordAuthenticationToken(user, null, emptyList()) :
  109. null;
  110. }
  111. return null;
  112. }
  113. }
  114.  
  115. @Configuration
  116. @EnableWebSecurity
  117. public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  118. @Autowired
  119. private IUsuarioService usuarioService;
  120. @Override
  121. protected void configure(HttpSecurity http) throws Exception {
  122. http.csrf().disable().authorizeRequests()
  123. .antMatchers("/").permitAll()
  124. .antMatchers(HttpMethod.POST, "/login").permitAll()
  125. .anyRequest().authenticated()
  126. .and()
  127. // // We filter the api/login requests
  128. .addFilterBefore(new JWTLoginFilter("/login", authenticationManager()),
  129. UsernamePasswordAuthenticationFilter.class)
  130. // And filter other requests to check the presence of JWT in header
  131. .addFilterBefore(new JWTAuthenticationFilter(),
  132. UsernamePasswordAuthenticationFilter.class);
  133. }
  134.  
  135. @Override
  136. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  137. // Create a default account
  138. Usuario usuario = usuarioService.findAll().stream().filter(U -> U.getIdusuario().trim().equals("ADMINISTRADOR")).findFirst().orElse(null);
  139. auth.inMemoryAuthentication()
  140. .withUser(usuario.getIdusuario().trim())
  141. .password(usuario.getPassword())
  142. .roles("ADMIN");
  143. }
  144. }
  145.  
  146. this.axios.get('http://localhost:8080/api/teatro', {
  147. headers: {
  148. 'Content-Type' : 'application/json',
  149. 'Authorization': 'Bearer ' + 'hola'
  150. }
  151. })
  152.  
  153. @Override
  154. public Authentication attemptAuthentication(
  155. HttpServletRequest req, HttpServletResponse res)
  156. throws AuthenticationException, IOException, ServletException {
  157.  
  158. .readValue(req.getInputStream(), AccountCredentials.class);
  159. return getAuthenticationManager().authenticate(
  160. new UsernamePasswordAuthenticationToken(
  161. creds.getUsername(),
  162. ClavePass.Encriptar(creds.getPassword()),
  163. Collections.emptyList()
  164. )
  165. );
Add Comment
Please, Sign In to add comment