Spring Role Based Security
Spring Role Based Security
xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.1</version>
</parent>
<groupId>com.examly</groupId>
<artifactId>springapp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springapp</name>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- <dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency> -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.11.5</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.11.5</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.11.5</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<image>
<builder>paketobuildpacks/builder-jammy-
base:latest</builder>
</image>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
</configuration>
</plugin>
</plugins>
</build>
</project>
application.properties
spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=jdbc:mysql://localhost/appdb?createDatabaseIfNotExist=true
spring.datasource.username=root
spring.datasource.password=examly
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.show-sql= true
spring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect
enable.swagger.plugin=true
spring.mvc.pathmatch.matching-strategy=ant-path-matcher
Model Classes
User.java
package com.examly.springapp.model;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(unique = true)
public User() {
this.id = id;
this.username = username;
this.password = password;
this.role = role;
return id;
this.id = id;
return username;
}
public void setUsername(String username) {
this.username = username;
return password;
this.password = password;
return role;
this.role = role;
@Override
return "User [id=" + id + ", username=" + username + ", password=" + password + ", role=" + role
+ "]";
@Override
int result = 1;
@Override
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
if (id != other.id)
return false;
return true;
Gift.java
package com.examly.springapp.model;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Gift() {
this.giftId = giftId;
this.name = name;
this.description = description;
this.price = price;
return giftId;
this.giftId = giftId;
return name;
return description;
this.description = description;
return price;
this.price = price;
@Override
return "Gift [giftId=" + giftId + ", name=" + name + ", description=" + description + ", price=" +
price + "]";
@Override
int result = 1;
return result;
}
@Override
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
if (giftId != other.giftId)
return false;
return true;
Repositories
UserRepo.java
package com.examly.springapp.repository;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.examly.springapp.model.User;
@Repository
GiftRepo.java
package com.examly.springapp.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.examly.springapp.model.Gift;
@Repository
Exception
UserExistException.java
package com.examly.springapp.exceptions;
}
GlobalExceptionAdvice.java
package com.examly.springapp.exceptions;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
@ExceptionHandler
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(false);
@ExceptionHandler(AuthenticationException.class )
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(errmsg);
Services
UserService.java
package com.examly.springapp.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import com.examly.springapp.exceptions.UserExistException;
import com.examly.springapp.model.User;
import com.examly.springapp.repository.UserRepo;
@Service
@Autowired
@Autowired
if(existUser != null){
user.setPassword(passwordEncoder.encode(user.getPassword()));
user = userRepo.save(user);
return true;
}
GiftService.java
package com.examly.springapp.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.examly.springapp.model.Gift;
import com.examly.springapp.repository.GiftRepo;
import java.util.List;
@Service
@Autowired
return giftRepo.save(gift);
gift.setGiftId(giftId);
return giftRepo.save(gift);
if(giftRepo.existsById(giftId)){
giftRepo.deleteById(giftId);
return true;
}else
return false;
}
return giftRepo.findAll();
return giftRepo.findById(giftId).orElse(null);
Configuration
JwtUtils.java
package com.examly.springapp.configuration;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
@Component
return claimsResolver.apply(claims);
return Jwts
.parserBuilder()
.setSigningKey(getSignKey())
.build()
.parseClaimsJws(token)
.getBody();
}
public Boolean validateToken(String token, UserDetails userDetails) {
return Jwts.builder()
.setClaims(claims)
.setSubject(username)
.setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(new Date(System.currentTimeMillis()+1000*60*60))
.signWith(getSignKey(), SignatureAlgorithm.HS256).compact();
return Keys.hmacShaKeyFor(keyBytes);
}
2
JwtAutheticationEntryPoint.java
package com.examly.springapp.configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.security.core.AuthenticationException;
import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@Component
@Autowired
@Qualifier("handlerExceptionResolver")
@Override
}
3
JwtAuthenticationFilter.java
package com.examly.springapp.configuration;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
@Component
@Autowired
@Autowired
UserDetailsServiceImpl userDetailsServiceImpl;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
token = authHeader.substring(7);
logger.info("Token : "+token);
username = jwtService.extractUsername(token);
if(jwtService.validateToken(token, userDetails)){
authenticationToken.setDetails(new
WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authenticationToken);
}else{
filterChain.doFilter(request, response);
}
}
CustomUserDetails.java
package com.examly.springapp.configuration;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import com.examly.springapp.model.User;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
this.username = byUsername.getUsername();
this.password= byUsername.getPassword();
auths.add(new SimpleGrantedAuthority(byUsername.getRole()));
this.authorities = auths;
}
@Override
return authorities;
@Override
return password;
@Override
return username;
@Override
return true;
@Override
return true;
@Override
return true;
@Override
UserDetailsServiceImpl.java
package com.examly.springapp.configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import com.examly.springapp.repository.UserRepo;
import com.examly.springapp.model.User;
@Component
@Autowired
@Override
if(user == null){
logger.info(user+"");
SecurityConfig.java
package com.examly.springapp.configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
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.AuthenticationConfigur
ation;
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.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
@Autowired
UserDetailsService userDetailsService;
@Autowired
JwtAuthenticationFilter jwtAuthenticationFilter;
@Autowired
JwtAutheticationEntryPoint unauthorizedHandler;
@Bean
.requestMatchers("/auth/login","/auth/register","/api/gift/welcome").permitAll()
.anyRequest().authenticated()
// .requestMatchers("/api/gift","/api/gift/**")
// .authenticated()
);
httpSecurity.sessionManagement(sessionManager ->
sessionManager.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
httpSecurity.exceptionHandling(exceptionHandling ->
exceptionHandling.authenticationEntryPoint(
unauthorizedHandler::commence) );
httpSecurity.authenticationProvider(authenticationProvider());
httpSecurity.addFilterBefore(jwtAuthenticationFilter,
UsernamePasswordAuthenticationFilter.class);
return httpSecurity.build();
// @Bean
// return http.csrf().disable()
// .authorizeHttpRequests()
// .requestMatchers("/auth/login","/auth/register","/api/gift/welcome")
// .permitAll()
// .and()
// .authorizeHttpRequests()
// .requestMatchers("/api/gift/**")
// .authenticated()
// .and()
// .sessionManagement()
// .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
// .and()
// .exceptionHandling().authenticationEntryPoint(unauthorizedHandler)
// .and()
// .authenticationProvider(authenticationProvider())
// .addFilterBefore(jwtAuthenticationFilter,
UsernamePasswordAuthenticationFilter.class).build();
// }
@Bean
@Bean
authenticationProvider.setUserDetailsService(userDetailsService);
authenticationProvider.setPasswordEncoder(passwordEncoder());
return authenticationProvider;
@Bean
return config.getAuthenticationManager();
}
Controller
AuthController.java
package com.examly.springapp.controller;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.examly.springapp.configuration.JwtUtils;
import com.examly.springapp.model.User;
import com.examly.springapp.service.UserService;
@RestController
@Autowired
@Autowired
@Autowired
System.out.println("************Register : "+user);
userService.registerUser(user);
return ResponseEntity.status(HttpStatus.CREATED).body(true);
@PostMapping("/auth/login")
if(authentication.isAuthenticated()){
return jwtService.GenerateToken(user.getUsername());
else {
GiftController.java
package com.examly.springapp.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.examly.springapp.model.Gift;
import com.examly.springapp.service.GiftService;
@RestController
@Autowired
@GetMapping("/api/gift/welcome")
@PreAuthorize("permitAll()")
@PostMapping("/api/gift")
@PreAuthorize("hasAuthority('ADMIN')")
return ResponseEntity.status(HttpStatus.CREATED).body(giftService.addGift(gift));
@PutMapping("/api/gift/{giftId}")
@PreAuthorize("hasAuthority('ADMIN')")
@DeleteMapping("/api/gift/{giftId}")
@PreAuthorize("hasAuthority('ADMIN')")
return ResponseEntity.status(HttpStatus.OK).body(giftService.deleteGift(giftId));
@GetMapping("/api/gift")
@PreAuthorize("permitAll()")
return ResponseEntity.status(HttpStatus.OK).body(giftService.getAllGift());
@GetMapping("/api/gift/{giftId}")
@PreAuthorize("permitAll()")
return ResponseEntity.status(HttpStatus.OK).body(giftService.getGiftById(giftId));