首页 > 解决方案 > Angular 5发送请求时如何防止Spring安全登录重定向302

问题描述

我总是得到 302 响应而不是 JSON 响应(200 OK),当我尝试使用 Spring Boot JWT 登录时,是否有任何合理的方法可以阻止 Spring Security 在成功身份验证后重定向我的 http 请求,顺便说一句,我正在使用角度 5 HttpClient 向 Spring boot 发送 Http 请求。我已经尝试了网络上的所有解决方案,但不幸的是它们都不起作用!!!

@EnableWebSecurity
public class SecurityTasks extends WebSecurityConfigurerAdapter{
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private BCryptPasswordEncoder bcrypt;
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(bcrypt);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {     
        http.csrf().disable();
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.authorizeRequests().antMatchers("/login/**","/register/**","/").permitAll();
        http.authorizeRequests().antMatchers(HttpMethod.POST,"/tasks/**").hasAuthority("ADMIN");
        http.authorizeRequests().anyRequest().authenticated();
        // authenticationManager() will return authentication object  
        http.addFilter(new JWTAuthenticationFilter(authenticationManager()));
        http.addFilterBefore(new JWTAuthorizationFilter(),UsernamePasswordAuthenticationFilter.class);
    }
}

JWT授权码:

public class JWTAuthorizationFilter extends OncePerRequestFilter{

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse res, FilterChain filterChain)
            throws ServletException, IOException {
          res.addHeader("Access-Control-Allow-Origin", "*");
          res.addHeader("Access-Control-Allow-Headers",
            "Origin,Accept,X-Requested-With,Content-Type,"
            + "Access-Control-Request-Method,"
            + "Acces-Control-Request-Headers,"
            + "Authorization");
          res.addHeader("Access-Control-Expose-Headers",
            "Access-Control-Allow-Origin,"
            + "Access-Control-Allow-Credentials,Authorization");
          if(request.getMethod().equals("OPTIONS")){
           res.setStatus(HttpServletResponse.SC_OK);
          }

        String jwt  = request.getHeader(SecurityConstants.HEADER_STRING);
        System.out.println("***********c*************"+jwt+"*********************");
        if (jwt == null || !jwt.startsWith(SecurityConstants.TOKEN_PREFIX)) {
            filterChain.doFilter(request, res); return;
        }
        Claims claims = Jwts.parser()
                        .setSigningKey(SecurityConstants.SECRET)
                        .parseClaimsJws(jwt.replace(SecurityConstants.TOKEN_PREFIX,""))
                        .getBody();
        String username = claims.getSubject();
        ArrayList<Map<String,String>> roles = (ArrayList<Map<String,String>>) claims.get("roles");
        Collection<GrantedAuthority> authoroties = new ArrayList<>();
        roles.forEach(t->{authoroties.add(new SimpleGrantedAuthority(t.get("authority")));});
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username,null,authoroties);
        // context security de spring this set will charge utilisateur authentifie
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request, res);
          }

}

标签: angularspring-bootangular2-jwt

解决方案


推荐阅读