Spring启动AccessDeniedException异常

时间:2017-09-19 05:58:27

标签: java spring-boot spring-security

我是春季启动新手,在启动时配置弹簧安全性需要一些帮助。 这是我的控制器类

@RequestMapping(value = UrlMapping.LOGIN, method = RequestMethod.GET)
public String login(Model model, String error, String logout) {
    if (error != null) {
        model.addAttribute(UIAttribute.ERROR, "Your username and password is invalid.");
    }

    if (logout != null) {
        model.addAttribute(UIAttribute.MESSAGE, "You have been logged out successfully.");
    }

    return UrlMapping.LOGIN_DESTINATION_JSP;
}

这个是安全配置类

    @Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private AccessDeniedHandlerImpl accessDeniedHandler;

    @Autowired
    UserDetailsService userDetailsServiceImpl;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.httpBasic().and().authorizeRequests().anyRequest().authenticated()
                .antMatchers("/**").hasRole("ADMIN")
                .antMatchers("/welcome").hasRole("USER").and()
                .formLogin()
                .loginPage("/login")
                .failureUrl("/login?error")
                .defaultSuccessUrl("/welcome").and()
                .exceptionHandling().accessDeniedHandler(accessDeniedHandler);
    }

    @Autowired
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .inMemoryAuthentication()
                .withUser("user").password("password").roles("USER")
                .and().withUser("admin").password("admin").roles("USER", "ADMIN");
        auth.userDetailsService(userDetailsServiceImpl).passwordEncoder(encoder());
    }

    @Bean
    UserDetailsServiceImpl userDetailsServiceImpl() {
        return new UserDetailsServiceImpl();
    }

    @Bean(name = BeanIds.AUTHENTICATION_MANAGER)
    @Override
    public AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    BCryptPasswordEncoder encoder() {
        return new BCryptPasswordEncoder(11);
    }
}

这是AccessDeniedHandlerImpl类

    // handle 403 page
@Component
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {

    private static Logger logger = LoggerFactory.getLogger(AccessDeniedHandlerImpl.class);

    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                       AccessDeniedException e) throws IOException, ServletException {

        Authentication auth = SecurityContextHolder.getContext().getAuthentication();

        if (auth != null) {
            logger.info("User '" + auth.getName() + "' attempted to access the protected URL: "
                    + httpServletRequest.getRequestURI());
        }

        httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/403");
    }
}

这是UserDetailsS​​erviceImpl类

@Transactional
@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    @Override
    @Transactional(readOnly = true)
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findByUsername(username);

        Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
        for (Role role : user.getRoles()){
            grantedAuthorities.add(new SimpleGrantedAuthority(role.getName()));
        }

        return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), grantedAuthorities);
    }
}

任何人都可以帮我解决这个问题:当我点击此网址“http://localhost:8084/login”时,为什么我会收到此例外。

 org.springframework.security.access.AccessDeniedException: Access is denied
    at org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:84) ~[spring-security-core-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:233)

0 个答案:

没有答案