Spring boot how make a user role managing with jwt

前端 未结 3 474
栀梦
栀梦 2021-01-03 09:24

I\'m writing a RESTful api with spring boot. I\'m using spring boot, jersey, mongo db, swagger, spring boot security and jwt.

I have written the models, the reposito

3条回答
  •  半阙折子戏
    2021-01-03 09:53

    First need to add the roles inside the JWT. For that you can add as Claim in the JWT Generator class.

        public String generateToken(UserDetails userDetails) {
            Map claims = new HashMap<>();
            Set Userroles = new HashSet<>();
            User user = userRepository.findByUsername(userDetails.getUsername());
            for(Role role:user.getRoles()){
                Userroles.add(role.getName());
            }
            claims.put("Roles",Userroles.toArray());
            return createToken(claims, userDetails.getUsername());
        }
    
        private String createToken(Map claims, String subject) {
            
            return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(new Date(System.currentTimeMillis()))
                    .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 10))
                    .signWith(SignatureAlgorithm.HS256, SECRET_KEY).compact();
        }
    

    In the user model class need to include the roles in Set or any other data structure.

     @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
        @JoinTable(name = "USER_ROLES", joinColumns = {
                @JoinColumn(name = "USER_ID") }, inverseJoinColumns = {
                @JoinColumn(name = "ROLE_ID") })
        private Set roles;
    

    In the Repository need to have a method like below.

    User findByUsername(String username);
    

    Please check this Github Repo(https://github.com/Senthuran100/SpringBoot_JWT) for your reference.

提交回复
热议问题