Spring启动如何使用jwt管理用户角色 [英] Spring boot how make a user role managing with jwt

查看:738
本文介绍了Spring启动如何使用jwt管理用户角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用spring boot编写一个RESTful api。
我正在使用spring boot,jersey,mongo db,swagger,spring boot security和jwt。



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



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

我有登录路线,它返回一个令牌。这是我的SecurityConfig的代码

  ... 
@Configuration
@EnableWebSecurity
public class SecurityConfig扩展了WebSecurityConfigurerAdapter {

@Autowired
UserRepository userRepository;

@Override
public void configure(HttpSecurity httpSecurity)抛出异常{
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);
}

}

我写了回报我的JWTLoginFilter用户登录时的令牌

  ... 
@Override
public authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res)抛出AuthenticationException,IOException,ServletException {
Credential creds = new ObjectMapper()。readValue(req.getInputStream(),Credential.class);

用户user = userRepository.login(creds);

if(user == null)
抛出新的BadCredentialsException();

UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
creds.getUsername(),
creds.getPassword()
);

返回令牌;
}
...

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

  @PreAuthorize(hasRole('ROLE_ADMIN'))

这是终点的一部分

  ... 。

@Component
@Path(story)
@Api(value =Story,produce =application / json)
公共类StoryEndpoint {

private static final Logger LOGGER = LoggerFactory.getLogger(StoryEndpoint.class);

@Autowired
StoryRepository storyRepository;


@GET
@Path(/)
@Produces(MediaType.APPLICATION_JSON)
@PreAuthorize(hasRole('ROLE_ADMIN') )< ---我想在这里插入
@ApiOperation(value =Get All Story,response = Story.class)
@ApiResponses(value = {
@ApiResponse(code = = 200,message =hello resource found),
@ApiResponse(code = 404,message =鉴于管理员用户未找到)
})
public Response getAllStory(){
Iterable< Story> stories = storyRepository.findAll();
LOGGER.info(getAllStory);
return(故事!= null)? Response.ok(stories).build():Response.ok(ResponseErrorGenerator.generate(Response.Status.NOT_FOUND))。status(Response.Status.NOT_FOUND).build();
}
....

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

解决方案

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

 集合< ? extends GrantedAuthority> authority 
= Arrays.asList(claims.get(AUTHORITIES_KEY).toString()。split(,))。stream()
.map(authority - > new SimpleGrantedAuthority(authority))
.collect(Collectors.toList());

用户主体=新用户(claims.getSubject(),,
权限);

UsernamePasswordAuthenticationToken t
= new UsernamePasswordAuthenticationToken(principal,,authority);


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 repositories for the requests to the DB. Now I have integrated the Security and jwt token.

Now I need to discretize the role of the users, because a user cant call a route that need an admin priviledges.

I have a route for login, it's return a token. This is the code of my 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 the JWTLoginFilter that return me the 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 this on my endpoint class on method

@PreAuthorize("hasRole('ROLE_ADMIN')")

this is a part of an 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')") <--- 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();
    }
....

How I can make a mechanism for assign to user the role and how i can pass the role in token and discretize on route the role of user?

解决方案

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);

这篇关于Spring启动如何使用jwt管理用户角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