Skip to content

Commit 2a1db7b

Browse files
finalizando tópicos em informática
1 parent 7e34541 commit 2a1db7b

22 files changed

+409
-76
lines changed

README.md

+5-3
Original file line numberDiff line numberDiff line change
@@ -106,12 +106,14 @@ POST localhost:4040/users/sign-up
106106
107107
~~~json
108108
{
109-
"username" : "fulano",
110-
"password" : "123"
109+
"username": "fulano",
110+
"password": "123",
111+
"authorizations": [
112+
{ "type": "ROLE_USER" }
113+
]
111114
}
112115
~~~
113116

114-
115117
> **Listagem:** lista todas as imagens cadastradas no banco de dados PostgreSQL por método GET, onde todos os usuários podem acessar a lista de imagens:
116118
117119
```

db/create-tables.sql

+24-2
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,9 @@ CREATE USER api_restful WITH PASSWORD 'api_spring_restful';
1111
CREATE TABLE public.users
1212
(
1313
id bigint NOT NULL GENERATED BY DEFAULT AS IDENTITY ( INCREMENT 1 START 1 MINVALUE 1 MAXVALUE 9223372036854775807 CACHE 1 ),
14-
username character varying(255) COLLATE pg_catalog."default",
1514
password character varying(255) COLLATE pg_catalog."default",
16-
admin BOOLEAN NOT NULL
15+
username character varying(255) COLLATE pg_catalog."default",
16+
CONSTRAINT users_pkey PRIMARY KEY (id)
1717
)
1818
WITH (
1919
OIDS = FALSE
@@ -23,9 +23,31 @@ TABLESPACE pg_default;
2323
ALTER TABLE public.users
2424
OWNER to api_restful;
2525

26+
-- Criação da tabela para o controle de autorizações
27+
28+
CREATE TABLE public.user_authorizations
29+
(
30+
id bigint NOT NULL GENERATED BY DEFAULT AS IDENTITY ( INCREMENT 1 START 1 MINVALUE 1 MAXVALUE 9223372036854775807 CACHE 1 ),
31+
type character varying(255) COLLATE pg_catalog."default",
32+
user_id bigint,
33+
CONSTRAINT user_authorizations_pkey PRIMARY KEY (id),
34+
CONSTRAINT fkgek2c3qxjc3g29pk0gaqkythi FOREIGN KEY (user_id)
35+
REFERENCES public.users (id) MATCH SIMPLE
36+
ON UPDATE NO ACTION
37+
ON DELETE NO ACTION
38+
)
39+
WITH (
40+
OIDS = FALSE
41+
)
42+
TABLESPACE pg_default;
43+
44+
ALTER TABLE public.user_authorizations
45+
OWNER to api_restful;
46+
2647
-- Copiando os dados do usuário admin para o banco de dados a partir de um arquivo em csv
2748

2849
\COPY public.users FROM 'csv/users.csv' DELIMITER ';' CSV HEADER;
50+
\COPY public.authorization FROM 'csv/user_authorizations.csv' DELIMITER ';' CSV HEADER;
2951

3052
-- Criação da tabela para o cadastro de municípios
3153

db/csv/user_authorizations.csv

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
id;type;users_id
2+
1;ROLE_ADMIN;1
3+
2;ROLE_USER;1
4+
3;ROLE_USER;2

db/csv/users.csv

+3-2
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
1-
id;username;password;admin
2-
1;admin;$2a$10$Iy9nZ.bPRh87DKMJfipQSur5zLO8TZXeDzd/57mE5KCt2IPAPiqp.;true
1+
id;username;password
2+
1;admin;$2a$10$Iy9nZ.bPRh87DKMJfipQSur5zLO8TZXeDzd/57mE5KCt2IPAPiqp.
3+
2;user;$2a$10$Iy9nZ.bPRh87DKMJfipQSur5zLO8TZXeDzd/57mE5KCt2IPAPiqp.

docs/assets/db-model.png

16.6 KB
Loading
+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
{
2+
"username": "fulano",
3+
"password": "123",
4+
"authorizations": [
5+
{ "type": "ROLE_USER" }
6+
]
7+
}

src/main/java/api/restful/controller/UserController.java

+6-8
Original file line numberDiff line numberDiff line change
@@ -7,28 +7,26 @@
77
import org.springframework.web.bind.annotation.RequestMethod;
88
import org.springframework.web.bind.annotation.RestController;
99
import org.springframework.web.server.ResponseStatusException;
10+
import org.springframework.beans.factory.annotation.Autowired;
1011

1112
import api.restful.model.user.AuthUser;
12-
import api.restful.model.user.AuthUserRepository;
1313
import api.restful.handler.CustomMessage;
14+
import api.restful.services.AuthorizationServiceImpl;
1415

1516
@RestController
1617
@RequestMapping("/users")
1718
public class UserController {
19+
@Autowired
20+
private AuthorizationServiceImpl authorizationServiceImpl;
1821

19-
private AuthUserRepository userRepository;
22+
@Autowired
2023
private BCryptPasswordEncoder bCryptPasswordEncoder;
2124

22-
public UserController(AuthUserRepository applicationUserRepository, BCryptPasswordEncoder bCryptPasswordEncoder) {
23-
this.userRepository = applicationUserRepository;
24-
this.bCryptPasswordEncoder = bCryptPasswordEncoder;
25-
}
26-
2725
@RequestMapping(value = "/sign-up", method = RequestMethod.POST, produces = "application/json")
2826
public CustomMessage signUp(@RequestBody AuthUser user) {
2927
try {
3028
user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
31-
userRepository.save(user);
29+
this.authorizationServiceImpl.createUser(user);
3230
return new CustomMessage(200, "Saved");
3331
} catch (Exception e) {
3432
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "User not found", e);

src/main/java/api/restful/controller/jwt/JWTAuthenticationFilter.java

+24-3
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,12 @@
22

33
import com.auth0.jwt.JWT;
44
import api.restful.model.user.AuthUser;
5+
import api.restful.model.views.UserCache;
6+
import api.restful.model.user.Authorization;
7+
import api.restful.model.user.AuthorizationRepository;
58
import api.restful.model.views.ResponseToken;
9+
import api.restful.services.AuthorizationServiceImpl;
10+
611
import com.google.gson.Gson;
712
import com.fasterxml.jackson.databind.ObjectMapper;
813
import org.springframework.security.authentication.AuthenticationManager;
@@ -12,6 +17,9 @@
1217
import org.springframework.security.core.userdetails.User;
1318
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
1419

20+
import org.springframework.security.core.GrantedAuthority;
21+
import org.springframework.security.core.authority.SimpleGrantedAuthority;
22+
1523
import javax.servlet.FilterChain;
1624
import javax.servlet.ServletException;
1725
import javax.servlet.http.HttpServletRequest;
@@ -20,6 +28,8 @@
2028
import java.io.PrintWriter;
2129
import java.util.ArrayList;
2230
import java.util.Date;
31+
import java.util.List;
32+
import java.util.Collection;
2333

2434
import static com.auth0.jwt.algorithms.Algorithm.HMAC512;
2535
import static api.restful.controller.security.SecurityConstants.EXPIRATION_TIME;
@@ -37,11 +47,13 @@ public JWTAuthenticationFilter(AuthenticationManager authenticationManager) {
3747
public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res) throws AuthenticationException {
3848
try {
3949
AuthUser creds = new ObjectMapper().readValue(req.getInputStream(), AuthUser.class);
50+
List<GrantedAuthority> updatedAuthorities = new ArrayList<>();
51+
updatedAuthorities.add(new SimpleGrantedAuthority("ROLE_USER"));
4052
return authenticationManager.authenticate(
4153
new UsernamePasswordAuthenticationToken(
4254
creds.getUsername(),
4355
creds.getPassword(),
44-
new ArrayList<>()
56+
updatedAuthorities
4557
)
4658
);
4759
} catch (IOException e) {
@@ -51,11 +63,20 @@ public Authentication attemptAuthentication(HttpServletRequest req, HttpServletR
5163

5264
@Override
5365
protected void successfulAuthentication(HttpServletRequest req, HttpServletResponse res, FilterChain chain, Authentication auth) throws IOException, ServletException {
66+
List<Authorization> authorizations = (List<Authorization>) auth.getAuthorities();
67+
List<String> aut = new ArrayList<String>();
68+
for (Authorization autho : authorizations) {
69+
aut.add(autho.getAuthority());
70+
}
71+
String username = ((User) auth.getPrincipal()).getUsername();
72+
String password = ((User) auth.getPrincipal()).getPassword();
73+
UserCache user = new UserCache(username, password, aut);
74+
String jsonUser = new Gson().toJson(user);
5475
String token = JWT.create()
55-
.withSubject(((User) auth.getPrincipal()).getUsername())
76+
.withSubject(jsonUser)
5677
.withExpiresAt(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
5778
.sign(HMAC512(SECRET.getBytes()));
58-
ResponseToken response = new ResponseToken(200, token, true, "Use this token to API CRUD options");
79+
ResponseToken response = new ResponseToken(200, token, user, "Use this token to API CRUD options");
5980
String jsonString = new Gson().toJson(response);
6081
PrintWriter out = res.getWriter();
6182
res.addHeader(HEADER_STRING, token);

src/main/java/api/restful/controller/jwt/JWTAuthorizationFilter.java

+20-7
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,27 @@
22

33
import com.auth0.jwt.JWT;
44
import com.auth0.jwt.algorithms.Algorithm;
5+
import com.google.gson.Gson;
56

67
import org.springframework.security.authentication.AuthenticationManager;
78
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
89
import org.springframework.security.core.context.SecurityContextHolder;
910
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
11+
import org.springframework.security.core.GrantedAuthority;
12+
import org.springframework.security.core.authority.SimpleGrantedAuthority;
13+
14+
import api.restful.model.user.AuthUser;
15+
import api.restful.model.user.Authorization;
16+
import api.restful.model.views.UserCache;
1017

1118
import javax.servlet.FilterChain;
1219
import javax.servlet.ServletException;
1320
import javax.servlet.http.HttpServletRequest;
1421
import javax.servlet.http.HttpServletResponse;
1522
import java.io.IOException;
1623
import java.util.ArrayList;
24+
import java.util.List;
25+
import java.util.Collection;
1726

1827
import static api.restful.controller.security.SecurityConstants.HEADER_STRING;
1928
import static api.restful.controller.security.SecurityConstants.SECRET;
@@ -26,23 +35,27 @@ public JWTAuthorizationFilter(AuthenticationManager authManager) {
2635

2736
@Override
2837
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException {
29-
UsernamePasswordAuthenticationToken authentication = getAuthentication(req);
30-
SecurityContextHolder.getContext().setAuthentication(authentication);
38+
this.getAuthentication(req);
3139
chain.doFilter(req, res);
3240
}
3341

34-
private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
42+
private void getAuthentication(HttpServletRequest request) {
3543
String token = request.getHeader(HEADER_STRING);
3644
if (token != null) {
37-
String user = JWT.require(Algorithm.HMAC512(SECRET.getBytes()))
45+
String jsonUser = JWT.require(Algorithm.HMAC512(SECRET.getBytes()))
3846
.build()
3947
.verify(token)
4048
.getSubject();
49+
UserCache user = new Gson().fromJson(jsonUser, UserCache.class);
50+
List<GrantedAuthority> updatedAuthorities = new ArrayList<>();
51+
for (String role : user.getRole()) {
52+
updatedAuthorities.add(new SimpleGrantedAuthority(role));
53+
}
4154
if (user != null) {
42-
return new UsernamePasswordAuthenticationToken(user, null, new ArrayList<>());
55+
UsernamePasswordAuthenticationToken authentication =
56+
new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword(), updatedAuthorities);
57+
SecurityContextHolder.getContext().setAuthentication(authentication);
4358
}
44-
return null;
4559
}
46-
return null;
4760
}
4861
}

src/main/java/api/restful/controller/security/WebSecurity.java

+12-8
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,13 @@
1010
import org.springframework.web.cors.CorsConfiguration;
1111
import org.springframework.web.cors.CorsConfigurationSource;
1212
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
13+
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
14+
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
1315

1416
import api.restful.services.UserDetailsServiceImpl;
1517
import api.restful.controller.jwt.JWTAuthorizationFilter;
1618
import api.restful.model.user.AuthUser;
19+
import api.restful.model.user.AuthorizationRepository;
1720
import api.restful.controller.jwt.JWTAuthenticationFilter;
1821

1922
import org.springframework.context.annotation.Bean;
@@ -24,6 +27,7 @@
2427

2528
@Configuration
2629
@EnableWebSecurity
30+
@EnableGlobalMethodSecurity(prePostEnabled = true)
2731
public class WebSecurity extends WebSecurityConfigurerAdapter {
2832
@Autowired
2933
private UserDetailsServiceImpl userDetailsService;
@@ -38,14 +42,14 @@ public WebSecurity(UserDetailsServiceImpl userDetailsService, BCryptPasswordEnco
3842

3943
@Override
4044
protected void configure(HttpSecurity http) throws Exception {
41-
http.cors().and().csrf().disable().authorizeRequests()
42-
.antMatchers(HttpMethod.POST, "/users/sign-up").permitAll()
43-
.antMatchers(HttpMethod.GET, "/catalog/list").permitAll()
44-
.anyRequest().authenticated()
45-
.and()
46-
.addFilter(new JWTAuthenticationFilter(authenticationManager()))
47-
.addFilter(new JWTAuthorizationFilter(authenticationManager()))
48-
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
45+
http.cors().and().csrf().disable()
46+
.addFilterBefore(new JWTAuthorizationFilter(authenticationManager()), UsernamePasswordAuthenticationFilter.class)
47+
.addFilterBefore(new JWTAuthenticationFilter(authenticationManager()), UsernamePasswordAuthenticationFilter.class)
48+
.authorizeRequests()
49+
.antMatchers(HttpMethod.GET, "/catalog/list").permitAll()
50+
.anyRequest().authenticated()
51+
.and()
52+
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
4953
}
5054

5155
@Override

src/main/java/api/restful/model/catalog/Coordinate.java

+2-2
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
import api.restful.model.views.Views;
1313

1414
@Entity
15-
@Table(name="coordinate")
15+
@Table(name = "coordinate")
1616
public class Coordinate {
1717
@Id
1818
@JsonView(Views.Internal.class)
@@ -30,7 +30,7 @@ public class Coordinate {
3030

3131
@ManyToOne
3232
@JsonView(Views.Internal.class)
33-
@JoinColumn(name="catalog_id")
33+
@JoinColumn(name = "catalog_id")
3434
private Catalog catalog;
3535

3636
public Coordinate() {}

0 commit comments

Comments
 (0)