java - User Authentication with REST in a web app secured with Spring Security -
my spring boot-based web app authenticates against remote rest api. so, have extended abstractuserdetailsauthenticationprovider
so:
public class restauthenticationprovider extends abstractuserdetailsauthenticationprovider { @override protected void additionalauthenticationchecks(userdetails userdetails, usernamepasswordauthenticationtoken authentication) throws authenticationexception { // todo auto-generated method stub } @override protected userdetails retrieveuser(string username, usernamepasswordauthenticationtoken authentication) throws authenticationexception { string password = (string) authentication.getcredentials(); credentials creds = new credentials(); creds.setusername(username); creds.setpassword(password); resttemplate template = new resttemplate(); try { responseentity<authentication> auth = template.postforentity("http://localhost:8080/api/authenticate", creds, authentication.class); if (auth.getstatuscode() == httpstatus.ok) { string token = auth.getheaders().get("authorization").get(0); // great! what? return new user(authentication.getname(), password, collections.singletonlist(new simplegrantedauthority("role_user"))); } throw new badcredentialsexception("failed authenticate, server returned " + auth.getstatuscodevalue()); } catch (httpclienterrorexception e) { // check type of error throw new badcredentialsexception(e.getstatustext()); } } }
this works great. problem subsequent access api require api key being provided in resttemplate
headers. line :
string token = auth.getheaders().get("authorization").get(0); // great! what?
what i'm after way persist token @ session level future access. down line, i'm trying along lines of:
securitycontext context = securitycontextholder.getcontext(); authentication userdetails = context.getauthentication() ;
where somehow userdetails
contain api key.
any suggestions?
thanks!
this you designing & implementing own security solution. framework provides way implement how resolve userdetails
based on credentials.
i see question subsequent invocations of this. reason "old school" web apps have sessions, "new school" thinks it's "not cool" anymore "does not scale" ( or whatever other reasons ) , assume you're 1 of those.
if don't want use sessions - need user database ( or cache, or session store, or ) based on identified.
your current implementation provides feature using username , password, assume don't want keep in memory & send every request.
so want generate token, store in database ( or cache, or token store, or session store ) , implement authenticationprovider
next time read userdetails
based on token, not user credentials.
you use jwt
token able serialize whole userdetails
object token & send on wire, wouldn't recommend either there no way invalidate it, unless you're storing token id
in database / session store.
more read here: invalidating json web tokens
Comments
Post a Comment