Principal id to principal object of request context

2018/10/28 posted in  Authn&Authz

https://github.com/zhangkaitao/shiro-example/tree/master/shiro-example-chapter23-server

https://github.com/zhangkaitao/shiro-example/blob/master/shiro-example-chapter23-server/src/sql/shiro-schema.sql

https://github.com/zhangkaitao/shiro-example/blob/master/shiro-example-chapter23-server/src/sql/shiro-data.sql

https://github.com/zhangkaitao/shiro-example/blob/master/shiro-example-chapter23-server/src/main/resources/spring-config-shiro.xml

public class SysUserFilter extends PathMatchingFilter {
    @Autowired
    private UserService userService;
    @Override
    protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        String username = (String)SecurityUtils.getSubject().getPrincipal();
        request.setAttribute(Constants.CURRENT_USER, userService.findByUsername(username));
        return true;
    }
}
@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CurrentUser {
    String value() default Constants.CURRENT_USER;
}
public class CurrentUserMethodArgumentResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(CurrentUser.class);
    }
    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        CurrentUser currentUserAnnotation = parameter.getParameterAnnotation(CurrentUser.class);
        return webRequest.getAttribute(currentUserAnnotation.value(), NativeWebRequest.SCOPE_REQUEST);
    }
}
@Controller
public class IndexController {
    @Autowired
    private ResourceService resourceService;
    @Autowired
    private AuthorizationService authorizationService;
    @RequestMapping("/")
    public String index(@CurrentUser User loginUser, Model model) {
        Set<String> permissions = authorizationService.findPermissions(Constants.SERVER_APP_KEY, loginUser.getUsername());
        List<Resource> menus = resourceService.findMenus(permissions);
        model.addAttribute("menus", menus);
        return "index";
    }
}

因此,可以考虑JWT作为Principal的携带者。