首页 > 解决方案 > 认证成功后的 Spring Security 返回 403

问题描述

我从具有权限的用户登录,但它总是返回 403 用户具有措施所需的角色,即使它不允许我访问我不确定是否需要在标题中包含其他任何内容,其他已发布案例对我不起作用

安全配置文件

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

    @Autowired
    private ControllerUserServicesDetails userServDetails;
    @Autowired
    private JWTSerivice jWTService;

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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/", "/css/**", "/js/").permitAll()
                .anyRequest().authenticated().and()
                .addFilter(new JWTAuthenticationFilter(authenticationManager(), jWTService))
                .addFilter(new JWTAutoritationFilter(authenticationManager(), jWTService))
                .csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and().cors().configurationSource(corsConfigurationSource());
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
        config.setAllowCredentials(true);
        config.setAllowedOrigins(Arrays.asList("*"));
        config.setAllowedHeaders(Arrays.asList("Content-Type", "Authorization"));
        config.addAllowedHeader("Access-Control-Allow-Origin");
        config.addAllowedHeader("cache-control");
        config.addAllowedHeader("authentication");
        config.addAllowedHeader("access-control-allow-headers");
        config.addAllowedHeader("access-control-allow-methods");
        config.addAllowedHeader("credentials");
        config.addExposedHeader("Access-Control-Allow-Credentials");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return source;
    }

    @Bean
    public FilterRegistrationBean<CorsFilter> corsFilter() {
        FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<CorsFilter>(new CorsFilter(corsConfigurationSource()));
        bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
        return bean;
    }

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

}

过滤器验证.java

public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    private AuthenticationManager authenticationManager;
    private JWTSerivice jWTService;

    public JWTAuthenticationFilter(AuthenticationManager authenticationManager, JWTSerivice jWTService) {
        this.authenticationManager = authenticationManager;
        this.jWTService = jWTService;
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request,
            HttpServletResponse response) throws AuthenticationException {
        String username = request.getParameter("usuario");
        String password = request.getParameter("clave");
        if (username == null && password == null) {
            Usuario user = null;
            try {
                user = new ObjectMapper().readValue(request.getInputStream(), Usuario.class);
                username = user.getUsuario();
                password = user.getClave();
            } catch (IOException ex) {
                Logger.getLogger(JWTAuthenticationFilter.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        logger.info("usuarios " + username);
        logger.info("passs " + password);
        username = username.trim();
        UsernamePasswordAuthenticationToken authToken
                = new UsernamePasswordAuthenticationToken(username, password);
        logger.info("authToken " + authenticationManager.authenticate(authToken));
        return authenticationManager.authenticate(authToken);
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        String token = jWTService.create(authResult);
        response.addHeader(JWTServiceImp.HEADER_STRING, JWTServiceImp.TOKEN_PREFIX + token);
        Map<String, Object> body = new HashMap<>();
        body.put("token", token);
        body.put("user", (User) authResult.getPrincipal());
        body.put("mensaje", "Session inciada con exito");
        response.getWriter().write(new ObjectMapper().writeValueAsString(body));
        response.setStatus(200);
        response.setContentType("application/json");
    }

    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
        Map<String, Object> body = new HashMap<>();
        body.put("mensaje", "error de autenticacion username o password icorrecto!!!");
        body.put("error", failed.getMessage());
        response.getWriter().write(new ObjectMapper().writeValueAsString(body));
        response.setStatus(401);
        response.setContentType("application/json");
    }

}

我想访问的方法

@RestController
@RequestMapping("/empresa/")
@CrossOrigin(origins = "*", methods= {RequestMethod.GET,RequestMethod.POST},allowCredentials = "true")
public class EmpresaServices {

    @Autowired
    private EmpresaDao dao;

    @Secured({"ROLE_EMPRESA"})
    @PostMapping("/saveorupdate/")
    public Empresa saveOrUpdate(@RequestBody Empresa e) {
        return dao.saveOrUpdate(e);
    }

    @Secured({"ROLE_EMPRESA"})
    @GetMapping("/findall/")
    public List<Empresa> findall() {
        return dao.findAll();
    }

    @Secured({"ROLE_EMPRESA"})
    @GetMapping("/findallmenu/{user}/")
    public List<MenuUsuario> findallMenu(@PathVariable Long user) {
        return dao.findAllMenu(user);
    }
}

userDetailsS​​ervices.java

@Service
public class ControllerUserServicesDetails implements UserDetailsService {

    @Autowired
    private UsuarioDao usuarioDao;
    private final Logger logger = LoggerFactory.getLogger(ControllerUserServicesDetails.class);

    @Override
    @Transactional(readOnly = true)
    public UserDetails loadUserByUsername(String usario) throws UsernameNotFoundException {
        Usuario usuario = usuarioDao.findByUsuario(usario);
        logger.error("usuario " + usuario.getUsuario());
        logger.error("usuario " + usuario.getClave());
        if (usuario == null) {
            logger.error("ERROR EL USUARIO NO EXISTE");
            throw new UsernameNotFoundException("USUARIO NO EXISTE");
        }
        List<GrantedAuthority> granList = new ArrayList<>();
        for (MenuUsuario menu : usuario.getMenuUsuarioList()) {
            granList.add(new SimpleGrantedAuthority(menu.getMenu().getRoles()));
        }
        User user = new User(usuario.getUsuario(), usuario.getClave(), "ACTIVO".equals(usuario.getEstatus()), true, true, true, granList);
        return user;
    }
}

标签: javaspringspring-bootspring-security

解决方案


推荐阅读