我有一个用户微服务,处理与用户有关的所有事情,包括安全性(创建用户,登录,重设密码...)。 我正在使用JWT令牌来提高安全性。
我的配置安全性如下:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(
securedEnabled = true,
jsr250Enabled = true,
prePostEnabled = true
)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
CustomUserDetailsService customUserDetailsService;
@Autowired
private JwtAuthenticationEntryPoint unauthorizedHandler;
@Bean
public JwtAuthenticationFilter jwtAuthenticationFilter() {
return new JwtAuthenticationFilter();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
/**
* the main Spring Security interface for authenticating a user
*
* @return the {@link AuthenticationManager}
* @throws Exception
*/
@Bean(BeanIds.AUTHENTICATION_MANAGER)
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
/**
* create an AuthenticationManager instance
*
* @param auth AuthenticationManagerBuilder used to create the instance of AuthenticationManager
* @throws Exception
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(customUserDetailsService)
.passwordEncoder(passwordEncoder());
}
/**
* configure security functionality, add rules to protect resources
* define what route can be accessed without authentication
*
* @param http
* @throws Exception
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http.headers().frameOptions().disable();
http
.cors()
.and()
.csrf()
.disable()
.exceptionHandling()
.authenticationEntryPoint(unauthorizedHandler)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/h2-console/**")
.permitAll()
.antMatchers("/api/auth/**")
.permitAll()
.antMatchers(HttpMethod.GET, "/api/user/**")
.permitAll()
.anyRequest()
.authenticated();
// Add our custom JWT security filter
http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
}
}
我要做的是使用用户微服务来保护另一个微服务(目前是基本的CRUD)。
我已经在CRUD微服务中创建了伪装界面
@FeignClient(name="UserMicroservice", url="http://localhost:8080")
public interface UserClient {
@PostMapping(value = "/api/auth/login")
AuthTokenDto authenticateUser(@RequestBody LogInDto logInDto);
}
和控制器
@RestController
public class AuthController {
@Autowired
UserClient userClient;
@PostMapping("/api/auth/login")
public AuthTokenDto authenticate(@RequestBody LogInDto logInDto) {
AuthTokenDto token = userClient.authenticateUser(logInDto);
return token;
}
}
这可以成功调用用户微服务并获取jwt令牌。
但是我不知道如何让我的CRUD微服务使用用户微服务的安全配置。
那么,从本质上讲,我该如何使用用户微服务来保护CRUD微服务的端点?
到目前为止,我一直无法自行找到解决方案,也无法搜索互联网。
答案 0 :(得分:1)
我建议您将令牌保存在redis数据库中并在所有微服务中实现安全层,并且每次您的微服务收到请求时,如果令牌存在,则实现JWT的类将在redis中进行搜索。
我这样实现
public class JWTAuthorizationFilter extends BasicAuthenticationFilter{
public JWTAuthorizationFilter(AuthenticationManager authenticationManager) {
super(authenticationManager);
}
@Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
throws IOException, ServletException {
String header = req.getHeader(Constantes.HEADER_AUTHORIZACION_KEY);
Logger.getLogger(JWTAuthorizationFilter.class.getCanonicalName()).log(Level.INFO, "HEADER: "+header);
if (header == null || !header.startsWith(Constantes.TOKEN_BEARER_PREFIX)) {
chain.doFilter(req, res);
return;
}
UsernamePasswordAuthenticationToken authentication = getAuthentication(req);
SecurityContextHolder.getContext().setAuthentication(authentication);
chain.doFilter(req, res);
}
private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
String token = request.getHeader(Constantes.HEADER_AUTHORIZACION_KEY);
Logger.getLogger(JWTAuthorizationFilter.class.getCanonicalName()).log(Level.INFO, "token: "+token);
if (token != null) {
// Se procesa el token y se recupera el usuario.
Jedis jedis = new Jedis(SystemVariables.getDataBaseRedisIp());
String key = jedis.get(token);
Logger.getLogger(JWTAuthorizationFilter.class.getCanonicalName()).log(Level.INFO, "key: "+key);
String user = JWT.require(Algorithm.HMAC256(key)).build()
.verify(token.replace(Constantes.TOKEN_BEARER_PREFIX, ""))
.getSubject();
if (user != null) {
return new UsernamePasswordAuthenticationToken(user, null, new ArrayList<>());
}
return null;
}
return null;
}
然后在每个http请求上添加标头Authorization以及生成的令牌,例如:
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhZG1pbiIsImV4cCI6MTU2NDEwNjMzNX0.HzG2nKUReCsrEZZOQLH8cuh3yfuP4VX0tkDvWTS8_s8