Added Signup and JWT Login
This commit is contained in:
@@ -3,6 +3,8 @@ package com.skycrate.backend.skycrateBackend;
|
||||
import com.skycrate.backend.skycrateBackend.controller.HDFScontroller;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
|
||||
|
||||
|
||||
@SpringBootApplication
|
||||
public class SkycrateBackendApplication {
|
||||
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package com.skycrate.backend.skycrateBackend.config;
|
||||
|
||||
import java.security.AuthProvider;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.authentication.AuthenticationProvider;
|
||||
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
|
||||
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.security.crypto.bcrypt.BCrypt;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
|
||||
import com.skycrate.backend.skycrateBackend.repository.UserRepository;
|
||||
|
||||
@Configuration
|
||||
public class ApplicationConfiguration {
|
||||
private final UserRepository userRepository;
|
||||
public ApplicationConfiguration(UserRepository userRepository){
|
||||
this.userRepository=userRepository;
|
||||
|
||||
}
|
||||
@Bean
|
||||
UserDetailsService userDetailsService() {
|
||||
return username -> userRepository.findByEmail(username)
|
||||
.orElseThrow(() -> new UsernameNotFoundException("User not found"));
|
||||
}
|
||||
@Bean
|
||||
BCryptPasswordEncoder passwordEncoder(){
|
||||
return new BCryptPasswordEncoder();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception{
|
||||
return config.getAuthenticationManager();
|
||||
}
|
||||
|
||||
@Bean
|
||||
AuthenticationProvider authenticationProvider(){
|
||||
DaoAuthenticationProvider authprovider=new DaoAuthenticationProvider();
|
||||
authprovider.setUserDetailsService(userDetailsService());
|
||||
authprovider.setPasswordEncoder(passwordEncoder());
|
||||
return authprovider;
|
||||
}
|
||||
}
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
package com.skycrate.backend.skycrateBackend.config;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.springframework.lang.NonNull;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
import org.springframework.web.servlet.HandlerExceptionResolver;
|
||||
|
||||
import com.skycrate.backend.skycrateBackend.services.JwtService;
|
||||
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
|
||||
@Component
|
||||
public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
||||
|
||||
|
||||
private final HandlerExceptionResolver handlerExceptionResolver;
|
||||
private JwtService jwtService;
|
||||
private UserDetailsService userDetailsService;
|
||||
|
||||
public JwtAuthenticationFilter(JwtService jwtService,UserDetailsService userDetailsService,HandlerExceptionResolver handlerExceptionResolver){
|
||||
|
||||
this.handlerExceptionResolver=handlerExceptionResolver;
|
||||
this.jwtService=jwtService;
|
||||
this.userDetailsService=userDetailsService;
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
protected void doFilterInternal(
|
||||
@NonNull HttpServletRequest request,
|
||||
@NonNull HttpServletResponse response,
|
||||
@NonNull FilterChain filterChain) throws ServletException, IOException {
|
||||
final String authHeader=request.getHeader("Authorization");
|
||||
if (authHeader==null || !authHeader.startsWith("Bearer")){
|
||||
filterChain.doFilter(request, response);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
final String userjwt=authHeader.substring(7);
|
||||
final String userEmail=jwtService.extractUsername(userjwt);
|
||||
Authentication authentication=SecurityContextHolder.getContext().getAuthentication();
|
||||
if(userEmail!=null && authentication==null){
|
||||
|
||||
UserDetails userDetails=this.userDetailsService.loadUserByUsername(userEmail);
|
||||
if (jwtService.isTokenValid(userjwt, userDetails)) {
|
||||
|
||||
UsernamePasswordAuthenticationToken authenticationToken=new UsernamePasswordAuthenticationToken(
|
||||
userDetails, null, userDetails.getAuthorities()
|
||||
);
|
||||
authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
|
||||
SecurityContextHolder.getContext().setAuthentication(authenticationToken);
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
filterChain.doFilter(request, response);
|
||||
}
|
||||
catch (Exception err) {
|
||||
handlerExceptionResolver.resolveException(request, response, null, err);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -1,23 +1,23 @@
|
||||
package com.skycrate.backend.skycrateBackend.config;
|
||||
// package com.skycrate.backend.skycrateBackend.config;
|
||||
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
// import org.springframework.context.annotation.Bean;
|
||||
// import org.springframework.context.annotation.Configuration;
|
||||
// import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
// import org.springframework.security.web.SecurityFilterChain;
|
||||
|
||||
@Configuration
|
||||
public class SecurityConfig {
|
||||
// @Configuration
|
||||
// public class SecurityConfig {
|
||||
|
||||
@Bean
|
||||
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||
http
|
||||
.csrf(csrf -> csrf.disable()) // Disable CSRF for testing APIs
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
.requestMatchers("/api/hdfs/**").permitAll() // Allow HDFS endpoints
|
||||
.anyRequest().authenticated() // Everything else needs auth
|
||||
);
|
||||
// @Bean
|
||||
// public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||
// http
|
||||
// .csrf(csrf -> csrf.disable()) // Disable CSRF for testing APIs
|
||||
// .authorizeHttpRequests(auth -> auth
|
||||
// .requestMatchers("/api/hdfs/**").permitAll() // Allow HDFS endpoints
|
||||
// .anyRequest().authenticated() // Everything else needs auth
|
||||
// );
|
||||
|
||||
return http.build();
|
||||
}
|
||||
}
|
||||
// return http.build();
|
||||
// }
|
||||
// }
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
package com.skycrate.backend.skycrateBackend.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.authentication.AuthenticationProvider;
|
||||
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.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||
import org.springframework.web.cors.CorsConfiguration;
|
||||
import org.springframework.web.cors.CorsConfigurationSource;
|
||||
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
public class SecurityConfiguration {
|
||||
private final AuthenticationProvider authenticationProvider;
|
||||
private final JwtAuthenticationFilter jwtAuthenticationFilter;
|
||||
|
||||
public SecurityConfiguration(
|
||||
JwtAuthenticationFilter jwtAuthenticationFilter,
|
||||
AuthenticationProvider authenticationProvider
|
||||
) {
|
||||
this.authenticationProvider = authenticationProvider;
|
||||
this.jwtAuthenticationFilter = jwtAuthenticationFilter;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
|
||||
http.csrf()
|
||||
.disable()
|
||||
.authorizeHttpRequests()
|
||||
.requestMatchers("/api/hdfs/**") // Specific API endpoints that don't require authentication
|
||||
.permitAll()
|
||||
.requestMatchers("/api/**") // Other endpoints that should be open
|
||||
.permitAll()
|
||||
.anyRequest()
|
||||
.authenticated() // All other requests require authentication
|
||||
.and()
|
||||
.sessionManagement()
|
||||
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
|
||||
.and()
|
||||
.authenticationProvider(authenticationProvider)
|
||||
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
|
||||
return http.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
CorsConfigurationSource corsConfigurationSource() {
|
||||
CorsConfiguration configuration = new CorsConfiguration();
|
||||
|
||||
configuration.setAllowedOrigins(List.of("*"));
|
||||
configuration.setAllowedMethods(List.of("GET", "PUT", "DELETE", "POST"));
|
||||
configuration.setAllowedHeaders(List.of("Authorization", "Content-Type"));
|
||||
|
||||
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
|
||||
|
||||
source.registerCorsConfiguration("/**", configuration);
|
||||
|
||||
return source;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.skycrate.backend.skycrateBackend.controller;
|
||||
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.skycrate.backend.skycrateBackend.dto.LoginUserDto;
|
||||
import com.skycrate.backend.skycrateBackend.dto.RegisterUserDto;
|
||||
import com.skycrate.backend.skycrateBackend.models.User;
|
||||
import com.skycrate.backend.skycrateBackend.responses.LoginResponse;
|
||||
import com.skycrate.backend.skycrateBackend.services.AuthenticationService;
|
||||
import com.skycrate.backend.skycrateBackend.services.JwtService;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
|
||||
|
||||
@RequestMapping("/api")
|
||||
@RestController
|
||||
public class AuthController {
|
||||
|
||||
private final JwtService jwtService;
|
||||
private AuthenticationService authenticationService;
|
||||
|
||||
public AuthController(JwtService jwtService,AuthenticationService authenticationService){
|
||||
this.jwtService=jwtService;
|
||||
this.authenticationService=authenticationService;
|
||||
}
|
||||
|
||||
@GetMapping("/test")
|
||||
public String teString(@RequestParam String param) {
|
||||
return new String();
|
||||
}
|
||||
|
||||
@PostMapping("/login")
|
||||
public ResponseEntity<LoginResponse> LoginController(@RequestBody LoginUserDto entity) {
|
||||
|
||||
User authenticatedUser=authenticationService.authenticate(entity);
|
||||
String jwtToken=jwtService.generateToken(authenticatedUser);
|
||||
|
||||
LoginResponse loginResponse=new LoginResponse().setToken(jwtToken).setExpiresIn(jwtService.getExpirtationTime());
|
||||
return ResponseEntity.ok(loginResponse);
|
||||
}
|
||||
|
||||
@PostMapping("/signup")
|
||||
public ResponseEntity<User> register(@RequestBody RegisterUserDto entity) {
|
||||
User registeredUser=authenticationService.signUp(entity);
|
||||
|
||||
|
||||
return ResponseEntity.ok(registeredUser);
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.skycrate.backend.skycrateBackend.dto;
|
||||
|
||||
|
||||
public class LoginUserDto {
|
||||
private String email;
|
||||
private String password;
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.skycrate.backend.skycrateBackend.dto;
|
||||
|
||||
public class RegisterUserDto {
|
||||
|
||||
private String email;
|
||||
private String password;
|
||||
private String firstname;
|
||||
private String lastname;
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public RegisterUserDto setEmail(String email) {
|
||||
this.email = email;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public RegisterUserDto setPassword(String password) {
|
||||
this.password = password;
|
||||
return this;
|
||||
|
||||
}
|
||||
|
||||
public String getFirstname() {
|
||||
return firstname;
|
||||
}
|
||||
|
||||
public RegisterUserDto setFirstname(String firstname) {
|
||||
this.firstname = firstname;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getLastname() {
|
||||
return lastname;
|
||||
}
|
||||
|
||||
public RegisterUserDto setLastname(String lastname) {
|
||||
this.lastname = lastname;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package com.skycrate.backend.skycrateBackend.models;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Collection;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
import org.hibernate.annotations.CreationTimestamp;
|
||||
import org.hibernate.annotations.UpdateTimestamp;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
|
||||
@Table(name = "users")
|
||||
@Entity
|
||||
public class User implements UserDetails {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
@Column(nullable = false)
|
||||
private Integer id;
|
||||
|
||||
@Column(nullable = false)
|
||||
private String username;
|
||||
|
||||
/*
|
||||
|
||||
//Optional feature might add later
|
||||
|
||||
@Column(name = "verification_code")
|
||||
private String verificationCode;
|
||||
|
||||
@Column(name ="verification_expiry")
|
||||
private LocalDateTime verificationExpiry;
|
||||
|
||||
*/
|
||||
|
||||
@Column(unique = true, nullable = false)
|
||||
private String email;
|
||||
|
||||
@Column(nullable = false)
|
||||
private String password;
|
||||
|
||||
|
||||
|
||||
public User(){
|
||||
}
|
||||
|
||||
public User(String firstname,String lastname,String email,String password){
|
||||
this.username=firstname+lastname;
|
||||
this.email=email;
|
||||
this.password=password;
|
||||
}
|
||||
|
||||
|
||||
@CreationTimestamp
|
||||
@Column(updatable = false, name = "created_at")
|
||||
private Date createdAt;
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public Collection<? extends GrantedAuthority> getAuthorities(){
|
||||
return List.of();
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getUsername() {
|
||||
return email;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAccountNonExpired() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAccountNonLocked() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isCredentialsNonExpired() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEnabled() {
|
||||
return true;
|
||||
}
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Integer id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
|
||||
|
||||
public void setFullname(String firstname,String lastname) {
|
||||
this.username=firstname+lastname;
|
||||
}
|
||||
|
||||
public String getFullname(String firstname,String lastname){
|
||||
return this.username;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public Date getCreatedAt() {
|
||||
return createdAt;
|
||||
}
|
||||
|
||||
public void setCreatedAt(Date createdAt) {
|
||||
this.createdAt = createdAt;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.skycrate.backend.skycrateBackend.repository;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
import com.skycrate.backend.skycrateBackend.models.User;
|
||||
public interface UserRepository extends CrudRepository<User,Integer> {
|
||||
Optional<User> findByEmail(String email);
|
||||
/*
|
||||
// might use later
|
||||
Optional<User> findByVerificationCode(String verificationCode);
|
||||
*/
|
||||
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.skycrate.backend.skycrateBackend.responses;
|
||||
|
||||
|
||||
public class LoginResponse {
|
||||
private String token;
|
||||
private long expiresIn;
|
||||
|
||||
public String getToken() {
|
||||
return token;
|
||||
}
|
||||
|
||||
public LoginResponse setToken(String token) {
|
||||
this.token = token;
|
||||
return this;
|
||||
}
|
||||
|
||||
public long getExpiresIn() {
|
||||
return expiresIn;
|
||||
}
|
||||
|
||||
public LoginResponse setExpiresIn(long expiresIn) {
|
||||
this.expiresIn = expiresIn;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
package com.skycrate.backend.skycrateBackend.services;
|
||||
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.skycrate.backend.skycrateBackend.dto.LoginUserDto;
|
||||
import com.skycrate.backend.skycrateBackend.dto.RegisterUserDto;
|
||||
import com.skycrate.backend.skycrateBackend.models.User;
|
||||
import com.skycrate.backend.skycrateBackend.repository.UserRepository;
|
||||
|
||||
@Service
|
||||
public class AuthenticationService {
|
||||
|
||||
private final UserRepository userRepository;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
private final AuthenticationManager authenticationManager;
|
||||
|
||||
public AuthenticationService( UserRepository userRepository, AuthenticationManager authenticationManager , PasswordEncoder passwordEncoder){
|
||||
this.userRepository=userRepository;
|
||||
this.passwordEncoder=passwordEncoder;
|
||||
this.authenticationManager=authenticationManager;
|
||||
}
|
||||
|
||||
public User signUp(RegisterUserDto inputuser){
|
||||
User user=new User(inputuser.getFirstname(),inputuser.getLastname(),inputuser.getEmail(),passwordEncoder.encode(inputuser.getPassword()));
|
||||
/*
|
||||
User user = new User()
|
||||
.setFullname(inputuser.getFirstname(),inputuser.getLastname())
|
||||
.setEmail(inputuser.getEmail())
|
||||
.setPassword(passwordEncoder.encode(inputuser.getPassword()));
|
||||
*/
|
||||
|
||||
return userRepository.save(user) ;
|
||||
}
|
||||
|
||||
public User authenticate(LoginUserDto inputuser){
|
||||
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(inputuser.getEmail()
|
||||
, inputuser.getPassword()));
|
||||
return userRepository.findByEmail(inputuser.getEmail()).orElseThrow();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package com.skycrate.backend.skycrateBackend.services;
|
||||
|
||||
import java.security.Key;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import io.jsonwebtoken.Claims;
|
||||
import io.jsonwebtoken.Jwts;
|
||||
import io.jsonwebtoken.SignatureAlgorithm;
|
||||
import io.jsonwebtoken.io.Decoders;
|
||||
import io.jsonwebtoken.security.Keys;
|
||||
|
||||
@Service
|
||||
public class JwtService {
|
||||
@Value("${security.jwt.secret-key}")
|
||||
private String secretKey;
|
||||
|
||||
@Value("${security.jwt.expiration-time}")
|
||||
private long jwtExpiration;
|
||||
|
||||
public String extractUsername(String token){
|
||||
return extractClaim(token,Claims::getSubject);
|
||||
}
|
||||
|
||||
public <T> T extractClaim(String token,Function<Claims,T> claimsResolver){
|
||||
final Claims claims=extractAllClaims(token);
|
||||
return claimsResolver.apply(claims);
|
||||
|
||||
}
|
||||
|
||||
public String generateToken(UserDetails userDetails) {
|
||||
return generateToken(new HashMap<>(), userDetails);
|
||||
}
|
||||
|
||||
public String generateToken(Map<String, Object> extraClaims, UserDetails userDetails) {
|
||||
return buildToken(extraClaims, userDetails, jwtExpiration);
|
||||
}
|
||||
|
||||
public long getExpirtationTime(){
|
||||
return jwtExpiration;
|
||||
}
|
||||
private String buildToken(Map<String,Object> extraClaims,UserDetails userDetails,long expiration){
|
||||
|
||||
return Jwts.builder().setClaims(extraClaims).setSubject(userDetails.getUsername())
|
||||
.setIssuedAt(new Date(System.currentTimeMillis()))
|
||||
.setExpiration(new Date(System.currentTimeMillis() + expiration))
|
||||
.signWith(getSignInKey(), SignatureAlgorithm.HS256)
|
||||
.compact();
|
||||
}
|
||||
|
||||
public boolean isTokenValid(String token, UserDetails userDetails) {
|
||||
final String username = extractUsername(token);
|
||||
return (username.equals(userDetails.getUsername())) && !isTokenExpired(token);
|
||||
}
|
||||
|
||||
private boolean isTokenExpired(String token) {
|
||||
return extractExpiration(token).before(new Date());
|
||||
}
|
||||
|
||||
private Date extractExpiration(String token) {
|
||||
return extractClaim(token, Claims::getExpiration);
|
||||
}
|
||||
|
||||
private Claims extractAllClaims(String token) {
|
||||
return Jwts
|
||||
.parserBuilder()
|
||||
.setSigningKey(getSignInKey())
|
||||
.build()
|
||||
.parseClaimsJws(token)
|
||||
.getBody();
|
||||
}
|
||||
|
||||
private Key getSignInKey() {
|
||||
byte[] keyBytes = Decoders.BASE64.decode(secretKey);
|
||||
return Keys.hmacShaKeyFor(keyBytes);
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,8 @@ spring.application.name=skycrateBackend
|
||||
spring.servlet.multipart.max-file-size=1000MB
|
||||
spring.servlet.multipart.max-request-size=1000MB
|
||||
|
||||
security.jwt.secret-key=3cfa76ef14937c1c0ea519f8fc057a80fcd04a7420f8e8bcd0a7567c272e007b
|
||||
security.jwt.expiration-time=3600000
|
||||
|
||||
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect
|
||||
spring.datasource.username=kshitij
|
||||
@@ -12,3 +14,29 @@ spring.datasource.url=jdbc:mysql://192.168.29.55:3306/skycrate
|
||||
spring.jpa.hibernate.ddl-auto=update
|
||||
spring.jpa.show-sql=true
|
||||
spring.jpa.properties.hibernate.format_sql=true
|
||||
spring.jpa.open-in-view=false
|
||||
logging.level.org.springframework.security.config.annotation.authentication.configuration.InitializeUserDetailsBeanManagerConfigurer=ERROR
|
||||
|
||||
server.port=8081
|
||||
|
||||
|
||||
|
||||
|
||||
# spring.application.name=skycrateBackend
|
||||
|
||||
# spring.servlet.multipart.max-file-size=1000MB
|
||||
# spring.servlet.multipart.max-request-size=1000MB
|
||||
|
||||
# security.jwt.secret-key=3cfa76ef14937c1c0ea519f8fc057a80fcd04a7420f8e8bcd0a7567c272e007b
|
||||
# security.jwt.expiration-time=3600000
|
||||
|
||||
# spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect
|
||||
# spring.datasource.username=root
|
||||
# spring.datasource.password=sqlsys
|
||||
# spring.datasource.url=jdbc:mysql://localhost:3306/skycrate
|
||||
|
||||
# spring.jpa.hibernate.ddl-auto=update
|
||||
# spring.jpa.show-sql=true
|
||||
# spring.jpa.properties.hibernate.format_sql=true
|
||||
|
||||
# server.port=8081
|
||||
|
||||
Reference in New Issue
Block a user