java–jwt_java – Spring引导如何使用jwt管理用户角色

我正在用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);

}

}

我编写了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;

}

...

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

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

这是端点的一部分

....

@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')")

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

}

....

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值