Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement Spring Security for Admin and User Roles, Refactor Controllers, and Add Custom 403 Page #80

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 15 additions & 16 deletions JtProject/.classpath
Original file line number Diff line number Diff line change
@@ -1,27 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" output="target/classes" path="src/main/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
<attributes>
<attribute name="maven.pomderived" value="true"/>
<attribute name="optional" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
<attributes>
<attribute name="test" value="true"/>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-11">
<attributes>
<attribute name="module" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
Expand All @@ -45,13 +31,26 @@
<attribute name="m2e-apt" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="target/test-classes" path="target/generated-test-sources/test-annotations">
<classpathentry kind="src" output="target/classes" path="src/main/java">
<attributes>
<attribute name="ignore_optional_problems" value="true"/>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
<attribute name="test" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="target/test-classes" path="target/generated-test-sources/test-annotations">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
<attribute name="ignore_optional_problems" value="true"/>
<attribute name="m2e-apt" value="true"/>
<attribute name="test" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="target/classes"/>
Expand Down
4 changes: 2 additions & 2 deletions JtProject/.project
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,12 @@
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name>
<name>org.eclipse.buildship.core.gradleprojectbuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.buildship.core.gradleprojectbuilder</name>
<name>org.eclipse.m2e.core.maven2Builder</name>
<arguments>
</arguments>
</buildCommand>
Expand Down
8 changes: 6 additions & 2 deletions JtProject/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,11 @@
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>


<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>

</dependencies>

Expand All @@ -70,4 +74,4 @@
</plugins>
</build>

</project>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
package com.jtspringproject.JtSpringProject.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
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.util.matcher.AntPathRequestMatcher;

import com.jtspringproject.JtSpringProject.models.User;
import com.jtspringproject.JtSpringProject.services.userService;

@Configuration
public class SecurityConfiguration {

userService UserService;

public SecurityConfiguration(userService UserService) {
this.UserService = UserService;
}

@Configuration
@Order(1)
public static class AdminConfigurationAdapter{

@Bean
SecurityFilterChain adminFilterChain(HttpSecurity http) throws Exception {
http.antMatcher("/admin/**")
.authorizeHttpRequests(requests -> requests
.requestMatchers(new AntPathRequestMatcher("/admin/login")).permitAll()
.requestMatchers(new AntPathRequestMatcher("/admin/**")).hasRole("ADMIN")
)
.formLogin(login -> login
.loginPage("/admin/login")
.loginProcessingUrl("/admin/loginvalidate")
.successHandler((request, response, authentication) -> {
response.sendRedirect("/admin/"); // Redirect on success
})
.failureHandler((request, response, exception) -> {
response.sendRedirect("/admin/login?error=true"); // Redirect on failure
}))

.logout(logout -> logout.logoutUrl("/admin/logout")
.logoutSuccessUrl("/admin/login")
.deleteCookies("JSESSIONID"))
.exceptionHandling(exception -> exception
.accessDeniedPage("/403") // Custom 403 page
);
http.csrf(csrf -> csrf.disable());
return http.build();
}
}

@Configuration
@Order(2)
public static class UserConfigurationAdapter{

@Bean
SecurityFilterChain userFilterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(requests -> requests
.antMatchers("/login", "/register", "/newuserregister" ,"/test", "/test2").permitAll()
.antMatchers("/**").hasRole("USER"))
.formLogin(login -> login
.loginPage("/login")
.loginProcessingUrl("/userloginvalidate")
.successHandler((request, response, authentication) -> {
response.sendRedirect("/"); // Redirect on success
})
.failureHandler((request, response, exception) -> {
response.sendRedirect("/login?error=true"); // Redirect on failure
}))

.logout(logout -> logout.logoutUrl("/logout")
.logoutSuccessUrl("/login")
.deleteCookies("JSESSIONID"))
.exceptionHandling(exception -> exception
.accessDeniedPage("/403") // Custom 403 page
);

http.csrf(csrf -> csrf.disable());
return http.build();
}
}

@Bean
UserDetailsService userDetailsService() {
return username -> {
User user = UserService.getUserByUsername(username);
if(user == null) {
throw new UsernameNotFoundException("User with username " + username + " not found.");
}
String role = user.getRole().equals("ROLE_ADMIN") ? "ADMIN":"USER";

return org.springframework.security.core.userdetails.User
.withUsername(username)
.passwordEncoder(input->passwordEncoder().encode(input))
.password(user.getPassword())
.roles(role)
.build();
};
}

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