多角色安全配置Spring MVC + Thymeleaf

时间:2019-01-30 16:22:02

标签: java spring security model-view-controller thymeleaf

我有2种类型的用户角色,我想在登录后为每种类型的用户设置不同的页面,但是我不知道该怎么做。

SecurityConfiguration

    @Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    public static final String SQL_LOGIN = "select username, password, active as enabled \n"
            + "from user where username = ?";

    public static final String SQL_PERMISSION = "select u.username, r.role as authority\r\n" + 
            "           from user u join user_role ur on u.id = ur.user_id join role r on ur.role_id = r.role_id\r\n" + 
            "           where u.username = ?";

    @Autowired
    private DataSource dataSource;

    @Autowired
    public void configurGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication().dataSource(dataSource).usersByUsernameQuery(SQL_LOGIN)
                .authoritiesByUsernameQuery(SQL_PERMISSION).passwordEncoder(passwordEncoder()); // bcrypt

    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
        .authorizeRequests()
        .antMatchers("/js/**").permitAll()
        .antMatchers("/css/**").permitAll()
        .antMatchers("/img/**").permitAll()
        .antMatchers("/fonts/**").permitAll()
        .antMatchers("/user/**").permitAll()
        .anyRequest().authenticated()
        .and()
        .formLogin()
        .loginPage("/login").permitAll()
        .defaultSuccessUrl("/vehicle/list", true)
        .and()
        .logout();
    }

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

}

WebMvcConfig

@Configuration

公共类WebMvcConfig实现WebMvcConfigurer {

@Override
public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/login").setViewName("login");
}

我如何制作不同的端点页面,一个用于ADMIN,另一个用于User?

//(ADMIN)
.loginPage("/login").permitAll() 
    .defaultSuccessUrl("/vehicle/list_admin", true)


//USER
.loginPage("/login").permitAll() 
        .defaultSuccessUrl("/vehicle/list", true)

类似的事情,有人可以帮我吗?

问候

2 个答案:

答案 0 :(得分:0)

您将需要实现一个AuthenticationSuccessHandler,以检查角色并根据该角色进行重定向。

检查下一个答案,以了解有关如何实现处理程序的想法。

AuthenticationSuccessHandler Spring Security

答案 1 :(得分:0)

您将需要一个AuthenticationSuccessHandler。像下面的代码这样的东西应该可以解决问题。

public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws
            IOException,
            ServletException {
        User principal = (User) authentication.getPrincipal();
        boolean isAdmin = false;
        Iterator<GrantedAuthority> grantedAuthorityIterator = principal.getAuthorities().iterator();
        while (grantedAuthorityIterator.hasNext()) {
            if (grantedAuthorityIterator.next().getAuthority().equalsIgnoreCase("ADMIN")) {
                isAdmin = true;
            }
        }
        if (isAdmin) {
            response.sendRedirect("/vehicle/list_admin");
        } else {
            response.sendRedirect("/vehicle/list");
        }
    }
}

此外,您将需要在Spring Security配置文件中添加此选项。 .successHandler(CustomAuthenticationSuccessHandler)