如何检查授权标头是否已发送?

时间:2019-11-26 17:30:28

标签: reactjs spring authentication jwt axios

我正在使用React和Spring Boot开发一个应用程序。我正在使用JWT。它是第一次工作。但是,当我重新加载浏览器时,axios.get不会检索任何内容并说未授权。我正在设置axios拦截器,在该拦截器中指定随每个请求发送授权标头。但是当我重新加载时它似乎不起作用。当我通过菜单在组件之间切换时,它可以工作,但不仅限于刷新浏览器时。 我的组件: 主要之一:

class MapApp extends Component {


    render() {
        return (
            <>
                <Router>
                    <>
                        <MenuComponent />
                        <Switch>
                            <Route path="/" exact component={LoginComponent} />
                            <Route path="/login" exact component={LoginComponent} />
                            <AuthenticatedRoute path="/logout" exact component={LogoutComponent} />
                            <AuthenticatedRoute path="/calculations" exact component={Calculations} />
                            <AuthenticatedRoute path="/calculations/:idCalc" exact component={Cluster} />
                            <AuthenticatedRoute path="/calculation-types" exact component={CalcTypes} />
                        </Switch>
                    </>
                </Router>
            </>
        )
    }
}

export default MapApp

菜单只是链接。

组件:

export default class Calculations extends Component {
  isCMounted = false;
  constructor(props) {
    super(props)

    this.state = {
        items: [],
        selected: null,
        addModalShow: false,
        updateModalShow: false,
        updateId: null,
        buttonOn: false,
        page: 1,
        elements: 0,
        newElements: null,
        loaded: false
    }
}

  componentDidMount() {
    this.isCMounted = true;
    console.log(localStorage.getItem('token'))
      this.load();
    console.log(AuthenticationService.isUserLoggedIn())
    console.log(AuthenticationService.getLoggedInUserName())
  };

  componentDidUpdate() {
    if(!this.state.loaded){
      this.load();
    }
  };

  componentWillUnmount(){
    this.isCMounted = false;
  }
  load = async () => {
    await axios.get('calculations')
    .then(res => {
      if (this.isCMounted && this.state.items.id === res.data.id){
        this.setState({items: res.data})
      }
    });
    if(this.state.selected != null && this.isCMounted) {
      this.setState({buttonOn: true})
    }
    this.setState({loaded: true})
  }
...
}

服务器上的过滤器:

package net.lacit.map.runner.maprunner.config;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import io.jsonwebtoken.ExpiredJwtException;

@Component
public class JwtTokenAuthorizationOncePerRequestFilter extends OncePerRequestFilter {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private UserDetailsService jwtInMemoryUserDetailsService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Value("${jwt.http.request.header}")
    private String tokenHeader;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        logger.debug("Authentication Request For '{}'", request.getRequestURL());

        final String requestTokenHeader = request.getHeader(this.tokenHeader);

        String username = null;
        String jwtToken = null;
        if (requestTokenHeader != null && requestTokenHeader.startsWith("Bearer ")) {
            jwtToken = requestTokenHeader.substring(7);
            try {
                username = jwtTokenUtil.getUsernameFromToken(jwtToken);
            } catch (IllegalArgumentException e) {
                logger.error("JWT_TOKEN_UNABLE_TO_GET_USERNAME", e);
            } catch (ExpiredJwtException e) {
                logger.warn("JWT_TOKEN_EXPIRED", e);
            }
        } else {
            logger.warn("JWT_TOKEN_DOES_NOT_START_WITH_BEARER_STRING");
        }

        logger.debug("JWT_TOKEN_USERNAME_VALUE '{}'", username);
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {

            UserDetails userDetails = this.jwtInMemoryUserDetailsService.loadUserByUsername(username);

            if (jwtTokenUtil.validateToken(jwtToken, userDetails)) {
                UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                usernamePasswordAuthenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
            }
        }

        chain.doFilter(request, response);
    }
}

0 个答案:

没有答案