我从前端收到一个JWT令牌,我应该解析并提取角色,如果角色是admin,则应授予对特定URL的访问权限。我尝试了不同的方法,但到目前为止没有任何结果。 以下是我的代码-
WebSecurityConfig.java
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
TestService testService;
@Autowired
private JWTAuthenticationEntryPoint unauthorizedHandler;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable().exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests()
.antMatchers("/trial/import").hasRole("ADMIN").anyRequest().authenticated().and().formLogin();
}
AppController.java
@RestController
@CrossOrigin(origins = "*", maxAge = 3600)
@RequestMapping("/trial")
public class AppController {
@Autowired
private ServiceController service;
@PostMapping("/token")
public boolean getAccess(@RequestHeader(name = "Authorization") String token) throws Exception {
boolean accessAllowed = service.getService().decodeToken(token);
return accessAllowed;
}
@PreAuthorize("hasAuthority('ADMIN')")
@RolesAllowed("ADMIN")
@PostMapping("/import")
public boolean runCSVImport(@RequestBody String file){
//doSomethingHere
}
ServiceController.java
@Service
@RestController
public class ServiceController{
@Autowired
public TestService testService;
....
public TestService getService(){
return testService;
}
}
TestService.java
@Component
public class TestService{
....
public boolean decodeToken(String token) throws Exception {
try {
DecodedJWT jwt = JWT.decode(token);
Claim role = jwt.getClaim("Role");
// String payLoad = jwt.getPayload();
boolean isAdmin = rollen.asString().contains("admin");
return isAdmin;
} catch (JWTDecodeException exception) {
throw new Exception("Probleme mit JWT Parsing");
}
}
}
现在,我被告知不要在数据库的表中维护用户详细信息或角色,因为这是必需的。因此,我对@PreAuthorize
和@RolesAllowed
的使用似乎不合理。还有其他方法,我可以通过GetMapping接收令牌,解析令牌并提取角色并允许访问/import
(如果是Admin)?
热诚欢迎任何帮助。