简体   繁体   中英

Accessing JWT Authorization token in Angular front-end - sent from back-end(spring) via response header

I want to create a basic login app with Spring-boot back-end and Angular front-end.

Registered users are stored in the database. 数据库中的用户表

Now, in the login page, user will enter email and password(not the encrypted one) in login URL: /user/login

If the user is registered in the database, back-end will send a JWT token along with the user id via response header (not via response body). See the code below in successfulAuthentication method:

public class AuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    private final AuthenticationManager authenticationManager;

    public AuthenticationFilter(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res)
            throws AuthenticationException {

        try {
            UserLoginRequestModel creds = new ObjectMapper()
                    .readValue(req.getInputStream(), UserLoginRequestModel.class);

            return authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(
                            creds.getEmail(),
                            creds.getPassword(),
                            new ArrayList<>()
                    )
            );

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void successfulAuthentication(
            HttpServletRequest req, HttpServletResponse res, FilterChain chain, Authentication auth)
            throws IOException, ServletException {

        String userName = ((User) auth.getPrincipal()).getUsername();

        String token = Jwts.builder()
                .setSubject(userName)
                .setExpiration(new Date(System.currentTimeMillis() + SecurityConstants.EXPIRATION_TIME))
                .signWith(SignatureAlgorithm.HS512, SecurityConstants.getTokenSecret())
                .compact();

        UserService userService = (UserService) SpringApplicationContext.getBean("userServiceImpl");
        UserDto userDto = userService.getUser(userName);

        res.addHeader(SecurityConstants.HEADER_STRING, SecurityConstants.TOKEN_PREFIX + token); 
        // HEADER: Authorization: Bearer ...jsonwebtoken...

        res.addHeader("UserID", userDto.getUserId());
        // HEADER: UserId: asdf3232sf
    }
}

The backend works fine. See the Postman testing: POST req 以使用正确的凭据登录 url

My question is: what is the Angular way of extracting those "Authorization" and "UserID" headers from the response header.

My final goal is to add those headers in browser storage and send with subsequent requests(for CRUD) from frontend to backend.

Please excuse my bad English.

This should work.

http.get<any>('http://localhost:8080/users/login', {observe: 'response'}).subscribe(response => {
  console.log(response.headers.get('Authorization'));
  console.log(response.headers.get('UserID'))
});

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