简体   繁体   中英

Jwt authentication with Angular and spring

I am building the authentication for my angular app using JWT token. For any request to the rest api, I want that spring MVC check for the token in the header of the http request except when the http request is /login (to create a new token).

I am having an issue with my cors filter. It is sending a 401 status after the user is logged in successfully. The token sent in the "authorization" header is not taken into account.

angular service

getListe(): Promise<any> {
        let header = new Headers();
        header.append("authorization", localStorage.getItem("token"))
        return this.http.get(URL_API_REST + 'liste', header)
            .toPromise()
            .then(response => response.json())
            .catch(this.handleError);
    }

Spring Cors Filter

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request= (HttpServletRequest) req;

        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with, Content-Type");
        response.setHeader("Access-Control-Expose-Headers", "x-requested-with");

        if(!request.getRequestURI().equals("/rest/rest/login")) {
            response.setHeader("Access-Control-Allow-Headers", "x-requested-with, authorization");
            response.setStatus(HttpServletResponse.SC_OK);
        }

        /*if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            chain.doFilter(req, res);
        }
*/
        chain.doFilter(req, res);
    }

Spring Authentication Filter

 public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request= (HttpServletRequest) servletRequest;

        String token = request.getHeader("token");
        if(token != null){
            System.out.println("Présence d'un token");
        }
        else{
            if(!request.getRequestURI().equals("/rest/rest/login"))
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        }
        filterChain.doFilter(request, response);
    }

Is there something am I missing ?

I don't have time to try to analyze code now, but I recommend you this project in GitHub that show a simple login system using JWT and Java. I've used it as an example to implement JWT in some of my systems and it worked perfectly. Hope it helps.

I had a hard time dealing with this issue, but I hope the answers will spare the time for some.

Actually, I figured out that my angular wasn't sending the header authorization in the request headers. To solve that issue, I used the RequestOptions in my service Angular.

service Angular

getListe(): Promise<any> {
        let header = new Headers();
        header.append("authorization", localStorage.getItem("token"))
        let options = new RequestOptions({headers: header})
        return this.http.get(URL_API_REST + 'liste', options)
            .toPromise()
            .then(response => response.json())
            .catch(this.handleError);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM