我在Java中配置Shiro。我想用它来保护REST API。我使用基于令牌的身份验证我配置ShiroFilterFactoryBean如下:
@Bean
public ShiroFilterFactoryBean shiroFilterBean() {
ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
HashMap<String, String> definitionMap = Maps.newHashMap();
definitionMap.put("/api/auth", "anon");
definitionMap.put("/api/**", "noSessionCreation, authc");
shiroFilter.setFilterChainDefinitionMap(definitionMap);
HashMap<String, Filter> filters = Maps.newHashMap();
filters.put("authc", new RestTokenAuthenticatingFilter());
shiroFilter.setFilters(filters);
shiroFilter.setSecurityManager(securityManager());
return shiroFilter;
}
然后我有RestController如下:
@RestController
@RequestMapping("/api/auth")
public class AuthController {
@Inject
RestService restService;
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity login(@RequestBody LoginDto loginDto) {
String restToken = // ... create token
return new ResponseEntity<>(restToken, HttpStatus.OK);
}
@RequestMapping("/secure")
@RequiresAuthentication
public String secure() {
Subject subject = SecurityUtils.getSubject();
return "Should be 'true' == " + subject.isAuthenticated() + " ** " + subject.getPrincipal();
}
@RequestMapping("/insecure")
public String insecure() {
return "You dont have to be authenticated";
}
}
如何强制执行此行
filters.put("authc", new RestTokenAuthenticatingFilter());
仅适用于来自Shiro的使用@RequiresAuthentication(和其他人)注释的方法?
为什么我要这样做?例如,我希望有类似的东西
GET /api/cars
允许所有用户POST /api/cars
仅允许经过身份验证的用户当我在ShiroFilterFactoryBean中定义过滤器时,我无法实现这一点。