【问题标题】:How to show a different page for a type of user in spring security如何在 Spring Security 中为一类用户显示不同的页面
【发布时间】:2014-11-19 12:21:05
【问题描述】:

我正在一个使用 spring security 的 spring mvc 项目中工作,我是 spring security 的新手,我想知道如何在我的应用程序中拥有两种类型的用户,一个普通用户和一个管理员用户,并展示一个与管理员用户不同的索引页面和对普通用户具有较少功能的另一个索引页面,到目前为止我有这个:

我的 configSecurity 类 WebSecurityConfigurerAdapter

public class ConfigSecurity extends WebSecurityConfigurerAdapter {

private AutenticarProvider authen;


    @Override
    protected void configure( HttpSecurity http ) throws Exception 
    {
        http
            .authenticationProvider(authen)
            .authorizeRequests()
                    .antMatchers("/resources/**").permitAll()
                    .antMatchers("/css/**").permitAll() 
                    .antMatchers("/js/**").permitAll()
                    .antMatchers("/img/**").permitAll() 
                    .antMatchers("/sound/**").permitAll() 
                    .antMatchers("/fonts/**").permitAll()
                    .antMatchers("/ajax/**").permitAll()
                    .antMatchers("/php/**").permitAll()
                    .antMatchers("/xml/**").permitAll()
                    .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')") <-- i am not sure about this just guessing
                    .anyRequest().authenticated()
                    .and()
            .formLogin()
                    .loginPage("/loginPage")
                    .permitAll()
                    .and()
            .logout()                                    
                    .permitAll();
    }
}

还有我实现 AuthenticationProvider 的类:

@Component
public class AutenthenProvider implements AuthenticationProvider 
{
public Authentication authenticate(Authentication authentication) 
            throws AuthenticationException {

        User user = null;
        Authentication auth = null;
        String name = null;
        String password = null;

        try 
        {
            name = authentication.getName();
            password = authentication.getCredentials().toString();

            if(name != null && !name.trim().equals("") && password != null && !password.trim().equals(""))
            {
                user  =  this.obtainUserFromDataBase(name);

                if(user  != null)
                {
                    List<GrantedAuthority> grantedAuths = new ArrayList<GrantedAuthority>();



                    auth = new UsernamePasswordAuthenticationToken(name, password);
                }
                else
                {
                    throw new UsernameNotFoundException("the user dont exist");

                }

            }
            else
            {
                throw new BadCredentialsException("invalid credentials");
            }
        } 
        catch (AuthenticationException e) {
            throw e;
        }
        catch (Exception ex) {
            throw new AuthenticationServiceException("", ex.getCause());
        }

        return auth;
    }

和我的控制器类中的控制器方法

    @RequestMapping(value = "/loginPage", method = RequestMethod.GET)
    public String loginPage(Model model) {

        logger.info("**Login PAGE!!**");

        return "loginPage";
    }

我正在考虑将这一行 .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')") 放在我的配置方法中,但我不确定它是如何工作的,如果我这样做意味着我将有重复的页面,因为我的应用程序中有页面可以两个用户都可以查看这是否意味着我将这两个页面重复但在不同的文件夹中?

【问题讨论】:

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


    【解决方案1】:

    您可以根据角色使用tags that Spring has builtin,例如管理员或用户。您还可以定义自定义角色。

    <sec:authorize access="hasRole('supervisor')">
    
    This content will only be visible to users who have
    the "supervisor" authority in their list of <tt>GrantedAuthority</tt>s.
    
    </sec:authorize>
    

    您还可以通过hasRole([role]) method 获得基于代码的解决方案,或者查看此答案How to check "hasRole" in Java Code with Spring Security?

    【讨论】:

    • 我有一个基于代码的配置,我找到的所有教程都是针对 xml 配置的,你有一个基于代码的教程,也许你可以给我?
    • 我觉得可以用hasRole([role])的方法(不过我自己没试过)
    【解决方案2】:

    首先,正确的方法是使用角色。在你AuthenticationProvider 中,你给管理员用户一个GrantedAuthority ROLE_ADMIN,通过稍微修改它:

    List<GrantedAuthority> grantedAuths = new ArrayList<GrantedAuthority>();
    
    // only if user is recognized as admin
        grantedAuths.add(new SimpleGrantedAuthority("ROLE_ADMIN")
    
    auth = new UsernamePasswordAuthenticationToken(name, password);
    

    然后您将能够使用.antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")/admin/** 的访问权限限制为管理员用户,并且您可以将放在JSP 页面中

    <sec:authorize access="hasRole('ROLE_ADMIN')">
    
    This content will only be visible to users who have
    the "ROLE_ADMIN" authority in their list of <tt>GrantedAuthority</tt>s.
    
    </sec:authorize>
    

    由 909 Niklas 提议

    无论如何,我几乎从来不用实现AuthenticationProvider。我通常使用DaoAuthenticationProvider 和相关的UserDetailsServiceInMemoryUserDetailsManager 用于测试,JdbcUserDetailsManager 当用户存储在真正的数据库中时)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-02
      • 2018-01-20
      • 1970-01-01
      • 2011-03-28
      • 2016-11-23
      • 2021-11-13
      • 1970-01-01
      • 2016-11-01
      相关资源
      最近更新 更多