2

我有 Spring Boot 应用程序,我试图将 Apache shiro 与它集成。作为第一次迭代,我正在验证和授权 JWT 方式,没有任何会话。

按照我的架构方式,每个 REST 请求都必须包含需要验证的 JWT 标头。我正在使用 shiro 过滤器进行操作。验证后,过滤器设置一个上下文,任何 REST 控制器方法都可以获取并对其进行操作。

我希望社区的意见,以确保我的配置是正确的。此外,我面临着某些问题(至少是 IMO)。因此,如果有人可以对正确的处理方式有所了解,将不胜感激。

以下是一些代码片段,展示了我的配置和领域设计。

片段 1:Shiro 配置

private AuthenticationService authenticationService;
/**
 * FilterRegistrationBean
 * @return
 */
@Bean
public FilterRegistrationBean filterRegistrationBean() {
    FilterRegistrationBean filterRegistration = new FilterRegistrationBean();
    filterRegistration.setFilter(new DelegatingFilterProxy("shiroFilter"));
    filterRegistration.setEnabled(true);
    filterRegistration.setDispatcherTypes(DispatcherType.REQUEST);
    filterRegistration.setOrder(1);
    return filterRegistration;
}
@Bean(name = "securityManager")
public DefaultWebSecurityManager securityManager() {
    DefaultWebSecurityManager dwsm = new DefaultWebSecurityManager();
    dwsm.setRealm(authenticationService());
    final DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
    // disable session cookie
    sessionManager.setSessionIdCookieEnabled(false);
    dwsm.setSessionManager(sessionManager);
    return dwsm;
}

/**
 * @see org.apache.shiro.spring.web.ShiroFilterFactoryBean
 * @return
 */
@Bean(name="shiroFilter")
public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("securityManager") SecurityManager securityManager, JWTTimeoutProperties jwtTimeoutProperties, TokenUtil tokenUtil) {
    ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
    bean.setSecurityManager(securityManager);

    //TODO: Create a controller to replicate unauthenticated request handler
    bean.setUnauthorizedUrl("/unauthor");

    Map<String, Filter> filters = new HashMap<>();
    filters.put("perms", new AuthenticationTokenFilter(jwtTimeoutProperties, tokenUtil));
    filters.put("anon", new AnonymousFilter());
    bean.setFilters(filters);

    LinkedHashMap<String, String> chains = new LinkedHashMap<>();
    chains.put("/", "anon");
    chains.put("/favicon.ico", "anon");
    chains.put("/index.html", "anon");
    chains.put("/**/swagger-resources", "anon");
    chains.put("/api/**", "perms");

    bean.setFilterChainDefinitionMap(chains);
    return bean;
}
@Bean
@DependsOn(value="lifecycleBeanPostProcessor")
public AuthenticationService authenticationService() {
    if (authenticationService==null){
        authenticationService = new AuthenticationService();
    }

    return  authenticationService;
}


@Bean
@DependsOn(value="lifecycleBeanPostProcessor")
public Authorizer authorizer() {
    return authenticationService();
}


@Bean
@DependsOn("lifecycleBeanPostProcessor")
public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
    DefaultAdvisorAutoProxyCreator proxyCreator = new DefaultAdvisorAutoProxyCreator();
    proxyCreator.setProxyTargetClass(true);
    return proxyCreator;
}

片段 2:身份验证过滤器

public class AuthenticationTokenFilter extends PermissionsAuthorizationFilter {
@Override
public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws IOException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    String authorizationHeader = httpRequest.getHeader(TOKEN_HEADER);
    String authToken;

    String alreadyFilteredAttributeName = getAlreadyFilteredAttributeName();
    httpRequest.setAttribute(alreadyFilteredAttributeName, true);

    AuthenticationService.ensureUserIsLoggedOut(); // To not end up getting following error.

    if (authorizationHeader != null && !authorizationHeader.isEmpty()) {

        if (authorizationHeader.startsWith(BEARER_TOKEN_START_WITH)) {
            authToken = authorizationHeader.substring(BEARER_TOKEN_START_INDEX);
        } else if (authorizationHeader.startsWith(BASIC_TOKEN_START_WITH)) {
            String caseId = UUID.randomUUID().toString();
            log.warn("{} Basic authentication is not supported but a Basic authorization header was passed in", caseId);
            return false;
        } else {
            // if its neither bearer nor basic, default it to bearer.
            authToken = authorizationHeader;
        }
        try {
            if(tokenUtil.validateTokenAgainstSignature(authToken, jwtTimeoutProperties.getSecret())) {
                Map<String, Object> outerClaimsFromToken = tokenUtil.getOuterClaimsFromToken(authToken, jwtTimeoutProperties.getSecret());

                JWTAuthenticationToken jwtAuthenticationToken = new JWTAuthenticationToken(outerClaimsFromToken.get(TokenUtil.CLAIM_KEY_USERID),
                                                (String) outerClaimsFromToken.get(TokenUtil.CLAIM_KEY_INNER_TOKEN));
                SecurityUtils.getSubject().login(jwtAuthenticationToken);

        } catch (JwtException | AuthenticationException ex) {
            log.info("JWT validation failed.", ex);
        }
    }
    return false;
}

片段 3:TokenRestController

public Response getToken() {

    AuthenticationService.ensureUserIsLoggedOut(); // To not end up getting following error.
                                                        // org.apache.shiro.session.UnknownSessionException: There is no session with id

        // TODO: In case of logging in with the organization, create own token class implementing HostAuthenticationToken class.
        IAMLoginToken loginToken = new IAMLoginToken(authenticationRequestDTO.getUsername(), authenticationRequestDTO.getPassword());
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(loginToken);
        } catch (AuthenticationException e) {
            log.debug("Unable to login", e);
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(null);
        }

