繁体   English   中英

在 Angular 前端访问 JWT 授权令牌 - 通过响应 header 从后端(弹簧)发送

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

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

注册用户存储在数据库中。 数据库中的用户表

现在,在登录页面,用户将在登录 URL 中输入 email 和密码(不是加密的): /user/login

如果用户在数据库中注册,后端将通过响应 header(不是通过响应正文)发送一个 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
    }
}

后端工作正常。 请参阅 Postman 测试: POST req 以使用正确的凭据登录 url

我的问题是:从响应 header 中提取那些“授权”和“用户 ID”标头的 Angular 方法是什么。

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

请原谅我的英语不好。

这应该有效。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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