有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java JWT应该是一个独立的auth微服务,而不是与后端业务逻辑坐在一起吗?

我是微服务体系结构的新手,我正在使用SpringBoot构建应用程序,希望为我的API添加JWT auth

参考链接:https://dzone.com/articles/spring-boot-security-json-web-tokenjwt-hello-world

我想知道是否应该将身份验证/授权代码从business micro service(BMS)中分离出来。因此,每次对BMS的rest API调用都会反过来调用auth微服务进行验证。这是一种很好的做法,还是会对网络流量造成很大影响

电话可能看起来像:

客户->;BusinessApp->;AuthMS->;商务应用程序->;客户

将其分离出来的原因是,有些配置和代码与业务应用程序结合起来看起来不太好,但我不确定每次API调用所需的网络成本

JWT应用程序中的示例代码,在运行不同的服务/服务器时有意义吗?:

import java.util.Objects;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.javainuse.service.JwtUserDetailsService;
import com.javainuse.config.JwtTokenUtil;
import com.javainuse.model.JwtRequest;
import com.javainuse.model.JwtResponse;
@RestController
@CrossOrigin
public class JwtAuthenticationController {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private JwtTokenUtil jwtTokenUtil;
@Autowired
private JwtUserDetailsService userDetailsService;
@RequestMapping(value = "/authenticate", method = RequestMethod.POST)
public ResponseEntity<?> createAuthenticationToken(@RequestBody JwtRequest authenticationRequest) throws Exception {
authenticate(authenticationRequest.getUsername(), authenticationRequest.getPassword());
final UserDetails userDetails = userDetailsService
.loadUserByUsername(authenticationRequest.getUsername());
final String token = jwtTokenUtil.generateToken(userDetails);
return ResponseEntity.ok(new JwtResponse(token));
}
private void authenticate(String username, String password) throws Exception {
try {
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
} catch (DisabledException e) {
throw new Exception("USER_DISABLED", e);
} catch (BadCredentialsException e) {
throw new Exception("INVALID_CREDENTIALS", e);
}
}
}

共 (1) 个答案

  1. # 1 楼答案

    让api网关处理所有授权请求是一种很好的做法。 请求将通过api网关进行验证,然后才能访问微服务(业务逻辑所在的位置)。让您的网关负责以下事项:

    (1) validate tokens with every request (2) prevent all unauthenticated requests to the services

    Check this out for more details