java - What are the best practices of sharing the user id among microservices? -
i have 2 spring boot microservices deployed of now:
- auth gateway
- restful services business logic.
auth gateway issues jwt token after successful login. next request, validates/authorizes jwt token before redirecting request business logic.
best way share user related information auth gateway other services?
between auth gateway
written using springsecurity , spring boot.
encode necessary details (user id etc.) in jwt token.
you issue token in auth gateway , jwt access token has 3 parts: header, claims , signature
place necessary info claims section. see the example
@component public class jwttokenfactory { private final jwtsettings settings; @autowired public jwttokenfactory(jwtsettings settings) { this.settings = settings; } /** * factory method issuing new jwt tokens. * * @param username * @param roles * @return */ public accessjwttoken createaccessjwttoken(usercontext usercontext) { if (stringutils.isblank(usercontext.getusername())) throw new illegalargumentexception("cannot create jwt token without username"); if (usercontext.getauthorities() == null || usercontext.getauthorities().isempty()) throw new illegalargumentexception("user doesn't have privileges"); claims claims = jwts.claims().setsubject(usercontext.getusername()); claims.put("scopes", usercontext.getauthorities().stream().map(s -> s.tostring()).collect(collectors.tolist())); datetime currenttime = new datetime(); string token = jwts.builder() .setclaims(claims) .setissuer(settings.gettokenissuer()) .setissuedat(currenttime.todate()) .setexpiration(currenttime.plusminutes(settings.gettokenexpirationtime()).todate()) .signwith(signaturealgorithm.hs512, settings.gettokensigningkey()) .compact(); return new accessjwttoken(token, claims); }
Comments
Post a Comment