Validate 2 different user profiles in Spring Security

Asked

Viewed 144 times

-4

Good afternoon, I’m trying to validate two access profiles in Spring Security. The Admin profile and the Tecnicosup, each profile should be directed to a different Home screen. Only the Admin profile is correctly performing. I used as an example this earlier question that is well what I want to do: https://stackoverflow.com/questions/48854004/spring-security-two-roles-implementation . Could someone help me validate the two profiles?

package br.com.sgis.configuration;

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.Authentication.Authenticationsuccesshandler; import org.springframework.security.web.util.matcher.Antpathrequestmatcher;

@Configuration @Enablewebsecurity public class Securityconfiguration 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("/cadastro").permitAll()
            .antMatchers("/recuperarSenha").permitAll()
            .antMatchers("/atualizarSenha").permitAll()
            .antMatchers("/atualizarSenha/**").permitAll()
            .antMatchers("/tecnico/**").hasAuthority("TECNICOSUP")
            .antMatchers("/admin/**").hasAuthority("ADMIN")
            .anyRequest()
            .authenticated().and().csrf().disable().formLogin()
            .loginPage("/login").failureUrl("/login?error=true")
            .successHandler(this.getSuccessHandler())
            .usernameParameter("email")
            .passwordParameter("password")
            .and().logout()
            .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
            .logoutSuccessUrl("/").and().exceptionHandling()
            .accessDeniedPage("/access-denied");

}


private AuthenticationSuccessHandler getSuccessHandler() {
    return (AuthenticationSuccessHandler) new RoleBasedAuthenticationSuccessHandler(
             "/admin/home",
             "/tecnico/home",
               "ROLE_ADMIN"                
            );
}


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

}

import java.io.Ioexception;

import javax.servlet.Servletexception; import javax.servlet.http.Httpservletrequest; import javax.servlet.http.Httpservletresponse;

import org.springframework.security.core.Authentication; import org.springframework.security.core.Grantedauthority; import org.springframework.security.web.Authentication.Authenticationsuccesshandler; import org.springframework.security.web.Authentication.Simpleurlauthenticationsuccesshandler;

public class Rolebasedauthenticationsuccesshandler extends Simpleurlauthenticationsuccesshandler implements AuthenticationSuccessHandler {

Private string adminRoleTargetUrl;

Private string adminRoleAuthority;

/** * @param defaultTargetUrl / public Rolebasedauthenticationsuccesshandler(String defaultTargetUrl, String adminRoleTargetUrl, String adminRoleAuthority) { super(defaultTargetUrl); this.adminRoleTargetUrl = adminRoleTargetUrl; this.adminRoleAuthority = adminRoleAuthority; System.out.println("adminRoleTargetUrl..." + this.adminRoleTargetUrl ); System.out.println("this.adminRoleAuthority.." + this.adminRoleAuthority ); } / (non-Javadoc) * @see org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler#onAuthenticationSuccess(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.springframework.security.core.Authentication) */ @Override public void onAuthenticationSuccess(Httpservletrequest request, Httpservletresponse Response, Authentication Authentication) throws Ioexception, Servletexception { System.out.println("entered here...isAdmin" + isAdmin(Authentication) ); if(isAdmin(Authentication)){ System.out.println("entered if"); this.getRedirectStrategy(). sendRedirect(request, Response, this.getAdminRoleTarUrl()); Return; } super.onAuthenticationSuccess(request, Sponse, Authentication); }

/** * @param Authentication */ protected Boolean isAdmin(Authentication Authentication) { for(Grantedauthority Authority : Authentication.getAuthorities()){ if(Authority.getAuthority().equals(this.getAdminRoleAuthority()){ Return true; } } Return false; }

/** * @Return the adminRoleTargetUrl */ public string getAdminRoleTarUrl() { Return adminRoleTargetUrl; }

/** * @Return the adminRoleAuthority */ public string getAdminRoleAuthority() { Return adminRoleAuthority; }

}

1 answer

0

I managed to find the problem, replace ROLE_ADMIN by ADMIN and worked:

private AuthenticationSuccessHandler getSuccessHandler() {
    return (AuthenticationSuccessHandler) new RoleBasedAuthenticationSuccessHandler(
             "/admin/home",
             "/tecnico/home",
               "ADMIN"                
            );
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.