Я пытаюсь получить доступ к странице приветствия после входа в систему, используя
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService customUserDetailsService;
@Autowired
private DataSource dataSource;
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
authenticationManagerBuilder.userDetailsService(customUserDetailsService).passwordEncoder(passwordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/resources/**").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.successForwardUrl("/welcome")
.permitAll()
.and()
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/");
}
}
Мой UserDetailsService
:
@Service(value = "customUserDetailsService")
public class CustomUserDetailsServiceImpl implements UserDetailsService {
private static Logger logger = LoggerFactory.getLogger(CustomUserDetailsServiceImpl.class);
@Autowired
private UserService userService;
@Override
@Transactional(readOnly = true)
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
User user = userService.findByEmail(email);
if (user == null) {
logger.error("User with email" + email + " not found.");
throw new UsernameNotFoundException("Oops! User not found with username: " + email);
} else {
logger.info("User {} successfully logged", user.getUsername());
return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(), getAuthorities(user));
}
}
private Collection<GrantedAuthority> getAuthorities(User user) {
List<GrantedAuthority> authorities = new ArrayList<>();
for (UserProfile userProfile : user.getUserProfileSet()) {
authorities.add(new SimpleGrantedAuthority("ROLE_" + userProfile.getType()));
}
return authorities;
}
}
Соответствующие биты контроллеров:
@RequestMapping(value = "/", method = RequestMethod.GET)
public String index(Principal principal) {
if (logger.isDebugEnabled()) {
logger.debug("getWelcome is executed");
System.out.println(principal);
}
return principal == null ? "homeNotSignedIn" : "welcome";
}
@GetMapping("/login")
public String login(Model model, String error, String logout) {
if (error != null)
model.addAttribute("error", "Your username and password is invalid.");
if (logout != null)
System.out.println(">>>>>>>>>>>>>>>>>>> LOGOUT <<<<<<<<<<<<<<<<<<");
model.addAttribute("message", "You have been logged out successfully.");
return "login";
}
@GetMapping("/welcome")
public String welcome(Model model) {
System.out.println(">>>>>>>>>>>>>>>>>>>>>>> WELCOME <<<<<<<<<<<<<<<<<<<<<<<");
return "welcome";
}
Мой pom.xml
:
<?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>ie.gtludwig.pa</groupId>
<artifactId>pa</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<name>PA</name>
<modules>
<module>core</module>
<module>engine</module>
</modules>
<properties>
<!-- JAVA -->
<version.java>1.8</version.java>
<java.version>${version.java}</java.version>
<jdk.version>${version.java}</jdk.version>
<maven.compiler.target>${version.java}</maven.compiler.target>
<maven.compiler.source>${version.java}</maven.compiler.source>
<!-- Generic properties -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!-- External Dependency Versions -->
<spring-boot.version>2.1.3.RELEASE</spring-boot.version>
<jedis.version>2.9.1</jedis.version>
<junit.version>4.12</junit.version>
<logback.version>1.2.3</logback.version>
<thymeleaf.version>3.0.11.RELEASE</thymeleaf.version>
<thymeleaf-layout-dialect.version>2.3.0</thymeleaf-layout-dialect.version>
<flyway.version>5.2.0</flyway.version>
<mysql.version>8.0.16</mysql.version>
<h2database.version>1.4.199</h2database.version>
<sendgrid-java.version>4.3.0</sendgrid-java.version>
<commons-lang3.version>3.7</commons-lang3.version>
<commons-io.version>2.6</commons-io.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<!--WEB-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-json</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>nz.net.ultraq.thymeleaf</groupId>
<artifactId>thymeleaf-layout-dialect</artifactId>
<version>${thymeleaf-layout-dialect.version}</version>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>
<!--SECURITY-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!--OPERATIONS-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.jolokia</groupId>
<artifactId>jolokia-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!--SERVER-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<!--DATABASE-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
<scope>runtime</scope>
</dependency>
<!--TEST DATABASE FOR TESTING PROCESSES AND RULES IN-MEMORY-->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${h2database.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.2.17.Final</version>
<scope>runtime</scope>
</dependency>
<!--EMAIL-->
<!-- https://mvnrepository.com/artifact/com.sendgrid/sendgrid-java -->
<dependency>
<groupId>com.sendgrid</groupId>
<artifactId>sendgrid-java</artifactId>
<version>${sendgrid-java.version}</version>
</dependency>
<!--DEV/TEST-->
<!--DEV TOOLS CONFLICT WITH JREBEL - DISABLE THIS IF JREBEL IS BEING USED -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<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>
<version>5.0.7.RELEASE</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
<plugin>
<!-- Resource plugin to enable expanding properties from this file so that they can be exposed by the zone (E.g. @project.version@) -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
<configuration>
<nonFilteredFileExtensions>
<!--font/binary files must be excluded from filtering or they will be corrupted-->
<nonFilteredFileExtension>woff2</nonFilteredFileExtension>
<nonFilteredFileExtension>woff</nonFilteredFileExtension>
<nonFilteredFileExtension>ttf</nonFilteredFileExtension>
<nonFilteredFileExtension>jks</nonFilteredFileExtension>
</nonFilteredFileExtensions>
<delimiters>
<delimiter>@</delimiter>
</delimiters>
<useDefaultDelimiters>false</useDefaultDelimiters>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<archive>
<manifestEntries>
<!-- Add our project version to the manifest file -->
<version>${project.version}</version>
<description>${project.description}</description>
</manifestEntries>
</archive>
<failOnMissingWebXml>false</failOnMissingWebXml>
<attachClasses>false</attachClasses>
</configuration>
<version>3.1.0</version>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>external</id>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<version>${spring-boot.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
</profile>
</profiles>
Что происходит:
Когда я получаю доступ к localhost:8080/core
, я получаю правильную страницу homeNotSignedIn
, но нет CSS или JS, загруженных из /resources/**
.Я нажимаю ссылку перенаправления входа на страницу входа (опять же без CSS или JS) и CAN .Зарегистрированное имя пользователя отображается на консоли, поэтому customUserDetailsService
вроде бы работает нормально, но меня не перенаправляют на /welcome
.На данный момент я могу выйти из системы, набрав /logout
в URL, и это работает и отправляет меня на homeNotSignedIn
.
Я перебираюсь туда-сюда и не могу получитьэто сделано.
Чего мне не хватает?
Я все время повторял это и не могу этого сделать.
Чего мне не хватает?
РЕДАКТИРОВАТЬ Мне удалось загрузить CSS и JS, изменив:
.antMatchers("/resources/**").permitAll()
на:
.antMatchers("/css/**", "/js/**").permitAll()