【问题标题】:Best way to handle multiply roles in spring security [duplicate]在春季安全中处理多个角色的最佳方法[重复]
【发布时间】:2019-12-09 15:00:55
【问题描述】:

我正在使用 Spring 模块和休眠将 Web 应用程序构建为宠物项目。 我想将具有不同权限的用户重定向到不同的页面。 到目前为止,我有我的WebSecurityConfigurerAdapter:

@EnableWebSecurity
public class ConfigSecurity extends WebSecurityConfigurerAdapter {


    @Autowired
    UserDetailsService userDetailsService;


    @Autowired
    public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {

        PasswordEncod encodde = new PasswordEncod();

            auth.userDetailsService(userDetailsService).passwordEncoder(new PasswordEncod());
    }



    @Override
    protected void configure(HttpSecurity http) throws Exception {
         http
                .authorizeRequests()
                .antMatchers("/curator").authenticated();

        http.formLogin()
                .loginPage("/login")
                .failureUrl("/login?error")
                .usernameParameter("j_username")
                .passwordParameter("j_password")
                .permitAll().and().csrf().disable();
    }
}

和自定义 UserDetails 服务:

    public class MyUserDetailsService  implements UserDetailsService {
    UserDao dao = new UserDaoImpl();

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        System.out.println(s);
        User user = dao.getByUsername(s);
        System.out.println(user.toString());

        return
                new org.springframework.security.core.userdetails
                        .User(
                        user.getUsername(),
                        user.getPassword(),
                        buildUserAuthority(user));
    }

    private List<GrantedAuthority> buildUserAuthority(User user) {

        Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>();

        for (UserRole userRole : user.getUserRoles()) {
            setAuths.add(new SimpleGrantedAuthority(userRole.toString()));
        }

        List<GrantedAuthority> Result = new ArrayList<GrantedAuthority>(setAuths);

        return Result;
    }

}

我想创建一个登录页面,根据客户的权限将客户重定向到默认用户或管理页面,但我不明白这样做的最佳做法是什么。我曾考虑过制作一个可以完成这项工作的控制器,但我认为有更好的解决方案。我做得好吗,也许你可以建议我一些改进或方法?

【问题讨论】:

    标签: spring spring-mvc spring-security


    【解决方案1】:

    对于重定向,请遵循此 - spring security redirect based on role。但是一旦你配置了你的情况:

    antMatchers("/curator").authenticated()
    ...
    antMatchers("/some-action-**").access("hasAuthority('ADMIN')")
    

    只需使用 Spring Security 标签来隐藏链接。例如,使用安全标签为需要一些管理员角色的普通用户隐藏链接。如果上述配置正确,普通用户即使尝试访问受保护的 URL,也会被拒绝访问。让 Spring-Security 为您完成艰苦的(安全)工作。对于完整的示例,您可以参考this、this,最后是this。

    【讨论】:

    • 感谢回复
    猜你喜欢
    • 2017-09-15
    • 1970-01-01
    • 1970-01-01
    • 2020-04-12
    • 2011-09-28
    • 1970-01-01
    • 1970-01-01
    • 2021-01-07
    • 1970-01-01
    相关资源
    最近更新 更多