Spring启动如何使用jwt管理用户角色

Mar*_*oli 2 java roles spring-security jwt spring-boot

我正在用spring boot编写一个RESTful api.我正在使用春季靴子,运动衫,mongo db,swagger,spring boot security和jwt.

我已经编写了模型,请求数据库的存储库.现在我已经集成了Security和jwt令牌.

现在我需要离散用户的角色,因为用户无法调用需要管理员权限的路由.

我有一个登录路线,它返回一个令牌.这是我的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);
    }

}
Run Code Online (Sandbox Code Playgroud)

我编写了JWTLoginFilter,当用户登录时返回令牌

...
@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;
}
...
Run Code Online (Sandbox Code Playgroud)

我想在我的端点类上插入这个方法

@PreAuthorize("hasRole('ROLE_ADMIN')")
Run Code Online (Sandbox Code Playgroud)

这是端点的一部分

....

@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')") <--- I want insert here
    @ApiOperation(value = "Get All 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();
    }
....
Run Code Online (Sandbox Code Playgroud)

我如何建立一种机制来为用户分配角色以及如何在令牌中传递角色并在路由中离散用户的角色?

Ale*_*hev 8

您需要将用户角色存储在JWT令牌中作为附加声明,在令牌验证后提取它们并作为主体的"权限"传递:

 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);
Run Code Online (Sandbox Code Playgroud)


小智 6

首先需要在 JWT 中添加角色。为此,您可以在 JWT Generator 类中添加为 Claim。

    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();
    }
Run Code Online (Sandbox Code Playgroud)

在用户模型类中需要包含 Set 或任何其他数据结构中的角色。

 @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;
Run Code Online (Sandbox Code Playgroud)

在存储库中需要有如下方法。

User findByUsername(String username);
Run Code Online (Sandbox Code Playgroud)

请查看此 Github Repo(https://github.com/Senthuran100/SpringBoot_JWT)以供参考。