将Shiro过滤器与Spring中的Java Annotations结合使用

时间:2014-12-30 11:10:40

标签: java spring spring-mvc shiro

我在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中定义过滤器时,我无法实现这一点。

0 个答案:

没有答案