在Angular前端中访问JWT授权令牌-通过响应标头从后端(spring)发送

时间:2020-06-08 09:36:26

标签: angular spring spring-boot spring-security jwt

我想用Spring-boot后端和Angular前端创建一个基本的登录应用

注册用户存储在数据库中。 user table in database

现在,在登录页面中,用户将在登录URL: / user / login

中输入电子邮件和密码(不是加密的密码)。

如果用户已在数据库中注册,则后端将通过响应标头(而不是通过响应正文)发送JWT令牌以及用户ID。请参见 successfulAuthentication 方法中的以下代码:

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
    }
}

后端工作正常。请参阅邮递员测试: POST req to login url with correct creds

我的问题是:从响应标头中提取那些“ Authorization”和“ UserID”标头的Angular方法是什么。

我的最终目标是将这些标头添加到浏览器存储中,并从前端向后端发送后续请求(对于CRUD)。

请原谅我的英语不好。

1 个答案:

答案 0 :(得分:1)

这应该有效。

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