Spring Security中不同角色的多个主页

时间:2017-05-18 11:11:08

标签: java spring-mvc spring-boot spring-security

我正致力于使用安全功能启动并运行Spring Boot应用程序。我遇到了一些困难,因为我已经创造了其他问题。然而,这个问题有点在功能方面。我有多个角色,如ADMIN和CUSTOMER,登录后我想将它们发送到各自的在线页面。我想到的一种方法是创建一个目标网页,然后使用Cookie重定向它们,虽然我不知道如何做到这一点。如果我的方法正确或Spring Boot提供的默认功能,请您提供任何示例,请告诉我。

这是我的SecurityConfig类:

package com.crossover.techtrial.java.se.config;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private DataSource dataSource;

    @Value("${spring.queries.users-query}")
    private String usersQuery;

    @Value("${spring.queries.roles-query}")
    private String rolesQuery;

    @Override
    protected void configure(AuthenticationManagerBuilder auth)
            throws Exception 
    {
        auth.
            jdbcAuthentication()
                .usersByUsernameQuery(usersQuery)
                .authoritiesByUsernameQuery(rolesQuery)
                .dataSource(dataSource)
                .passwordEncoder(bCryptPasswordEncoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.
            authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/login").permitAll()
                .antMatchers("/registration").permitAll()
                .antMatchers("/app/*").hasAnyAuthority("ADMIN", "CUSTOMER")
                .antMatchers("/admin/**").hasAuthority("ADMIN").anyRequest()                
                .authenticated().and().csrf().disable().formLogin()
                .loginPage("/login").failureUrl("/login?error=true")
                .defaultSuccessUrl("/home")
                .usernameParameter("username")
                .passwordParameter("password")
                .and().logout()
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                .logoutSuccessUrl("/").and().exceptionHandling()
                .accessDeniedPage("/access-denied");
    }

    @Override
    public void configure(WebSecurity web) throws Exception 
    {
        web
           .ignoring()
           .antMatchers("/resources/**", "/static/**", "/css/**", "/js/**", "/images/**");
    }

}

编辑:

正如dur所指出的,我可能需要做这样的事情:

public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {


@Override
public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {

    HttpSession session = httpServletRequest.getSession();
    User authUser = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); 
    session.setAttribute("username", authUser.getUsername());        

    //set our response to OK status
    httpServletResponse.setStatus(HttpServletResponse.SC_OK);

    // Now I need to redirect the user based on his role.
    httpServletResponse.sendRedirect("home");
}

}

现在的问题是我如何从authUser获取角色的名称。我希望我做得对,我不需要做任何其他事情。其次,我如何将这个成功的处理程序安装到我的SecurityConfig类。请突出显示需要进行的更改。

2 个答案:

答案 0 :(得分:2)

正如@dur建议我通过添加CustomSuccessHandler解决了这个问题:

@Component
@Configuration
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler 
{
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest,
            HttpServletResponse httpServletResponse, Authentication authentication) 
                    throws IOException, ServletException, RuntimeException 
    {
        HttpSession session = httpServletRequest.getSession();
        User authUser = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        session.setAttribute("username", authUser.getUsername());
        //set our response to OK status
        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        authorities.forEach(authority -> 
                                { 
                                    if(authority.getAuthority().equals("ADMIN_ROLE")) 
                                    { 
                                        session.setAttribute("role", AppRole.ADMIN);
                                        try
                                        {
                                            //since we have created our custom success handler, its up to us to where
                                            //we will redirect the user after successfully login
                                            httpServletResponse.sendRedirect("/admin/home");
                                        } 
                                        catch (IOException e) 
                                        {
                                            throw new RuntimeException(e);
                                        }                                                                           
                                    }
                                    else if (authority.getAuthority().equals("CUSTOMER_ROLE"))
                                    {
                                        session.setAttribute("role", AppRole.CUSTOMER);
                                        try
                                        {
                                            //since we have created our custom success handler, its up to us to where
                                            //we will redirect the user after successfully login
                                            httpServletResponse.sendRedirect("/user/home");
                                        } 
                                        catch (IOException e) 
                                        {
                                            throw new RuntimeException(e);
                                        }   
                                    }
                                });

    }
}

我通过配置:

添加了这个
http.
    authorizeRequests()
        .antMatchers("/user/**").hasAuthority("CUSTOMER_ROLE")
        .antMatchers("/admin/**").hasAuthority("ADMIN_ROLE").anyRequest()               
        .authenticated().and().csrf().disable().formLogin()
        .loginPage("/login").failureUrl("/login?error=true")
        .successHandler(successHandler) // successHandler is a reference to my CustomAuthenticationSuccessHandler
        ....

答案 1 :(得分:-1)

首先尝试从 SecurityContextHolder 获取 SecurityContext (弹出框架保留的 SecurityContext 的持有者) 验证成功后身份验证对象。使用 SecurityContext ,您可以获取身份验证对象 securityContext.getAuthentication(),您可以从中获取用户角色 身份验证对象并使用此身份验证对象,检查 用户角色并重定向到不同用户角色的不同主页。