Revize 94cc7ade
Přidáno uživatelem Petr Urban před asi 2 roky(ů)
pom.xml | ||
---|---|---|
28 | 28 |
|
29 | 29 |
<dependencies> |
30 | 30 |
|
31 |
|
|
31 | 32 |
<dependency> |
32 | 33 |
<groupId>org.springframework.boot</groupId> |
33 | 34 |
<artifactId>spring-boot-starter</artifactId> |
src/main/java/cz/zcu/fav/kiv/antipatterndetectionapp/v2/security/JwtAuthenticationFilter.java | ||
---|---|---|
6 | 6 |
import cz.zcu.fav.kiv.antipatterndetectionapp.v2.service.OAuthServiceImpl; |
7 | 7 |
import org.springframework.beans.factory.annotation.Autowired; |
8 | 8 |
import org.springframework.core.annotation.Order; |
9 |
import org.springframework.http.ResponseEntity;
|
|
9 |
import org.springframework.http.*;
|
|
10 | 10 |
import org.springframework.security.authentication.AuthenticationProvider; |
11 |
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; |
|
12 |
import org.springframework.security.core.Authentication; |
|
13 |
import org.springframework.security.core.context.SecurityContextHolder; |
|
11 | 14 |
import org.springframework.stereotype.Component; |
15 |
import org.springframework.web.client.RestTemplate; |
|
12 | 16 |
import org.springframework.web.filter.OncePerRequestFilter; |
13 | 17 |
|
14 | 18 |
import javax.servlet.FilterChain; |
... | ... | |
23 | 27 |
@Component |
24 | 28 |
public class JwtAuthenticationFilter extends OncePerRequestFilter { |
25 | 29 |
|
30 |
private OAuthService oAuthService; |
|
26 | 31 |
|
32 |
public JwtAuthenticationFilter(OAuthService oAuthService) { |
|
33 |
this.oAuthService = oAuthService; |
|
34 |
} |
|
35 |
|
|
36 |
// @Override |
|
37 |
// protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { |
|
38 |
// System.out.println("------------------DO FILTER INTERNAL---------------------------"); |
|
39 |
// |
|
40 |
// String authorizationHeader = request.getHeader("Authorization"); |
|
41 |
// if(authorizationHeader == null || authorizationHeader.length() < 7) { |
|
42 |
// filterChain.doFilter(request, response); |
|
43 |
// return; |
|
44 |
// } |
|
45 |
//// OAuthServiceImpl oAuthService = new OAuthServiceImpl(); |
|
46 |
// |
|
47 |
// String token = authorizationHeader.substring(7); |
|
48 |
// |
|
49 |
// ResponseEntity<String> oAuthResponse = oAuthService.authenticate(token); |
|
50 |
// response.setContentType("application/json"); |
|
51 |
// response.setStatus(oAuthResponse.getStatusCodeValue()); |
|
52 |
// |
|
53 |
// BufferedWriter out = new BufferedWriter(response.getWriter()); |
|
54 |
// out.write(Objects.requireNonNull(oAuthResponse.getBody())); |
|
55 |
// out.flush(); |
|
56 |
// out.close(); |
|
57 |
// |
|
58 |
// filterChain.doFilter(request, response); |
|
59 |
// |
|
60 |
// } |
|
61 |
|
|
62 |
// @Override |
|
63 |
// protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) |
|
64 |
// throws ServletException, IOException { |
|
65 |
// |
|
66 |
// String authorizationHeader = request.getHeader("Authorization"); |
|
67 |
// if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) { |
|
68 |
// String token = authorizationHeader.substring(7); |
|
69 |
// try { |
|
70 |
// Authentication authentication = new UsernamePasswordAuthenticationToken(oAuthService.authenticate(token).getBody(), null); |
|
71 |
// SecurityContextHolder.getContext().setAuthentication(authentication); |
|
72 |
// } catch (Exception e) { |
|
73 |
// SecurityContextHolder.clearContext(); |
|
74 |
// response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid JWT token"); |
|
75 |
// } |
|
76 |
// } |
|
77 |
//// String authorizationHeader = request.getHeader("Authorization"); |
|
78 |
//// |
|
79 |
//// if(authorizationHeader == null || authorizationHeader.length() < 7) { |
|
80 |
//// filterChain.doFilter(request, response); |
|
81 |
//// return; |
|
82 |
//// } |
|
83 |
//// |
|
84 |
//// RestTemplate restTemplate = new RestTemplate(); |
|
85 |
//// HttpHeaders headers = new HttpHeaders(); |
|
86 |
//// headers.setContentType(MediaType.APPLICATION_JSON); |
|
87 |
//// |
|
88 |
//// |
|
89 |
//// HashMap<String, String> requestBody = new HashMap<>(); |
|
90 |
//// |
|
91 |
//// requestBody.put("name", "userName"); |
|
92 |
//// |
|
93 |
//// // set the JWT token in the authorization header |
|
94 |
//// |
|
95 |
//// headers.set("Authorization", authorizationHeader); |
|
96 |
//// requestBody.put("token", authorizationHeader.substring(7)); |
|
97 |
//// // |
|
98 |
//// |
|
99 |
//// String json = JSONBuilder.buildJson(requestBody); |
|
100 |
//// |
|
101 |
//// HttpEntity<String> entity = new HttpEntity<>(json, headers); |
|
102 |
//// //RequestBuilder.sendRequestResponse("http://localhost:8081/authenticate",token); |
|
103 |
//// ResponseEntity<String> responseEntity = restTemplate.exchange("http://localhost:8081/authenticate", HttpMethod.POST, entity, String.class); |
|
104 |
//// |
|
105 |
//// // do something with the response body |
|
106 |
//// |
|
107 |
//// if (responseEntity.getBody().contains("Invalid token")) { |
|
108 |
//// response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid JWT token"); |
|
109 |
//// |
|
110 |
//// } else { |
|
111 |
//// return; |
|
112 |
////// Authentication authentication = new UsernamePasswordAuthenticationToken("name", null); |
|
113 |
////// SecurityContextHolder.getContext().setAuthentication(authentication); |
|
114 |
//// } |
|
115 |
//// |
|
116 |
////// filterChain.doFilter(request, response); |
|
117 |
// } |
|
27 | 118 |
|
28 | 119 |
@Override |
29 |
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
|
|
30 |
System.out.println("------------------DO FILTER INTERNAL---------------------------");
|
|
120 |
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
|
|
121 |
throws IOException, ServletException {
|
|
31 | 122 |
|
32 | 123 |
String authorizationHeader = request.getHeader("Authorization"); |
33 |
if(authorizationHeader == null || authorizationHeader.length() < 7) { |
|
34 |
filterChain.doFilter(request, response);
|
|
124 |
if (authorizationHeader == null || authorizationHeader.length() < 7) {
|
|
125 |
chain.doFilter(request, response);
|
|
35 | 126 |
return; |
36 | 127 |
} |
37 |
OAuthServiceImpl oAuthService = new OAuthServiceImpl(); |
|
38 |
|
|
39 | 128 |
String token = authorizationHeader.substring(7); |
40 | 129 |
|
41 |
ResponseEntity<String> oAuthResponse = oAuthService.authenticate(token); |
|
42 |
response.setContentType("application/json"); |
|
43 |
response.setStatus(oAuthResponse.getStatusCodeValue()); |
|
44 |
|
|
45 |
BufferedWriter out = new BufferedWriter(response.getWriter()); |
|
46 |
out.write(Objects.requireNonNull(oAuthResponse.getBody())); |
|
47 |
out.flush(); |
|
48 |
out.close(); |
|
49 |
|
|
50 |
filterChain.doFilter(request, response); |
|
51 |
|
|
130 |
ResponseEntity<String> responseEntity = oAuthService.authenticate(token); |
|
131 |
if (token != null && responseEntity.getBody().contains("OK")) { |
|
132 |
// Token is valid, proceed with the request |
|
133 |
chain.doFilter(request, response); |
|
134 |
} else { |
|
135 |
// Token is invalid or not present, authenticate the request with external authentication provider |
|
136 |
// HttpHeaders headers = new HttpHeaders(); |
|
137 |
// headers.setContentType(MediaType.APPLICATION_JSON); |
|
138 |
// String requestBody = "{\"token\": \"" + token + "\"}"; |
|
139 |
// HttpEntity<String> entity = new HttpEntity<>(requestBody, headers); |
|
140 |
// |
|
141 |
// ResponseEntity<AuthenticationResponse> authenticationResponseEntity = |
|
142 |
// restTemplate.postForEntity(AUTHENTICATION_URL, entity, AuthenticationResponse.class); |
|
143 |
// |
|
144 |
// if (authenticationResponseEntity.getStatusCode() == HttpStatus.OK |
|
145 |
// && authenticationResponseEntity.getBody().isAuthenticated()) { |
|
146 |
// // Request is authenticated, proceed with the request |
|
147 |
// chain.doFilter(request, response); |
|
148 |
// } else { |
|
149 |
// Request is not authenticated, set response status to 401 Unauthorized |
|
150 |
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); |
|
151 |
// } |
|
152 |
} |
|
52 | 153 |
} |
53 |
|
|
54 |
|
|
55 | 154 |
} |
src/main/java/cz/zcu/fav/kiv/antipatterndetectionapp/v2/security/OAuth2ResourceServerConfigurer.java | ||
---|---|---|
1 |
package cz.zcu.fav.kiv.antipatterndetectionapp.v2.security; |
|
2 |
|
|
3 |
import org.springframework.security.config.annotation.web.builders.HttpSecurity; |
|
4 |
|
|
5 |
public class OAuth2ResourceServerConfigurer { |
|
6 |
public static void jwt( |
|
7 |
org.springframework.security.config.annotation.web.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer<HttpSecurity> |
|
8 |
httpSecurityOAuth2ResourceServerConfigurer) { |
|
9 |
|
|
10 |
} |
|
11 |
} |
src/main/java/cz/zcu/fav/kiv/antipatterndetectionapp/v2/security/OAuthSecurityHandler.java | ||
---|---|---|
1 |
//package cz.zcu.fav.kiv.antipatterndetectionapp.v2.security; |
|
2 |
// |
|
3 |
// |
|
4 |
//import org.springframework.http.ResponseEntity; |
|
5 |
//import org.springframework.security.core.Authentication; |
|
6 |
//import org.springframework.security.oauth2.core.oidc.user.OidcUser; |
|
7 |
//import org.springframework.security.web.authentication.logout.LogoutHandler; |
|
8 |
//import org.springframework.stereotype.Component; |
|
9 |
//import org.springframework.web.client.RestTemplate; |
|
10 |
//import org.springframework.web.util.UriComponentsBuilder; |
|
11 |
// |
|
12 |
//import javax.servlet.http.HttpServletRequest; |
|
13 |
//import javax.servlet.http.HttpServletResponse; |
|
14 |
// |
|
15 |
//@Component |
|
16 |
//public class OAuthSecurityHandler implements LogoutHandler { |
|
17 |
//// private static final Logger logger = LoggerFactory.getLogger(OAuthSecurityHandler.class); |
|
18 |
// private final RestTemplate restTemplate; |
|
19 |
// |
|
20 |
// public OAuthSecurityHandler(RestTemplate restTemplate) { |
|
21 |
// this.restTemplate = restTemplate; |
|
22 |
// } |
|
23 |
// |
|
24 |
// @Override |
|
25 |
// public void logout(HttpServletRequest request, HttpServletResponse response, |
|
26 |
// Authentication auth) { |
|
27 |
// logoutFromKeycloak((OidcUser) auth.getPrincipal()); |
|
28 |
// } |
|
29 |
// |
|
30 |
// private void logoutFromKeycloak(OidcUser user) { |
|
31 |
// String endSessionEndpoint = user.getIssuer() + "/protocol/openid-connect/logout"; |
|
32 |
// UriComponentsBuilder builder = UriComponentsBuilder |
|
33 |
// .fromUriString(endSessionEndpoint) |
|
34 |
// .queryParam("id_token_hint", user.getIdToken().getTokenValue()); |
|
35 |
// |
|
36 |
// ResponseEntity<String> logoutResponse = restTemplate.getForEntity( |
|
37 |
// builder.toUriString(), String.class); |
|
38 |
//// if (logoutResponse.getStatusCode().is2xxSuccessful()) { |
|
39 |
//// logger.info("Successfulley logged out from Keycloak"); |
|
40 |
//// } else { |
|
41 |
//// logger.error("Could not propagate logout to Keycloak"); |
|
42 |
//// } |
|
43 |
// } |
|
44 |
//} |
src/main/java/cz/zcu/fav/kiv/antipatterndetectionapp/v2/security/WebSecurityConfig.java | ||
---|---|---|
5 | 5 |
import org.springframework.boot.web.client.RestTemplateBuilder; |
6 | 6 |
import org.springframework.context.annotation.Bean; |
7 | 7 |
import org.springframework.context.annotation.Configuration; |
8 |
import org.springframework.http.HttpStatus; |
|
8 | 9 |
import org.springframework.security.authentication.AuthenticationManager; |
9 | 10 |
import org.springframework.security.authentication.AuthenticationProvider; |
10 | 11 |
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; |
... | ... | |
13 | 14 |
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; |
14 | 15 |
import org.springframework.security.config.http.SessionCreationPolicy; |
15 | 16 |
import org.springframework.security.core.userdetails.UserDetailsService; |
17 |
import org.springframework.security.web.authentication.HttpStatusEntryPoint; |
|
16 | 18 |
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; |
17 | 19 |
import org.springframework.web.client.RestTemplate; |
18 | 20 |
|
19 | 21 |
@Configuration |
20 |
@EnableWebSecurity |
|
22 |
@EnableWebSecurity(debug = true)
|
|
21 | 23 |
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { |
22 | 24 |
|
23 | 25 |
@Autowired |
... | ... | |
55 | 57 |
@Override |
56 | 58 |
protected void configure(HttpSecurity httpSecurity) throws Exception { |
57 | 59 |
httpSecurity |
58 |
.csrf() |
|
59 |
.disable() |
|
60 |
.csrf().disable() |
|
60 | 61 |
.authorizeRequests() |
61 | 62 |
.antMatchers("/v2/user/register", "/v2/user/login").permitAll() |
62 |
.anyRequest() |
|
63 |
.authenticated() |
|
63 |
.anyRequest().authenticated() |
|
64 |
.and() |
|
65 |
.exceptionHandling() |
|
66 |
.authenticationEntryPoint(new OAuthServiceImpl()) |
|
64 | 67 |
.and() |
65 | 68 |
.sessionManagement() |
66 | 69 |
.sessionCreationPolicy(SessionCreationPolicy.STATELESS); |
67 |
httpSecurity.addFilterAfter(new JwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class); |
|
70 |
// .and() |
|
71 |
// .addFilterBefore(new JwtAuthenticationFilter(new OAuthServiceImpl()), UsernamePasswordAuthenticationFilter.class); |
|
72 |
// httpSecurity.addFilterAfter(new JwtAuthenticationFilter(new OAuthServiceImpl()), UsernamePasswordAuthenticationFilter.class); |
|
73 |
// httpSecurity.addFilter(new JwtAuthenticationFilter(new OAuthServiceImpl())); |
|
68 | 74 |
} |
69 | 75 |
|
70 | 76 |
} |
src/main/java/cz/zcu/fav/kiv/antipatterndetectionapp/v2/service/OAuthServiceImpl.java | ||
---|---|---|
32 | 32 |
/** |
33 | 33 |
* URL path to authenticate endpoint of OAuth application |
34 | 34 |
*/ |
35 |
@Value("${auth.realm.authenticate}") |
|
36 |
private String AUTH_URL_AUTH; |
|
35 |
// @Value("${auth.realm.authenticate}")
|
|
36 |
private String AUTH_URL_AUTH = "http://localhost:8081/authenticate";
|
|
37 | 37 |
|
38 | 38 |
/** |
39 | 39 |
* URL path to login endpoint of OAuth application |
40 | 40 |
*/ |
41 |
@Value("${auth.realm.login}") |
|
42 |
private String AUTH_URL_LOGIN; |
|
41 |
// @Value("${auth.realm.login}")
|
|
42 |
private String AUTH_URL_LOGIN = "http://localhost:8081/login";
|
|
43 | 43 |
|
44 | 44 |
/** |
45 | 45 |
* URL path to logout endpoint of OAuth application |
src/main/java/cz/zcu/fav/kiv/antipatterndetectionapp/v2/utils/RequestBuilder.java | ||
---|---|---|
33 | 33 |
HttpHeaders headers = new HttpHeaders(); |
34 | 34 |
|
35 | 35 |
headers.setContentType(MediaType.APPLICATION_JSON); |
36 |
headers.setBearerAuth(token);
|
|
36 |
headers.set("Authorization", "Bearer " + token);
|
|
37 | 37 |
|
38 | 38 |
HttpEntity<String> entity = new HttpEntity<>(json, headers); |
39 |
return restTemplate.postForEntity(url, entity, String.class); |
|
39 |
ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class); |
|
40 |
return response; |
|
40 | 41 |
} |
41 | 42 |
|
42 | 43 |
} |
Také k dispozici: Unified diff
#10228 - authentication entry point