私は春の起動でRESTfulなAPIを書いています。 私は春のブート、ジャージー、mongoデータベース、swagger、春のブートセキュリティとjwtを使用しています。春の起動jwtでユーザロールを管理する方法
私はDBへのリクエストのためのモデル、リポジトリを書いています。これで、Securityトークンとjwtトークンが統合されました。
ここでは、ユーザーが管理者特権を必要とするルートを呼び出すことができないため、ユーザーの役割を離散化する必要があります。
私はログインのためのルートを持っています、それはトークンを返します。これは私が私のトークンを返すJWTLoginFilterを書か
...
@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);
}
}
私SecurityConfigのコードであるときに、ユーザがログインになります
...
@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();
}
....
私はどのようにユーザーに役割を割り当てるための仕組みを作ることができ、どのように私はトークンで役割を渡し、ユーザーの役割をルーティングする際に離散化することができますか?
権限とロール(「ROLE_」接頭辞付きの権限)を混用しないでください。「hasRole( 'ADMIN')」または「hasAuthority( 'ROLE_ADMIN')」を使用してください。 –