-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
6 changed files
with
171 additions
and
22 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
67 changes: 47 additions & 20 deletions
67
src/main/java/ailtonbsj/sauteweb/sauteapi/security/SecurityConfig.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,49 +1,76 @@ | ||
package ailtonbsj.sauteweb.sauteapi.security; | ||
|
||
import org.springframework.beans.factory.annotation.Autowired; | ||
import org.springframework.context.annotation.Bean; | ||
import org.springframework.http.HttpMethod; | ||
import org.springframework.security.authentication.AuthenticationManager; | ||
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration; | ||
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; | ||
import org.springframework.security.config.annotation.web.builders.HttpSecurity; | ||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; | ||
import org.springframework.security.config.http.SessionCreationPolicy; | ||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; | ||
import org.springframework.security.crypto.password.PasswordEncoder; | ||
import org.springframework.security.web.SecurityFilterChain; | ||
import org.springframework.web.cors.CorsConfiguration; | ||
import org.springframework.web.cors.CorsConfigurationSource; | ||
import org.springframework.web.cors.UrlBasedCorsConfigurationSource; | ||
import org.springframework.web.servlet.config.annotation.CorsRegistry; | ||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; | ||
|
||
import ailtonbsj.sauteweb.sauteapi.security.jwt.JWTAuthenticationFilter; | ||
|
||
@EnableWebSecurity | ||
@EnableMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true) | ||
public class SecurityConfig { | ||
|
||
@Bean | ||
public PasswordEncoder passwordEncoder() { | ||
return new BCryptPasswordEncoder(); | ||
} | ||
@Autowired | ||
CustomUserDetailsService userService; | ||
|
||
@Bean | ||
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) | ||
throws Exception { | ||
return authenticationConfiguration.getAuthenticationManager(); | ||
} | ||
@Autowired | ||
PasswordEncoder passwordEncoder; | ||
|
||
// @Bean | ||
// public PasswordEncoder passwordEncoder() { | ||
// return new BCryptPasswordEncoder(); | ||
// } | ||
|
||
// @Bean | ||
// public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) | ||
// throws Exception { | ||
// return authenticationConfiguration.getAuthenticationManager(); | ||
// } | ||
|
||
@Bean | ||
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { | ||
http.cors().and().csrf().disable().authorizeRequests() | ||
.antMatchers("/users/create", "/users/create/**") | ||
.permitAll().and().httpBasic(); | ||
http.cors().and().csrf().disable() | ||
.authorizeRequests() | ||
.antMatchers(HttpMethod.POST, "/users/create", "/users/create/**") | ||
.permitAll() | ||
.anyRequest().authenticated().and() | ||
.addFilter(new JWTAuthenticationFilter(authenticationManager())) | ||
.addFilter(new JWTAuthenticationFilter(authenticationManager())) | ||
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); | ||
return http.build(); | ||
} | ||
|
||
@Bean | ||
public WebMvcConfigurer corsConfigurer() { | ||
return new WebMvcConfigurer() { | ||
@Override | ||
public void addCorsMappings(CorsRegistry registry) { | ||
registry.addMapping("/**") | ||
.allowedMethods("*"); | ||
} | ||
}; | ||
CorsConfigurationSource corsConfigurationSource() { | ||
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); | ||
CorsConfiguration corsConfiguration = new CorsConfiguration().applyPermitDefaultValues(); | ||
source.registerCorsConfiguration("/**", corsConfiguration); | ||
return source; | ||
} | ||
|
||
// @Bean | ||
// public WebMvcConfigurer corsConfigurer() { | ||
// return new WebMvcConfigurer() { | ||
// @Override | ||
// public void addCorsMappings(CorsRegistry registry) { | ||
// registry.addMapping("/**") | ||
// .allowedMethods("*"); | ||
// } | ||
// }; | ||
// } | ||
|
||
} |
65 changes: 65 additions & 0 deletions
65
src/main/java/ailtonbsj/sauteweb/sauteapi/security/jwt/JWTAuthenticationFilter.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
package ailtonbsj.sauteweb.sauteapi.security.jwt; | ||
|
||
import java.io.IOException; | ||
import java.util.Date; | ||
|
||
import javax.servlet.FilterChain; | ||
import javax.servlet.ServletException; | ||
import javax.servlet.http.HttpServletRequest; | ||
import javax.servlet.http.HttpServletResponse; | ||
|
||
import org.springframework.beans.factory.annotation.Autowired; | ||
import org.springframework.security.authentication.AuthenticationManager; | ||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; | ||
import org.springframework.security.core.Authentication; | ||
import org.springframework.security.core.AuthenticationException; | ||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; | ||
|
||
import com.auth0.jwt.JWT; | ||
import com.auth0.jwt.algorithms.Algorithm; | ||
import com.fasterxml.jackson.databind.ObjectMapper; | ||
|
||
import ailtonbsj.sauteweb.sauteapi.entities.User; | ||
import ailtonbsj.sauteweb.sauteapi.security.UserPrincipal; | ||
|
||
public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter { | ||
|
||
public static final int TOKEN_EXPIRATION = 86_400_000; | ||
public static final String SECRET = "THIS_IS_YOUR_SECRET"; | ||
|
||
@Autowired | ||
AuthenticationManager authenticationManager; | ||
|
||
@Override | ||
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) | ||
throws AuthenticationException { | ||
|
||
try { | ||
// Maping Object to User Entity | ||
User user = new ObjectMapper().readValue( | ||
request.getInputStream(), User.class); | ||
UserPrincipal userPrincipal = new UserPrincipal(user); | ||
return authenticationManager.authenticate( | ||
new UsernamePasswordAuthenticationToken( | ||
userPrincipal.getUsername(), | ||
userPrincipal.getPassword(), | ||
userPrincipal.getAuthorities())); | ||
} catch (IOException e) { | ||
throw new RuntimeException("Falha ao autenticar ", e); | ||
} | ||
} | ||
|
||
@Override | ||
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, | ||
Authentication authResult) throws IOException, ServletException { | ||
|
||
UserPrincipal userPrincipal = (UserPrincipal) authResult.getPrincipal(); | ||
|
||
String token = JWT.create().withSubject(userPrincipal.getUsername()).withExpiresAt( | ||
new Date(System.currentTimeMillis() + TOKEN_EXPIRATION)).sign(Algorithm.HMAC512(SECRET)); | ||
|
||
response.getWriter().write(token); | ||
response.getWriter().flush(); | ||
} | ||
|
||
} |
52 changes: 52 additions & 0 deletions
52
src/main/java/ailtonbsj/sauteweb/sauteapi/security/jwt/JWTValidateFilter.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
package ailtonbsj.sauteweb.sauteapi.security.jwt; | ||
|
||
import java.io.IOException; | ||
import java.util.ArrayList; | ||
|
||
import javax.servlet.FilterChain; | ||
import javax.servlet.ServletException; | ||
import javax.servlet.http.HttpServletRequest; | ||
import javax.servlet.http.HttpServletResponse; | ||
|
||
import org.springframework.security.authentication.AuthenticationManager; | ||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; | ||
import org.springframework.security.core.authority.SimpleGrantedAuthority; | ||
import org.springframework.security.core.context.SecurityContextHolder; | ||
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; | ||
|
||
import com.auth0.jwt.JWT; | ||
import com.auth0.jwt.algorithms.Algorithm; | ||
import com.auth0.jwt.interfaces.DecodedJWT; | ||
|
||
public class JWTValidateFilter extends BasicAuthenticationFilter { | ||
|
||
public static final String HEADER_ATTR = "Authorization"; | ||
public static final String PREFIX_ATTR = "Bearer "; | ||
|
||
public JWTValidateFilter(AuthenticationManager authenticationManager) { | ||
super(authenticationManager); | ||
} | ||
|
||
@Override | ||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) | ||
throws IOException, ServletException { | ||
String attr = request.getHeader(HEADER_ATTR); | ||
if (attr == null || !attr.startsWith(PREFIX_ATTR)) { | ||
chain.doFilter(request, response); | ||
return; | ||
} | ||
|
||
String token = attr.replace(PREFIX_ATTR, ""); | ||
UsernamePasswordAuthenticationToken authenticationToken = getAuthenticationToken(token); | ||
SecurityContextHolder.getContext().setAuthentication(authenticationToken); | ||
chain.doFilter(request, response); | ||
} | ||
|
||
private UsernamePasswordAuthenticationToken getAuthenticationToken(String token) { | ||
DecodedJWT jwtDec = JWT.require(Algorithm.HMAC512(JWTAuthenticationFilter.SECRET)).build().verify(token); | ||
String user = jwtDec.getSubject(); | ||
// String authorities = jwtDec.getClaims(); | ||
if(user == null) return null; | ||
return new UsernamePasswordAuthenticationToken(user, null, new ArrayList<>()); | ||
} | ||
} |