0% found this document useful (0 votes)
3 views

Java

The document outlines a Java Spring Boot application implementing user registration and authentication services. It includes classes for user management, JWT token generation, and security configuration, along with REST controllers for handling user-related requests. Key components include UserService, AuthService, and JwtTokenService, which work together to manage user data and secure API access.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Java

The document outlines a Java Spring Boot application implementing user registration and authentication services. It includes classes for user management, JWT token generation, and security configuration, along with REST controllers for handling user-related requests. Key components include UserService, AuthService, and JwtTokenService, which work together to manage user data and secure API access.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 5

@Service

@RequiredArgsConstructor
public class UserService {

private final UserRepository userRepository;


private final PasswordEncoder passwordEncoder;

public User register(RegisterRequest request) {


User user = new User();
user.setUsername(request.getUsername());
user.setPassword(passwordEncoder.encode(request.getPassword()));
user.setFirstName(request.getFirstName());
user.setLastName(request.getLastName());
userRepository.save(user);
return user;
}
}

@Service
@RequiredArgsConstructor
public class JwtTokenService {

private final JwtEncoder encoder;


private final JwtDecoder decoder;

public String generateToken(Authentication authentication) {


Instant now = Instant.now();
String scope = "ROLE_ADMIN";
JwtClaimsSet claims = JwtClaimsSet.builder()
.issuer("self")
.issuedAt(now)
.expiresAt(now.plus(1, ChronoUnit.HOURS))
.subject(authentication.getName())
.claim("scope", scope)
.build();
var encoderParameters =
JwtEncoderParameters.from(JwsHeader.with(MacAlgorithm.HS256).build(), claims);
return this.encoder.encode(encoderParameters).getTokenValue();
}

public Long extractExpirationTime(String token) {


Jwt jwt = decoder.decode(token);
var exp = (Instant) jwt.getClaim("exp");
return exp.toEpochMilli();
}
}

@Service
@RequiredArgsConstructor
public class AuthUserDetailsService implements UserDetailsService {

private final UserRepository userRepository;

@Override
public UserDetails loadUserByUsername(String username) throws
UsernameNotFoundException {
return userRepository.findByUsername(username)
.map(AuthUser::new)
.orElseThrow(() -> new UsernameNotFoundException("User not found: "
+ username));
}
}

@Service
@RequiredArgsConstructor
public class AuthService {

private final AuthenticationManager authenticationManager;


private final JwtTokenService jwtTokenService;

public AuthResponse authenticate(AuthRequest authRequest) {


var token = new
UsernamePasswordAuthenticationToken(authRequest.getUsername(),
authRequest.getPassword());
Authentication authentication = authenticationManager.authenticate(token);

String jwtToken = jwtTokenService.generateToken(authentication);


Long expiresAt = jwtTokenService.extractExpirationTime(jwtToken);

return new AuthResponse(jwtToken, authentication.getName(), expiresAt);


}
}

public interface UserRepository extends JpaRepository<User, Long> {


Optional<User> findByUsername(String username);
}

@Entity
@Table(name = "users")
@Data
@NoArgsConstructor
public class User {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private String username;

private String password;

private String firstName;

private String lastName;


}

@RequiredArgsConstructor
public class AuthUser implements UserDetails {

private final User user;

@Override
public String getUsername() { return user.getUsername(); }
@Override
public String getPassword() { return user.getPassword(); }

@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
// Return a list of roles or authorities assigned to the user.
return List.of();
}

@Override
public boolean isAccountNonExpired() { return true; }

@Override
public boolean isAccountNonLocked() { return true; }

@Override
public boolean isCredentialsNonExpired() { return true; }

@Override
public boolean isEnabled() { return true; }

@Data
public class RegisterRequest {
private String username;
private String password;
private String firstName;
private String lastName;
}

@RestController
@RequestMapping("/user")
public class UserController {
private final UserService userService;

UserController(UserService userService) {
this.userService = userService;
}

@RequestMapping("/create")
public User createUser(@RequestBody RegisterRequest user) {
return userService.register(user);

@RestController
@RequestMapping("/user")
public class UserController {
private final UserService userService;

UserController(UserService userService) {
this.userService = userService;
}

@RequestMapping("/create")
public User createUser(@RequestBody RegisterRequest user) {
return userService.register(user);

@RestController
@RequiredArgsConstructor
@RequestMapping("/api/auth")
public class AuthController {

private final AuthService authService;

@PostMapping("/token")
public AuthResponse login(@RequestBody AuthRequest authRequest) {
return authService.authenticate(authRequest);
}
}

@Data
@NoArgsConstructor
@AllArgsConstructor
public class AuthResponse {
private String token;
private String username;
private Long expiresAt;
}

@Data
@NoArgsConstructor
@AllArgsConstructor
public class AuthRequest {
private String username;
private String password;
}

@Configuration
public class JwtConfig {

@Value("${jwt.key}")
private String jwtKey;

@Bean
public JwtEncoder jwtEncoder() {
return new NimbusJwtEncoder(new ImmutableSecret<>(jwtKey.getBytes()));
}

@Bean
public JwtDecoder jwtDecoder() {
byte[] bytes = jwtKey.getBytes();
SecretKeySpec originalKey = new SecretKeySpec(bytes, 0,
bytes.length,"RSA");
return NimbusJwtDecoder.withSecretKey(originalKey)
.macAlgorithm(MacAlgorithm.HS256)
.build();
}
}
@Configuration
@EnableWebSecurity
public class SecurityConfig {

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws
Exception {
return http
.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(auth -> {

auth.requestMatchers("/api/auth/token","/user/create").permitAll();
auth.anyRequest().authenticated();
})
.sessionManagement(session ->
session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.oauth2ResourceServer(oauth2 -> {
oauth2.jwt(withDefaults());
})
.build();
}

@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(10);
}

@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration
config) throws Exception {
return config.getAuthenticationManager();
}

}s

You might also like