Skip to content

Commit

Permalink
Starting JWT
Browse files Browse the repository at this point in the history
  • Loading branch information
ailtonbsj committed Sep 9, 2022
1 parent d401fe4 commit e8ac1d0
Show file tree
Hide file tree
Showing 6 changed files with 171 additions and 22 deletions.
7 changes: 7 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,13 @@
<java.version>17</java.version>
</properties>
<dependencies>

<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>4.0.0</version>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
import javax.persistence.Id;
import javax.persistence.PrePersist;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
Expand Down
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("*");
// }
// };
// }

}
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();
}

}
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<>());
}
}

0 comments on commit e8ac1d0

Please sign in to comment.