У меня есть некоторые проблемы, чтобы заставить его работать с spring security hasRole
. У меня есть 2 роли в дБ, сохраненные как ROLE_ADMIN и ROLE_USER . Я хочу дать разрешение на некоторые API с ролью ADMIN, некоторые с ролью USER. ЗДЕСЬ мой код.
SecurityConfig
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private DataSource dataSource;
@Value("${spring.queries.users-query}")
private String usersQuery;
@Value("${spring.queries.roles-query}")
private String rolesQuery;
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.jdbcAuthentication()
.dataSource(dataSource)
.passwordEncoder(bCryptPasswordEncoder())
.usersByUsernameQuery(usersQuery)
.authoritiesByUsernameQuery(rolesQuery);
}
@Override
protected void configure(HttpSecurity http) {
System.out.println("configure " );
try {
http.csrf().disable().authorizeRequests()
.antMatchers("/", "/*.html").permitAll()
.antMatchers("/home").permitAll()
.antMatchers("/login").permitAll()
.antMatchers("/profile/").hasAnyRole("ADMIN","USER")
.antMatchers("/admin/*").hasRole("ADMIN")
.antMatchers("/insurance/*").hasRole("ADMIN")
.antMatchers("/company/*").hasRole("ADMIN")
.anyRequest().authenticated();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void configure(WebSecurity web) {
web.httpFirewall(allowUrlEncodedSlashHttpFirewall())
.ignoring()
.antMatchers("/resources/**", "/static/**", "/css/**", "/js/**", "/images/**", "/templates/**");
}
@Bean
public HttpFirewall allowUrlEncodedSlashHttpFirewall() {
StrictHttpFirewall firewall = new StrictHttpFirewall();
/*firewall.setAllowUrlEncodedSlash(true);
firewall.setAllowSemicolon(true);*/
firewall.setAllowUrlEncodedDoubleSlash(true);
return firewall;
}
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
}
И у меня есть sql queries
в application.properties
spring.queries.users-query=select username, password, status from insurance.users where username=?
spring.queries.roles-query=select u.username, r.role from insurance.users u inner join insurance.roles r on(u.role_id=r.id) where u.username=?
Проблема в том, что когдаЯ пытаюсь войти, я получаю код ошибки 403.
Вот Controller.class
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(@RequestParam(value = "email") String email,
@RequestParam(value = "password") String password, HttpSession session) {
Result result = userService.login(email, password);
session.setAttribute("user", result.getData());
if(result.getStatus() == 200){
return "redirect:/profile";
} else {
return "redirect:/login?error";
}
}
@RequestMapping(value = "/profile", method = RequestMethod.GET)
public String profile(HttpSession httpSession, Model model) {
if(httpSession.getAttribute("user") != null) {
UserResponse user = (UserResponse) httpSession.getAttribute("user");
model.addAttribute("user", user);
return "profile";
} else {
return "redirect:/home";
}
}
Я попытался решить, но не смог найти. Если у вас есть какие-либо советы, пожалуйста, скажите.
Я изменил свой конфигурационный файл, как предложено. Я добавил свою собственную логику входа, теперь, когда я хочу перейти / admins или другой URL, я перенаправить на URL входа в систему Вот мой код конфигурации
protected void configure(HttpSecurity http) {
try {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/home").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/insurance/*").hasRole("ADMIN")
.antMatchers("/company/*").hasRole("ADMIN")
.and()
.formLogin()
.loginPage("/login.html").permitAll().usernameParameter("username") .passwordParameter("password")
.loginProcessingUrl("/login")
.defaultSuccessUrl("/profile.html", true);
} catch (Exception e) {
e.printStackTrace();
}
}