AuthenticationSuccessHandler in Spring Security

前端 未结 2 725
無奈伤痛
無奈伤痛 2020-12-15 07:18

I\'ve used spring security in a Spring Boot application and there are 2 types of users: one is an ADMIN, and one just a simple user. I get the data from a DataSource

相关标签:
2条回答
  • 2020-12-15 07:46
    import java.io.IOException;
    import java.util.Set;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.springframework.security.core.Authentication;
    import org.springframework.security.core.authority.AuthorityUtils;
    import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
    import org.springframework.stereotype.Component;
    
    @Component
    public class Securityhandler implements AuthenticationSuccessHandler {
    
         public void onAuthenticationSuccess(HttpServletRequest request,   HttpServletResponse response, Authentication authentication) throws IOException  {
            Set<String> roles = AuthorityUtils.authorityListToSet(authentication.getAuthorities());
            if (roles.contains("ROLE_ADMIN")) {
                response.sendRedirect("admin/home.html");
            }
        }
    }
    


    You've missed the @Component annotation in your success handler class.

    0 讨论(0)
  • 2020-12-15 08:03

    Rather than sublcassing AuthenticationSuccessHandler, It's worth knowing about the Spring security role-checking config:

    @Configuration
    @EnableWebSecurity
    public class SecSecurityConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
              .authorizeRequests()
              .antMatchers("/admin/**").hasRole("ADMIN");
        }
        ...
    } 
    

    OR pre-checking a Role per endpoint:

    @Autowired
    @PreAuthorize("hasRole('ADMIN')")
    @RequestMapping("/")
    public ModelAndView home(HttpServletRequest request) throws Exception {
    
    }
    

    where the default Role prefix is ROLE_

    https://docs.spring.io/spring-security/site/docs/3.0.x/reference/el-access.html https://www.baeldung.com/spring-security-expressions-basic

    0 讨论(0)
提交回复
热议问题