简体   繁体   中英

Spring Security hasAuthority is not working properly

I have 3 roles Super Admin, Admin and User. I redirect to two different pages after login. If Admin or Super Admin logged in, it will redirect to /dashboard . If User logs in, it will redirect to /pos . But after Admin and User logged in, it shows 403 page every time. I don't understand why.

@Configuration
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomUserDetailsService userDetailsService;

    @Autowired
    private AuthenticationSuccessHandler authenticationSuccessHandler;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .userDetailsService(userDetailsService)
            .passwordEncoder(passwordEncoder());
    }

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

        String loginPage = "/login";
        String logoutPage = "/logout";

        http
            .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.ALWAYS)
                .and()
            .authorizeRequests()
                .antMatchers(loginPage).permitAll()              
                .antMatchers("/dashboard", "/boxes/**", "/manufacturers/**", "/brands/**",
                        "/stocks/**", "/suppliers/**", "/saleinvoices/**", "/purchaseinvoices/**",
                        "/purchases/**", "/sales/**", "/returns/**", "/users/**").hasRole("ADMIN")
                .antMatchers("/dashboard", "/stocks/**", "/pos").hasRole("USER")    
                .antMatchers("/**").hasAuthority("SUPER_ADMIN")
                .anyRequest().authenticated()
                .and()
            .csrf().disable()
            .formLogin()
                .loginPage(loginPage).permitAll()
                .loginPage("/")
                .failureUrl("/login?error=true")
                .successHandler(authenticationSuccessHandler)
                .usernameParameter("username")
                .passwordParameter("password")
                .and()
            .logout()
                .logoutRequestMatcher(new AntPathRequestMatcher(logoutPage))
                .logoutSuccessUrl(loginPage)
                .and()
            .exceptionHandling();
        }
    }

    @Component
    public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

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

        Set<String> roles = AuthorityUtils.authorityListToSet(authentication.getAuthorities());

        if (roles.contains("USER")) {
            httpServletResponse.sendRedirect("/pos");
        } else {
               httpServletResponse.sendRedirect("/dashboard");
        }
    }
}

您可以使用 hasAnyRole() 并允许 ADMIN 和 SUPER_ADMIN 访问仪表板

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM