Skip to content
Snippets Groups Projects
Commit de09a3bd authored by hugcubi's avatar hugcubi
Browse files

Ligeros reajustes

parent d525f66d
No related branches found
No related tags found
1 merge request!36Develop
Showing
with 59 additions and 54 deletions
...@@ -11,7 +11,7 @@ import org.springframework.stereotype.Component; ...@@ -11,7 +11,7 @@ import org.springframework.stereotype.Component;
import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate; import org.springframework.web.client.RestTemplate;
import com.uva.authentication.models.RegisterRequest; import com.uva.authentication.models.auth.RegisterRequest;
import com.uva.authentication.models.remote.User; import com.uva.authentication.models.remote.User;
@Component @Component
...@@ -20,7 +20,7 @@ public class UserAPI { ...@@ -20,7 +20,7 @@ public class UserAPI {
@Autowired @Autowired
private RestTemplate restTemplate; private RestTemplate restTemplate;
@Value("${external.services.users.url}") @Value("${services.external.users.url}")
private String USER_API_URL; private String USER_API_URL;
/** /**
......
...@@ -8,7 +8,8 @@ import org.springframework.http.ResponseEntity; ...@@ -8,7 +8,8 @@ import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.HttpClientErrorException;
import com.uva.authentication.models.*; import com.uva.authentication.models.auth.LoginRequest;
import com.uva.authentication.models.auth.RegisterRequest;
import com.uva.authentication.services.AuthService; import com.uva.authentication.services.AuthService;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
...@@ -47,7 +48,7 @@ public class AuthController { ...@@ -47,7 +48,7 @@ public class AuthController {
@PostMapping("/password") @PostMapping("/password")
public ResponseEntity<?> changePassword(@RequestBody Map<String, String> json, public ResponseEntity<?> changePassword(@RequestBody Map<String, String> json,
@RequestHeader(value = "Authorization", required = false) String authorization) { @RequestHeader(value = "Authorization", required = true) String authorization) {
if (authorization == null || !authorization.startsWith("Bearer ")) if (authorization == null || !authorization.startsWith("Bearer "))
return new ResponseEntity<>(HttpStatus.FORBIDDEN); return new ResponseEntity<>(HttpStatus.FORBIDDEN);
...@@ -61,7 +62,7 @@ public class AuthController { ...@@ -61,7 +62,7 @@ public class AuthController {
@PostMapping("/delete/{id}") @PostMapping("/delete/{id}")
public Object postMethodName(@PathVariable int id, @RequestBody Map<String, String> json, public Object postMethodName(@PathVariable int id, @RequestBody Map<String, String> json,
@RequestHeader(value = "Authorization", required = false) String authorization) { @RequestHeader(value = "Authorization", required = true) String authorization) {
if (authorization == null || !authorization.startsWith("Bearer ")) if (authorization == null || !authorization.startsWith("Bearer "))
return new ResponseEntity<>(HttpStatus.FORBIDDEN); return new ResponseEntity<>(HttpStatus.FORBIDDEN);
......
...@@ -9,11 +9,11 @@ import org.springframework.web.bind.annotation.RequestMapping; ...@@ -9,11 +9,11 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import com.uva.authentication.models.JwtAuth; import com.uva.authentication.models.jwt.JwtAuth;
import com.uva.authentication.services.TokenService; import com.uva.authentication.services.TokenService;
@RestController @RestController
@RequestMapping("/token") @RequestMapping("token")
public class TokenController { public class TokenController {
@Autowired @Autowired
......
package com.uva.authentication.models;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@Data
@NoArgsConstructor
@AllArgsConstructor
public class TokenRequest {
private String token;
}
package com.uva.authentication.models; package com.uva.authentication.models.auth;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Data; import lombok.Data;
......
package com.uva.authentication.models; package com.uva.authentication.models.auth;
import com.uva.authentication.models.remote.UserRol; import com.uva.authentication.models.remote.UserRol;
......
package com.uva.authentication.models; package com.uva.authentication.models.jwt;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Data; import lombok.Data;
......
package com.uva.authentication.models; package com.uva.authentication.models.jwt;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.util.Date;
import com.auth0.jwt.interfaces.Claim; import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT; import com.auth0.jwt.interfaces.DecodedJWT;
import com.uva.authentication.models.remote.UserRol;
import lombok.Data; import lombok.Data;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import lombok.ToString;
@Getter @Getter
@Setter @Setter
@Data @Data
public class TokenData { @ToString
public class JwtData {
private Integer id; private Integer id;
private String name; private String name;
private String email; private String email;
private String rol; private UserRol rol;
private String service; private String service;
private String subject; private String subject;
private String audience; private String audience;
private Long ttl; private Long ttl;
public TokenData(DecodedJWT decoded, long ttl) { private Date issuedAt;
private Date expiresAt;
public JwtData(DecodedJWT decoded, long ttl) {
subject = decoded.getSubject(); subject = decoded.getSubject();
if (decoded.getAudience() != null && !decoded.getAudience().isEmpty())
audience = decoded.getAudience().get(0); audience = decoded.getAudience().get(0);
this.ttl = ttl; this.ttl = ttl;
issuedAt = decoded.getIssuedAt();
expiresAt = decoded.getExpiresAt();
for (Field field : this.getClass().getDeclaredFields()) { for (Field field : this.getClass().getDeclaredFields()) {
field.setAccessible(true); field.setAccessible(true);
// Verificamos si el campo está en el mapa y asignamos el valor // Verificamos si el campo está en el mapa y asignamos el valor
Claim claim = decoded.getClaim(field.getName()); Claim claim = decoded.getClaim(field.getName());
if (!claim.isMissing()) { System.out.println(field.getName() + " => " + claim.isMissing() + " " + claim.isNull() + " " + claim.asString()
+ " " + decoded.getClaim("rol").asString());
if (!claim.isNull()) {
String value = claim.asString();
try { try {
// Dependiendo del tipo de campo, asignamos el valor // Dependiendo del tipo de campo, asignamos el valor
if (field.getType() == Integer.class) { if (field.getType() == Integer.class) {
field.set(this, Integer.parseInt(claim.asString())); field.set(this, claim.asInt());
} else if (field.getType() == String.class) { } else if (field.getType() == String.class) {
field.set(this, claim.asString()); field.set(this, claim.asString());
} else if (field.getType() == UserRol.class) {
if (value != null)
field.set(this, UserRol.valueOf(value));
} }
} catch (IllegalAccessException e) { } catch (IllegalAccessException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
} }
System.out.println("\n\n\n<-- " + this + " -->");
} }
public boolean isAdmin() { public boolean isAdmin() {
return rol != null && rol == "ADMIN"; return rol != null && rol == UserRol.ADMIN;
} }
} }
\ No newline at end of file
package com.uva.authentication.models.remote; package com.uva.authentication.models.remote;
import com.uva.authentication.models.RegisterRequest; import com.uva.authentication.models.auth.RegisterRequest;
import lombok.Data; import lombok.Data;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
......
...@@ -6,13 +6,12 @@ import org.springframework.http.HttpStatus; ...@@ -6,13 +6,12 @@ import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.servlet.function.EntityResponse;
import com.uva.authentication.api.UserAPI; import com.uva.authentication.api.UserAPI;
import com.uva.authentication.models.JwtAuth; import com.uva.authentication.models.auth.LoginRequest;
import com.uva.authentication.models.LoginRequest; import com.uva.authentication.models.auth.RegisterRequest;
import com.uva.authentication.models.RegisterRequest; import com.uva.authentication.models.jwt.JwtAuth;
import com.uva.authentication.models.TokenData; import com.uva.authentication.models.jwt.JwtData;
import com.uva.authentication.models.remote.User; import com.uva.authentication.models.remote.User;
import com.uva.authentication.utils.JwtUtil; import com.uva.authentication.utils.JwtUtil;
import com.uva.authentication.utils.SecurityUtils; import com.uva.authentication.utils.SecurityUtils;
...@@ -78,7 +77,7 @@ public class AuthService { ...@@ -78,7 +77,7 @@ public class AuthService {
} }
public ResponseEntity<?> changePassword(String token, String actualPass, String newPass) { public ResponseEntity<?> changePassword(String token, String actualPass, String newPass) {
TokenData decoded = jwtUtil.decodeToken(token); JwtData decoded = jwtUtil.decodeToken(token);
if (decoded == null) if (decoded == null)
return new ResponseEntity<>(HttpStatus.FORBIDDEN); return new ResponseEntity<>(HttpStatus.FORBIDDEN);
...@@ -102,7 +101,7 @@ public class AuthService { ...@@ -102,7 +101,7 @@ public class AuthService {
} }
public ResponseEntity<?> deleteUser(String token, int id, String password) { public ResponseEntity<?> deleteUser(String token, int id, String password) {
TokenData decoded = jwtUtil.decodeToken(token); JwtData decoded = jwtUtil.decodeToken(token);
if (decoded == null) if (decoded == null)
return new ResponseEntity<>(HttpStatus.FORBIDDEN); return new ResponseEntity<>(HttpStatus.FORBIDDEN);
......
...@@ -5,8 +5,8 @@ import org.springframework.http.HttpStatus; ...@@ -5,8 +5,8 @@ import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import com.uva.authentication.models.JwtAuth; import com.uva.authentication.models.jwt.JwtAuth;
import com.uva.authentication.models.TokenData; import com.uva.authentication.models.jwt.JwtData;
import com.uva.authentication.utils.JwtUtil; import com.uva.authentication.utils.JwtUtil;
@Service @Service
...@@ -27,7 +27,7 @@ public class TokenService { ...@@ -27,7 +27,7 @@ public class TokenService {
} }
public ResponseEntity<?> getTokenInf(String token) { public ResponseEntity<?> getTokenInf(String token) {
TokenData decoded = jwtUtil.decodeToken(token); JwtData decoded = jwtUtil.decodeToken(token);
if (decoded == null) if (decoded == null)
return new ResponseEntity<>("Token has expire or is malformed", HttpStatus.FORBIDDEN); return new ResponseEntity<>("Token has expire or is malformed", HttpStatus.FORBIDDEN);
return ResponseEntity.ok(decoded); return ResponseEntity.ok(decoded);
......
...@@ -8,7 +8,7 @@ import org.springframework.web.client.HttpClientErrorException; ...@@ -8,7 +8,7 @@ import org.springframework.web.client.HttpClientErrorException;
import com.auth0.jwt.JWT; import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.algorithms.Algorithm;
import com.uva.authentication.models.TokenData; import com.uva.authentication.models.jwt.JwtData;
import com.uva.authentication.models.remote.User; import com.uva.authentication.models.remote.User;
import com.auth0.jwt.interfaces.DecodedJWT; import com.auth0.jwt.interfaces.DecodedJWT;
...@@ -32,14 +32,15 @@ public class JwtUtil { ...@@ -32,14 +32,15 @@ public class JwtUtil {
private String token; private String token;
private static final String SERVICE = "AUTH_SERVICES"; @Value("${spring.application.name}")
private String service;
public String getOwnInternalToken() { public String getOwnInternalToken() {
// Si no hay token, no es valido o quedan 10 seg para caducar se genera otro // Si no hay token, no es valido o quedan 10 seg para caducar se genera otro
if (token == null || validate(token) == null || if (token == null || validate(token) == null ||
decodeToken(token).getTtl() <= 10) { decodeToken(token).getTtl() <= 10) {
token = generateInternalToken(SERVICE); token = generateInternalToken(service);
} }
return token; return token;
...@@ -70,6 +71,8 @@ public class JwtUtil { ...@@ -70,6 +71,8 @@ public class JwtUtil {
public String generateToken(User user) { public String generateToken(User user) {
Algorithm algorithm = Algorithm.HMAC256(secretKey); Algorithm algorithm = Algorithm.HMAC256(secretKey);
System.out.println("\n\n<-- " + user + " " + user.getId() + " -->");
return JWT return JWT
.create() .create()
...@@ -77,7 +80,7 @@ public class JwtUtil { ...@@ -77,7 +80,7 @@ public class JwtUtil {
.withIssuedAt(new Date()) .withIssuedAt(new Date())
.withExpiresAt(new Date(System.currentTimeMillis() + extJwtExpiration * 1000)) .withExpiresAt(new Date(System.currentTimeMillis() + extJwtExpiration * 1000))
.withSubject(SERVICE) .withSubject(service)
.withAudience("EXTERNAL") .withAudience("EXTERNAL")
// DATA // DATA
...@@ -97,11 +100,11 @@ public class JwtUtil { ...@@ -97,11 +100,11 @@ public class JwtUtil {
} }
} }
public TokenData decodeToken(String token) { public JwtData decodeToken(String token) {
DecodedJWT decoded = validate(token); DecodedJWT decoded = validate(token);
if (decoded == null) if (decoded == null)
return null; return null;
return new TokenData(decoded, calculateTTL(decoded)); return new JwtData(decoded, calculateTTL(decoded));
} }
private long calculateTTL(DecodedJWT decodedJWT) { private long calculateTTL(DecodedJWT decodedJWT) {
......
...@@ -2,9 +2,10 @@ spring.application.name=authService ...@@ -2,9 +2,10 @@ spring.application.name=authService
server.port=8101 server.port=8101
security.jwt.secret-key=MiClaveDeSeguridadMuyLargaParaQueNoFalleSpringBoot security.jwt.secret-key=MiClaveDeSeguridadMuyLargaParaQueNoFalleSpringBoot
# 1h in millisecond # 1h in seconds
security.jwt.external.expiration=3600 security.jwt.external.expiration=3600
security.jwt.internal.expiration=20 # 10min in seconds
security.jwt.internal.expiration=600
security.jwt.kid=cYz3kNRLAirxVhHXQ5rh5xKrOwHwZVui security.jwt.kid=cYz3kNRLAirxVhHXQ5rh5xKrOwHwZVui
external.services.users.url=http://localhost:8201/users services.external.users.url=http://localhost:8201/users
\ No newline at end of file \ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please to comment