Skip to content

Commit 25c0ddb

Browse files
Configurado a autenticacao via token, utilizando spring configuration
1 parent c5eaceb commit 25c0ddb

File tree

5 files changed

+110
-8
lines changed

5 files changed

+110
-8
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
package br.com.testesantanderway.config.security;
2+
3+
import br.com.testesantanderway.modelo.Cliente;
4+
import br.com.testesantanderway.modelo.Perfil;
5+
import br.com.testesantanderway.repository.ClienteRepository;
6+
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
7+
import org.springframework.security.core.context.SecurityContextHolder;
8+
import org.springframework.security.core.token.TokenService;
9+
import org.springframework.web.filter.OncePerRequestFilter;
10+
11+
import javax.servlet.FilterChain;
12+
import javax.servlet.ServletException;
13+
import javax.servlet.http.HttpServletRequest;
14+
import javax.servlet.http.HttpServletResponse;
15+
import java.io.IOException;
16+
17+
public class AutenticacaoViaTokenFilter extends OncePerRequestFilter {
18+
private ServicoDeToken tokenService;
19+
private ClienteRepository repository;
20+
21+
public AutenticacaoViaTokenFilter(ServicoDeToken tokenService, ClienteRepository repository) {
22+
this.tokenService = tokenService;
23+
this.repository = repository;
24+
}
25+
26+
@Override
27+
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
28+
FilterChain filterChain) throws ServletException, IOException {
29+
String token = recuperarToken(request);
30+
boolean valido = tokenService.isTokenValido(token);
31+
if (valido){
32+
autenticarCliente(token);
33+
}
34+
35+
36+
filterChain.doFilter(request, response);
37+
}
38+
39+
private void autenticarCliente(String token) {
40+
String idCliente = tokenService.getIdCliente(token);
41+
Cliente cliente = repository.findById(idCliente).get();
42+
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(cliente,
43+
null, cliente.getAuthorities());
44+
SecurityContextHolder.getContext().setAuthentication(authentication);
45+
}
46+
47+
private String recuperarToken(HttpServletRequest request) {
48+
String token = request.getHeader("Authorization");
49+
if (token == null || token.isEmpty() || !token.startsWith("Bearer ")){
50+
return null;
51+
}
52+
53+
return token.substring(7, token.length());
54+
}
55+
}

testeSantanderWay/src/main/java/br/com/testesantanderway/config/security/ConfigSeguranca.java

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package br.com.testesantanderway.config.security;
22

3+
import br.com.testesantanderway.repository.ClienteRepository;
34
import org.springframework.beans.factory.annotation.Autowired;
45
import org.springframework.context.annotation.Bean;
56
import org.springframework.context.annotation.Configuration;
@@ -12,12 +13,18 @@
1213
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
1314
import org.springframework.security.config.http.SessionCreationPolicy;
1415
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
16+
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
1517

1618
@EnableWebSecurity
1719
@Configuration
1820
public class ConfigSeguranca extends WebSecurityConfigurerAdapter {
1921
@Autowired
2022
private AutenticacaoService autenticacaoService;
23+
@Autowired
24+
private ServicoDeToken tokenService;
25+
@Autowired
26+
private ClienteRepository clienteRepository;
27+
2128

2229
@Override
2330
@Bean
@@ -44,7 +51,8 @@ protected void configure(HttpSecurity http) throws Exception {
4451
.permitAll()
4552
.anyRequest().authenticated()
4653
.and().csrf().disable()
47-
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
54+
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
55+
.and().addFilterBefore(new AutenticacaoViaTokenFilter(tokenService, clienteRepository), UsernamePasswordAuthenticationFilter.class);
4856
}
4957

5058
//Recursos estáticos(js, css, img, etc.)

testeSantanderWay/src/main/java/br/com/testesantanderway/config/security/ServicoDeToken.java

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package br.com.testesantanderway.config.security;
22

33
import br.com.testesantanderway.modelo.Cliente;
4+
import io.jsonwebtoken.Claims;
45
import io.jsonwebtoken.Jwts;
56
import io.jsonwebtoken.SignatureAlgorithm;
67
import org.springframework.beans.factory.annotation.Value;
@@ -28,4 +29,19 @@ public String gerarToken(Authentication authentication) {
2829
.setExpiration(dataExpiracao)
2930
.signWith(SignatureAlgorithm.HS256, secret).compact();
3031
}
32+
33+
public boolean isTokenValido(String token){
34+
try {
35+
Jwts.parser().setSigningKey(this.secret).parseClaimsJws(token);
36+
37+
return true;
38+
} catch (Exception e){
39+
return false;
40+
}
41+
}
42+
43+
public String getIdCliente(String token){
44+
Claims claims = Jwts.parser().setSigningKey(this.secret).parseClaimsJws(token).getBody();
45+
return claims.getSubject();
46+
}
3147
}

testeSantanderWay/src/main/java/br/com/testesantanderway/controller/AuthController.java

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,20 +2,18 @@
22

33
import br.com.testesantanderway.config.security.ServicoDeToken;
44
import br.com.testesantanderway.controller.form.AuthForm;
5+
import br.com.testesantanderway.dto.TokenDTO;
56
import org.springframework.beans.factory.annotation.Autowired;
67
import org.springframework.http.ResponseEntity;
78
import org.springframework.security.authentication.AuthenticationManager;
89
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
910
import org.springframework.security.core.Authentication;
1011
import org.springframework.security.core.AuthenticationException;
11-
import org.springframework.security.core.token.TokenService;
1212
import org.springframework.web.bind.annotation.PostMapping;
1313
import org.springframework.web.bind.annotation.RequestBody;
1414
import org.springframework.web.bind.annotation.RequestMapping;
1515
import org.springframework.web.bind.annotation.RestController;
1616

17-
import javax.validation.Valid;
18-
1917
@RestController
2018
@RequestMapping("/auth")
2119
public class AuthController {
@@ -25,16 +23,14 @@ public class AuthController {
2523
private ServicoDeToken servicoDeToken;
2624

2725
@PostMapping
28-
public ResponseEntity<?> login(@RequestBody AuthForm form){
26+
public ResponseEntity<TokenDTO> login(@RequestBody AuthForm form){
2927
UsernamePasswordAuthenticationToken dadosLogin = form.converter();
3028
try {
3129
Authentication authentication = authManager.authenticate(dadosLogin);
3230
String token = servicoDeToken.gerarToken(authentication);
33-
System.out.println(token);
34-
return ResponseEntity.ok().build();
31+
return ResponseEntity.ok(new TokenDTO(token, "Bearer"));
3532
} catch (AuthenticationException e){
3633
return ResponseEntity.badRequest().build();
3734
}
38-
3935
}
4036
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package br.com.testesantanderway.dto;
2+
3+
public class TokenDTO {
4+
private String token;
5+
private String tipo;
6+
7+
public TokenDTO(String token, String tipo) {
8+
this.token = token;
9+
this.tipo = tipo;
10+
}
11+
12+
public String getToken() {
13+
return token;
14+
}
15+
16+
public void setToken(String token) {
17+
this.token = token;
18+
}
19+
20+
public String getTipo() {
21+
return tipo;
22+
}
23+
24+
public void setTipo(String tipo) {
25+
this.tipo = tipo;
26+
}
27+
}

0 commit comments

Comments
 (0)