        AuthenticatingUser user = (AuthenticatingUser) subject.getPrincipal();

            String authToken = authenticationService.generateToken(user);
            return ResponseEntity.status(HttpStatus.OK).body(new AuthenticationResponseDTO(authToken));
    });

片段 4:授权领域

@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    if (token instanceof IAMLoginToken) {
        IAMLoginToken usernamePasswordToken = (IAMLoginToken) token;

        UserBO user = identityManagerRepository.getUserByUsername(usernamePasswordToken.getUsername(), true);

        if (user != null && user.getSecret() != null && !user.getSecret().isEmpty()) {
            if(passwordEncoder.matches(String.valueOf(usernamePasswordToken.getPassword()), user.getPassword())) {
                if (!isActive(user)) {
                    throw new AuthenticationException("User account inactive.");
                }
                return new SimpleAuthenticationInfo(toAuthenticatingUser(user).withSecret(user.getSecret()), usernamePasswordToken.getPassword(), getName());
            }
        }
    } else if (token instanceof JWTAuthenticationToken) {
        JWTAuthenticationToken jwtToken = (JWTAuthenticationToken) token;
        String userId = (String) jwtToken.getUserId();
        String secret = cache.getUserSecretById(userId, false);

        if (secret != null && !secret.isEmpty()) {
            Map<String, Object> tokenClaims = tokenUtil.getClaims(jwtToken.getToken(), secret);
            String orgId = (String) tokenClaims.get(TokenUtil.CLAIM_KEY_ORG);
            String email = (String) tokenClaims.get(TokenUtil.CLAIM_KEY_EMAIL);
            String firstName = (String) tokenClaims.get(TokenUtil.CLAIM_KEY_FIRSTNAME);
            String lastName = (String) tokenClaims.get(TokenUtil.CLAIM_KEY_LASTNAME);
            Set<String> permissions = (Set<String>) tokenClaims.get(TokenUtil.CLAIM_KEY_PERMISSIONS);

            return new SimpleAccount(new AuthenticatingUser(userId, orgId, email, firstName, lastName, permissions), jwtToken.getToken(), getName());
        }
    }

    throw new AuthenticationException("Invalid username/password combination!");
}

@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

    SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
    authorizationInfo.setStringPermissions(((AuthenticatingUser)principals.getPrimaryPrincipal()).getPermissions());
    return authorizationInfo;
}

问题和问题

  • 与此处提到的相同错误。 Shiro 用 DefaultSecurityManager 抱怨“没有 id xxx 的会话” 我基本上希望 Shiro 停止使用和/或验证会话。有没有办法做到这一点?我通过实施与答案中提到的相同的修复来解决它,就是ensureUserIsLoggedOut()这样。

  • 正如您在配置的 ShiroFilterFactoryBean 定义中看到的那样,我正在设置一些过滤器链定义。在那里你可以看到我设置每个以开头的 api 调用都/api将在前面有身份验证过滤器。但问题是我想为它添加一些例外。比如,/api/v0/login就是其中之一。有没有办法做到这一点?

  • 总的来说,我不确定我提出的配置是否合适,因为我发现文档和类似的开源项目示例非常有限。

欢迎任何反馈。

4

2 回答 2

1

I resolved the first issue of unwanted session validation and management by stopping Shiro from using a Subject’s session to store that Subject’s state across requests/invocations/messages for all Subjects.

I just had to apply following configuration to my session manager in my shiro configuration. https://shiro.apache.org/session-management.html#disabling-subject-state-session-storage

于 2017-12-05T19:51:17.313 回答
0

您可能应该将您的令牌过滤器与“perms”过滤器分开。查看 BasicAuth 过滤器或“authc”过滤器。这应该可以帮助您解决所遇到的问题。您基本上使用的是“authz”过滤器(我猜这就是您需要这些解决方法的原因)

于 2017-11-28T15:46:42.087 回答