java - Spring boot how make a user role managing with jwt -


i'm writing restful api spring boot. i'm using spring boot, jersey, mongo db, swagger, spring boot security , jwt.

i have written models, repositories requests db. have integrated security , jwt token.

now need discretize role of users, because user cant call route need admin priviledges.

i have route login, it's return token. code of securityconfig

... @configuration @enablewebsecurity public class securityconfig extends websecurityconfigureradapter{      @autowired     userrepository userrepository;      @override     public void configure(httpsecurity httpsecurity) throws exception {         httpsecurity.csrf().disable().authorizerequests()                 .antmatchers("/").permitall()                 .antmatchers("/api/swagger.json").permitall()                 .antmatchers(httpmethod.post, "/login").permitall()                 .antmatchers("/api/*").authenticated()                 .and()                  .addfilterbefore(new jwtloginfilter("/login", authenticationmanager(), userrepository),                         usernamepasswordauthenticationfilter.class)                  .addfilterbefore(new jwtauthenticationfilter(),                         usernamepasswordauthenticationfilter.class);     }  } 

i written jwtloginfilter return me token when user makes login

... @override public authentication attemptauthentication(httpservletrequest req, httpservletresponse res) throws authenticationexception, ioexception, servletexception {     credential creds = new objectmapper().readvalue(req.getinputstream(), credential.class);      user user = userrepository.login(creds);      if (user == null)         throw new badcredentialsexception("");      usernamepasswordauthenticationtoken token = new usernamepasswordauthenticationtoken(         creds.getusername(),         creds.getpassword()     );      return token; } ... 

i want insert on endpoint class on method

@preauthorize("hasrole('role_admin')") 

this part of endpoint

....  @component @path("story") @api(value = "story", produces = "application/json") public class storyendpoint {      private static final logger logger = loggerfactory.getlogger(storyendpoint.class);      @autowired     storyrepository storyrepository;       @get     @path("/")     @produces(mediatype.application_json)     @preauthorize("hasrole('role_admin')") <--- want insert here     @apioperation(value = "get story", response = story.class)     @apiresponses(value = {             @apiresponse(code = 200, message = "hello resource found"),             @apiresponse(code = 404, message = "given admin user not found")     })     public response getallstory(){         iterable<story> stories = storyrepository.findall();         logger.info("getallstory");         return (stories!=null) ? response.ok(stories).build() : response.ok(responseerrorgenerator.generate(response.status.not_found)).status(response.status.not_found).build();     } .... 

how can make mechanism assign user role , how can pass role in token , discretize on route role of user?

you need store user roles inside jwt token additional claims, extract them after token validation , pass 'authorities' principal:

 collection<? extends grantedauthority> authorities                 = arrays.aslist(claims.get(authorities_key).tostring().split(",")).stream()                 .map(authority -> new simplegrantedauthority(authority))                 .collect(collectors.tolist());          user principal = new user(claims.getsubject(), "",                 authorities);          usernamepasswordauthenticationtoken t                 = new usernamepasswordauthenticationtoken(principal, "", authorities); 

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -