java – Spring引导如何使用jwt管理用户角色
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java – Spring引导如何使用jwt管理用户角色,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2995字,纯文字阅读大概需要5分钟。
内容图文
![java – Spring引导如何使用jwt管理用户角色](/upload/InfoBanner/zyjiaocheng/699/aaf41b8a18524eb28957e42ff2eb4438.jpg)
我正在用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')") <--- 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();
}
....
我如何建立一种机制来为用户分配角色以及如何在令牌中传递角色并在路由中离散用户的角色?
解决方法:
您需要将用户角色存储在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);
内容总结
以上是互联网集市为您收集整理的java – Spring引导如何使用jwt管理用户角色全部内容,希望文章能够帮你解决java – Spring引导如何使用jwt管理用户角色所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。