Last active
December 16, 2021 21:10
-
-
Save MWhyte/82ea154ba267be3be4f1617fbe93ebde to your computer and use it in GitHub Desktop.
A Post: Spring Security - User Roles and ThymeLeaf Extras
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Post: https://mwhyte.dev/spring-security-user-roles-and-thymeleaf-extras-c10113d4ad75 | |
Repo - https://github.com/mwhyte-dev/spring-security/tree/2.thymeleaf-extras |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package dev.mwhyte.spring.sec; | |
import org.springframework.boot.SpringApplication; | |
import org.springframework.boot.autoconfigure.SpringBootApplication; | |
@SpringBootApplication | |
public class Application { | |
public static void main(String[] args) { | |
SpringApplication.run(Application.class, args); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#server.port=8080 | |
spring.thymeleaf.mode=HTML |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package dev.mwhyte.spring.sec; | |
import org.hamcrest.CoreMatchers; | |
import org.hamcrest.Matcher; | |
import org.junit.jupiter.api.Test; | |
import org.junit.jupiter.api.extension.ExtendWith; | |
import org.springframework.beans.factory.annotation.Autowired; | |
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; | |
import org.springframework.boot.test.context.SpringBootTest; | |
import org.springframework.security.test.context.support.WithMockUser; | |
import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.FormLoginRequestBuilder; | |
import org.springframework.test.context.junit.jupiter.SpringExtension; | |
import org.springframework.test.web.servlet.MockMvc; | |
import static org.hamcrest.core.StringContains.containsString; | |
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin; | |
import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.authenticated; | |
import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.unauthenticated; | |
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; | |
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; | |
@ExtendWith(SpringExtension.class) | |
@SpringBootTest | |
@AutoConfigureMockMvc | |
public class ApplicationTests { | |
@Autowired | |
private MockMvc mockMvc; | |
@Test | |
public void loginWithValidUserThenAuthenticated() throws Exception { | |
FormLoginRequestBuilder login = formLogin() | |
.user("user") | |
.password("pass"); | |
mockMvc.perform(login) | |
.andExpect(authenticated().withUsername("user")); | |
} | |
@Test | |
public void loginWithInvalidUserThenUnauthenticated() throws Exception { | |
FormLoginRequestBuilder login = formLogin() | |
.user("invalid") | |
.password("invalidpassword"); | |
mockMvc.perform(login) | |
.andExpect(unauthenticated()); | |
} | |
@Test | |
public void accessUnsecuredResourceThenOk() throws Exception { | |
mockMvc.perform(get("/css/style.css")) | |
.andExpect(status().isOk()); | |
} | |
@Test | |
public void accessSecuredResourceUnauthenticatedThenRedirectsToLogin() throws Exception { | |
mockMvc.perform(get("/hello")) | |
.andExpect(status().is3xxRedirection()) | |
.andExpect(redirectedUrlPattern("**/login")); | |
} | |
@Test | |
@WithMockUser | |
public void accessSecuredResourceAuthenticatedThenOk() throws Exception { | |
mockMvc.perform(get("/index")) | |
.andExpect(status().isOk()); | |
} | |
@Test | |
@WithMockUser(roles = "USER") | |
public void loginWithRoleUserThenExpectUserSpecificContent() throws Exception { | |
mockMvc.perform(get("/index")) | |
.andExpect(status().isOk()) | |
.andExpect(content().string(containsString("This content is only shown to users."))) | |
.andExpect(content().string(doesNotContainString("This content is only shown to administrators."))); | |
} | |
@Test | |
@WithMockUser(roles = "ADMIN") | |
public void loginWithRoleAdminThenExpectAdminSpecificContent() throws Exception { | |
mockMvc.perform(get("/index")) | |
.andExpect(status().isOk()) | |
.andExpect(content().string(containsString("This content is only shown to administrators."))) | |
.andExpect(content().string(doesNotContainString("This content is only shown to users."))); | |
} | |
private Matcher<String> doesNotContainString(String s) { | |
return CoreMatchers.not(containsString(s)); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package dev.mwhyte.spring.sec.config; | |
import org.springframework.context.annotation.Configuration; | |
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; | |
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; | |
@Configuration | |
public class MvcConfig implements WebMvcConfigurer { | |
@Override | |
public void addViewControllers(ViewControllerRegistry registry) { | |
registry.addViewController("/").setViewName("login"); | |
registry.addViewController("/index").setViewName("index"); | |
registry.addViewController("/login").setViewName("login"); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="UTF-8"?> | |
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> | |
<modelVersion>4.0.0</modelVersion> | |
<groupId>dev.mwhyte</groupId> | |
<artifactId>spring-security-basic</artifactId> | |
<version>0.0.1-SNAPSHOT</version> | |
<name>spring-security-basic</name> | |
<description>An introduction to spring security</description> | |
<parent> | |
<groupId>org.springframework.boot</groupId> | |
<artifactId>spring-boot-starter-parent</artifactId> | |
<version>2.6.1</version> | |
</parent> | |
<properties> | |
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> | |
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> | |
<java.version>17</java.version> | |
</properties> | |
<dependencies> | |
<dependency> | |
<groupId>org.springframework.boot</groupId> | |
<artifactId>spring-boot-starter-web</artifactId> | |
</dependency> | |
<dependency> | |
<groupId>org.springframework.boot</groupId> | |
<artifactId>spring-boot-starter-thymeleaf</artifactId> | |
</dependency> | |
<dependency> | |
<groupId>org.springframework.boot</groupId> | |
<artifactId>spring-boot-starter-security</artifactId> | |
</dependency> | |
<dependency> | |
<groupId>org.thymeleaf.extras</groupId> | |
<artifactId>thymeleaf-extras-springsecurity5</artifactId> | |
<version>3.0.4.RELEASE</version> | |
</dependency> | |
<!-- TEST --> | |
<dependency> | |
<groupId>org.springframework.boot</groupId> | |
<artifactId>spring-boot-starter-test</artifactId> | |
<scope>test</scope> | |
</dependency> | |
<dependency> | |
<groupId>org.springframework.security</groupId> | |
<artifactId>spring-security-test</artifactId> | |
<scope>test</scope> | |
</dependency> | |
</dependencies> | |
<build> | |
<plugins> | |
<plugin> | |
<groupId>org.springframework.boot</groupId> | |
<artifactId>spring-boot-maven-plugin</artifactId> | |
</plugin> | |
</plugins> | |
</build> | |
</project> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package dev.mwhyte.spring.sec.config; | |
import org.springframework.beans.factory.annotation.Autowired; | |
import org.springframework.context.annotation.Configuration; | |
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; | |
import org.springframework.security.config.annotation.web.builders.HttpSecurity; | |
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; | |
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; | |
@Configuration | |
@EnableWebSecurity | |
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { | |
@Override | |
protected void configure(HttpSecurity http) throws Exception { | |
http | |
.authorizeRequests() | |
.antMatchers( "/css/**", "/images/**", "/favicon.ico").permitAll() | |
.anyRequest().authenticated() | |
.and() | |
.formLogin() | |
.loginPage("/login") | |
.defaultSuccessUrl("/index") | |
.permitAll() | |
.and() | |
.logout() | |
.permitAll() | |
.and().csrf().disable(); // we'll enable this in a later blog post | |
} | |
@Autowired | |
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { | |
auth | |
.inMemoryAuthentication() | |
.withUser("user").password("{noop}pass").roles("USER") | |
.and() | |
.withUser("admin").password("{noop}pass").roles("ADMIN"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment