Проблемы с входом в систему и ролью Java Spring
Я пишу базовое веб-приложение с использованием Java Spring Boot, и в настоящее время у меня возникают проблемы с ролями моих пользователей в моей базе данных и доступом к различным частям приложения. Пользователи могут иметь роль "ADMIN" или "USER". Единственная разница между тем, что разрешено для этих двух ролей, заключается в том, что АДМИНИСТРАТОР может посещать страницу "/register", в то время как другие люди в роли ПОЛЬЗОВАТЕЛЬ не могут. Я разместил код для моего метода настройки http ниже и не уверен, где я ошибаюсь. Я хочу, чтобы все пользователи могли получить доступ к странице входа и только ADMIN для доступа к странице "/register". Проблема, с которой я столкнулся, заключается в том, что на данный момент по какой-то причине страница "/home" моего приложения может быть видна даже без входа в систему. Вход в систему с использованием того, что у меня указано ниже, не выполняется принудительно.
package bcoreHW.security;
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;
import org.springframework.security.crypto.password.PasswordEncoder;
import bcoreHW.service.UserService;
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UserService userService;
@Autowired
private PasswordEncoder passwordEncoder;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers( // allow users access to any files in js, css, and img directories
"/login",
"/js/**",
"/css/**",
"/img/**")
.permitAll()
.antMatchers("/register")
.hasRole("ADMIN")
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/home")
.permitAll()
.and()
.logout()
.permitAll();
}
// @Autowired
// public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
// auth
// .inMemoryAuthentication()
// .withUser("test")
// .password("hello")
// .roles("USER");
// }
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService).passwordEncoder(passwordEncoder);
}
}
Если я изменю метод configure() на то, что указано ниже, по крайней мере, пользователь будет вынужден войти в систему, и разрешения оттуда будут правильными по принципу "по щелчку", но я все равно могу перейти к адресную строку и выполните поиск по запросу "/register" в роли ПОЛЬЗОВАТЕЛЯ, поэтому я попытался реализовать первый опубликованный мной фрагмент кода. Ни один из них еще не работал, и надеялся на некоторую помощь.
package bcoreHW.security;
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;
import org.springframework.security.crypto.password.PasswordEncoder;
import bcoreHW.service.UserService;
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UserService userService;
@Autowired
private PasswordEncoder passwordEncoder;
@Override
protected void configure(HttpSecurity http) throws Exception {
//@formatter:off
http
.authorizeRequests()
.antMatchers( // allow users access to any files in js, css, and img directories
"/login",
"/js/**",
"/css/**",
"/img/**")
.permitAll()
.anyRequest().
authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/home")
.permitAll()
.and()
.logout()
.permitAll();
}
// @Autowired
// public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
// auth
// .inMemoryAuthentication()
// .withUser("test")
// .password("hello")
// .roles("USER");
// }
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService).passwordEncoder(passwordEncoder);
}
}
1 ответ
Убедитесь, что вы сохраняете пользователей с ролями как ROLE_ADMIN
а также ROLE_USER
в базе данных
@Override
public void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers( "/login", "/js/**", "/css/**", "/img/**").permitAll() // allow users access to any files in js, css, and img directories
.antMatchers("/register").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/login")
.defaultSuccessUrl("/home").permitAll()
.and()
.logout().permitAll();
}