javascript
java–jwt_java – Spring引导如何使用jwt管理用户角色
我正在用spring boot編寫一個(gè)RESTful api.
我正在使用春季靴子,運(yùn)動(dòng)衫,mongo db,swagger,spring boot security和jwt.
我已經(jīng)編寫了模型,請求數(shù)據(jù)庫的存儲(chǔ)庫.現(xiàn)在我已經(jīng)集成了Security和jwt令牌.
現(xiàn)在我需要離散用戶的角色,因?yàn)橛脩魺o法調(diào)用需要管理員權(quán)限的路由.
我有一個(gè)登錄路線,它返回一個(gè)令牌.這是我的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,當(dāng)用戶登錄時(shí)返回令牌
...
@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;
}
...
我想在我的端點(diǎn)類上插入這個(gè)方法
@PreAuthorize("hasRole('ROLE_ADMIN')")
這是端點(diǎn)的一部分
....
@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();
}
....
我如何建立一種機(jī)制來為用戶分配角色以及如何在令牌中傳遞角色并在路由中離散用戶的角色?
總結(jié)
以上是生活随笔為你收集整理的java–jwt_java – Spring引导如何使用jwt管理用户角色的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: NLS_LANG详解
- 下一篇: 电脑内存条的作用是什么