Spring boot how make a user role managing with jwt

前端 未结 3 475
栀梦
栀梦 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<String, Object> claims = new HashMap<>();
            Set<String> 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<String, Object> 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<Role> 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.

    0 讨论(0)
  • 2021-01-03 10:11

    You need to store user roles inside JWT token as additional claims, extract them after token validation and pass as 'authorities' for 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);
    
    0 讨论(0)
  • 2021-01-03 10:12

    you should add role into Token and for example you can refer following link:- http://www.svlada.com/jwt-token-authentication-with-spring-boot/

    0 讨论(0)
提交回复
热议问题