1

I'm working in a spring mvc project using spring security, i am new to spring security and i wanted to know how to have two types of users in my application, a normal-user and an admin-user and show a different index page to the admin-user and another index page with less functions to the normal user, so far i have this:

My configSecurity class 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();
    }
}

And my class that implements 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;
    }

and my controller method from my controller class

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

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

        return "loginPage";
    }

I am thinking of putting this line .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')") in my configure method but i am not sure how this works, if i put that does that mean that i am going to have duplicate pages because there are pages in my application that can be view by both users does this mean that i am going to have those two pages duplicated but in different folders?

Cœur
  • 37,241
  • 25
  • 195
  • 267
stackUser2000
  • 1,615
  • 11
  • 32
  • 55

2 Answers2

0

You can use tags that Spring has builtin for the purpose based on roles e.g. admin or user. You can also define custom roles.

<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>

You might also have luck with the hasRole([role]) method for a code-based solution or have a look at this answer How to check "hasRole" in Java Code with Spring Security?

Community
  • 1
  • 1
Niklas Rosencrantz
  • 25,640
  • 75
  • 229
  • 424
0

First, the correct way is to use roles. In you AuthenticationProvider, you give a GrantedAuthority ROLE_ADMIN to admin users, by slightly modifying it :

List<GrantedAuthority> grantedAuths = new ArrayList<GrantedAuthority>();

// only if user is recognized as admin
    grantedAuths.add(new SimpleGrantedAuthority("ROLE_ADMIN")

auth = new UsernamePasswordAuthenticationToken(name, password);

Then you will be able to use .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')") to restrict access to /admin/** to admin users, and you can put in a JSP page

<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>

as proposed by 909 Niklas

Anyway, I almost never had to implement an AuthenticationProvider. I generally use a DaoAuthenticationProvider and a relevant UserDetailsService (InMemoryUserDetailsManager for tests and JdbcUserDetailsManager when the users are stored in a true database).

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252