当前位置: 首页>>代码示例>>Java>>正文


Java ContainerRequestContext.setSecurityContext方法代码示例

本文整理汇总了Java中javax.ws.rs.container.ContainerRequestContext.setSecurityContext方法的典型用法代码示例。如果您正苦于以下问题:Java ContainerRequestContext.setSecurityContext方法的具体用法?Java ContainerRequestContext.setSecurityContext怎么用?Java ContainerRequestContext.setSecurityContext使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在javax.ws.rs.container.ContainerRequestContext的用法示例。


在下文中一共展示了ContainerRequestContext.setSecurityContext方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: filter

import javax.ws.rs.container.ContainerRequestContext; //导入方法依赖的package包/类
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
    String usertokenId = requestContext.getHeaderString(Constants.USERTOKENID_HEADER);

    if (Strings.isNullOrEmpty(usertokenId)) {
        return;
    }

    UserToken userToken;
    try {
        userToken = tokenServiceClient.getUserTokenById(usertokenId);
    } catch (TokenServiceClientException e) {
        throw new NotAuthorizedException("UsertokenId: '" + usertokenId + "' not valid", e);
    }

    UibBrukerPrincipal brukerPrincipal = UibBrukerPrincipal.ofUserToken(userToken);
    ImmutableSet<String> tilganger = extractRolesAllowed(userToken, brukerPrincipal.uibBruker);

    requestContext.setSecurityContext(new AutentiseringsContext(brukerPrincipal, tilganger));

    if (authenticatedHandler != null) {
        authenticatedHandler.handle(requestContext);
    }
}
 
开发者ID:code-obos,项目名称:servicebuilder,代码行数:25,代码来源:UserTokenFilter.java

示例2: filter

import javax.ws.rs.container.ContainerRequestContext; //导入方法依赖的package包/类
@Override
public void filter(ContainerRequestContext containerRequest) throws WebApplicationException {
    String authorizationHeader = containerRequest.getHeaderString(HttpHeaders.AUTHORIZATION);
    String scheme = containerRequest.getUriInfo().getRequestUri().getScheme();
    logger.debug("authorizationHeader : " + authorizationHeader);

    if (authorizationHeader != null) {
        String[] loginPassword = BasicAuth.decode(authorizationHeader);
        checkLoginPassword(loginPassword);
        String login = loginPassword[0];
        String password = loginPassword[1];
        User user = dao.findByAlias(login);
        if (user.isGoodPassword(password)) {
            logger.debug("good password !");
            containerRequest.setSecurityContext(new AppSecurityContext(user, scheme));
        } else {
            logger.debug("wrong password !");
            containerRequest.setSecurityContext(new AppSecurityContext(User.getAnonymousUser(), scheme));
        }
    } else {
        containerRequest.setSecurityContext(new AppSecurityContext(User.getAnonymousUser(), scheme));
    }
}
 
开发者ID:maugern,项目名称:jersey-skeleton,代码行数:24,代码来源:AuthFilter.java

示例3: filter

import javax.ws.rs.container.ContainerRequestContext; //导入方法依赖的package包/类
/**
 * This method will catch any request and will analyse the header value of "Authorization" key.
 * If the key is valid, then it will extract the permission user from the token (see {@link JWTService#validateToken(String)}  validateToken()})
 * and put in a Jwt Security Context. see : {@link JWTSecurityContext}
 *
 * @param requestContext : the request context
 * @throws IOException            if an I/O exception occurs.
 * @throws NotAuthorizedException : if the request doesn't contain the token in the header,
 *                                then the user is not authenticated and not allowed to access to the application
 */
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {

    String token = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);

    if (token == null) {
        throw new NotAuthorizedException("user is not authenticated");
    }

    if (token.startsWith(AuthorizationRequestFilter.HEADER_PREFIX)) {
        // Remove header prefix
        token = token.substring(AuthorizationRequestFilter.HEADER_PREFIX.length());
    }

    // if the token is valid, jwt returns an object Principal which contains the list of the user permissions
    JWTPrincipal principal = this.jwtService.validateToken(token);

    String scheme = requestContext.getUriInfo().getRequestUri().getScheme();
    requestContext.setSecurityContext(new JWTSecurityContext(principal, scheme, requestContext.getUriInfo().getPathParameters(), snippetService));
}
 
开发者ID:Crunchy-Torch,项目名称:coddy,代码行数:31,代码来源:AuthorizationRequestFilter.java

示例4: filter

import javax.ws.rs.container.ContainerRequestContext; //导入方法依赖的package包/类
@Override
public void filter(final ContainerRequestContext requestContext) throws IOException {
    requestContext.setSecurityContext(new SecurityContext() {
        @Override
        public Principal getUserPrincipal() {
            return new Principal() {
                @Override
                public String getName() {
                    return principal;
                }
            };
        }

        @Override
        public boolean isSecure() {
            return false;
        }

        @Override
        public boolean isUserInRole(final String role) {
            return userRole.equals(role);
        }

        @Override
        public String getAuthenticationScheme() {
            return "BASIC";
        }
    });
}
 
开发者ID:trellis-ldp,项目名称:trellis,代码行数:30,代码来源:TestAuthenticationFilter.java

示例5: filter

import javax.ws.rs.container.ContainerRequestContext; //导入方法依赖的package包/类
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {

    final Charset CHARACTER_SET = Charset.forName("utf-8");

    String authHeader = requestContext.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
    if (authHeader != null && authHeader.startsWith("Basic")) {
        String decoded =
                new String(Base64.getDecoder().decode(authHeader.substring(6).getBytes()), CHARACTER_SET);
        final String[] split = decoded.split(":");
        final String username = split[0];
        final String password = split[1];
        // FIXME: 这里要验证登陆并在请求头或者参数中加入token
        boolean verify = false;
        if (!verify) {
            requestContext.abortWith(Response.status(401).header(HttpHeaders.WWW_AUTHENTICATE, "Basic")
                .build());
        }
        else {
            requestContext.setSecurityContext(new SecurityContext() {
                @Override
                public Principal getUserPrincipal() {
                    return new Principal() {
                        @Override
                        public String getName() {
                            return username;
                        }
                    };
                }


                @Override
                public boolean isUserInRole(String role) {
                    return true;
                }


                @Override
                public boolean isSecure() {
                    return false;
                }


                @Override
                public String getAuthenticationScheme() {
                    return "BASIC";
                }
            });
        }
    }

}
 
开发者ID:jiumao-org,项目名称:wechat-mall,代码行数:53,代码来源:BasicAuthFilter.java

示例6: filter

import javax.ws.rs.container.ContainerRequestContext; //导入方法依赖的package包/类
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {

	// Get realm
	Realm realm = ResourceUtils.lookupResource(getClass(), Realm.class, providers)
			.orElseThrow(() -> new IOException(
					"AuthContext setup failed: no Realm available from a ContextResolver or as a Context resource"));

	// replace SecurityContext
	requestContext.setSecurityContext(
			new AuthSecurityContext(realm, HttpUtils.isSecure(requestContext.getUriInfo().getRequestUri())));
}
 
开发者ID:holon-platform,项目名称:holon-jaxrs,代码行数:13,代码来源:AuthContextFilter.java

示例7: filter

import javax.ws.rs.container.ContainerRequestContext; //导入方法依赖的package包/类
@Override
public void filter(ContainerRequestContext containerRequestContext) throws IOException {
    final String authToken = containerRequestContext.getHeaders().getFirst("Authorization");

    if (StringUtils.isBlank(authToken)) {
        LOGGER.warn("Error decoding credentials");
        throw new WebApplicationException(unauthorizedHandler.buildResponse(prefix, realm));
    }

    try {
        final Optional<P> principal = authenticator.authenticate(authToken);
        if (principal.isPresent()) {
            containerRequestContext.setSecurityContext(new SecurityContext() {
                @Override
                public Principal getUserPrincipal() {
                    return principal.get();
                }

                @Override
                public boolean isUserInRole(String role) {
                    return authorizer.authorize(principal.get(), role);
                }

                @Override
                public boolean isSecure() {
                    return containerRequestContext.getSecurityContext().isSecure();
                }

                @Override
                public String getAuthenticationScheme() {
                    return "TOKEN";
                }
            });
        }
    } catch (AuthenticationException e) {
        LOGGER.warn("Error authenticating credentials", e);
        throw new WebApplicationException(unauthorizedHandler.buildResponse(prefix, realm));
    }
}
 
开发者ID:tosinoni,项目名称:SECP,代码行数:40,代码来源:TokenAuthFilter.java

示例8: handleTokenBasedAuthentication

import javax.ws.rs.container.ContainerRequestContext; //导入方法依赖的package包/类
private void handleTokenBasedAuthentication(String authenticationToken, ContainerRequestContext requestContext) {

        AuthenticationTokenDetails authenticationTokenDetails = authenticationTokenService.parseToken(authenticationToken);
        User user = userService.findByUsernameOrEmail(authenticationTokenDetails.getUsername());
        AuthenticatedUserDetails authenticatedUserDetails = new AuthenticatedUserDetails(user.getUsername(), user.getAuthorities());

        boolean isSecure = requestContext.getSecurityContext().isSecure();
        SecurityContext securityContext = new TokenBasedSecurityContext(authenticatedUserDetails, authenticationTokenDetails, isSecure);
        requestContext.setSecurityContext(securityContext);
    }
 
开发者ID:cassiomolin,项目名称:jersey-jwt,代码行数:11,代码来源:AuthenticationFilter.java

示例9: filter

import javax.ws.rs.container.ContainerRequestContext; //导入方法依赖的package包/类
@Override
public void filter(final ContainerRequestContext ctx) throws IOException {

    if (nonNull(ctx.getHeaders().getFirst(HttpHeaders.AUTHORIZATION))) {
        throw new WebApplicationException(unauthorizedHandler.buildResponse(prefix, realm));
    }

    final SecurityContext securityContext = ctx.getSecurityContext();
    final boolean secure = securityContext != null && securityContext.isSecure();

    ctx.setSecurityContext(new SecurityContext() {
        @Override
        public Principal getUserPrincipal() {
            return new PrincipalImpl(Trellis.AnonymousAgent.getIRIString());
        }

        @Override
        public boolean isUserInRole(final String role) {
            return false;
        }

        @Override
        public boolean isSecure() {
            return secure;
        }

        @Override
        public String getAuthenticationScheme() {
            return "NONE";
        }
    });
}
 
开发者ID:trellis-ldp,项目名称:trellis-rosid,代码行数:33,代码来源:AnonymousAuthFilter.java

示例10: filter

import javax.ws.rs.container.ContainerRequestContext; //导入方法依赖的package包/类
/**
 * Gets the token from the request and verifies it with the authentication service.
 * <p>
 * If there's no token, of if verification fails, then this throws an exception to indicate the request has
 * failed authentication.
 */
@Override
public void filter(final ContainerRequestContext requestContext) throws IOException {
    final Optional<String> optionalToken = getTokenFromHeader(requestContext.getHeaders());

    if (!optionalToken.isPresent()) {
        throw new WebApplicationException(unauthorizedHandler.buildResponse(prefix, realm));
    }

    final Optional<P> optionalUser;
    try {
        optionalUser = authenticator.authenticate(optionalToken.get());
    } catch (AuthenticationException e) {
        LOGGER.info("Authentication process failed. Credentials not necessarily invalid.");
        throw new WebApplicationException(unauthorizedHandler.buildResponse(prefix, realm));
    }

    if(optionalUser.isPresent()) {
        // We need to set up the security context so that our endpoints have a User to work with.
        requestContext.setSecurityContext(new SecurityContext() {
            @Override
            public Principal getUserPrincipal() {
                return optionalUser.get();
            }

            @Override
            public boolean isUserInRole(String role) {
                return true;
            }

            @Override
            public boolean isSecure() {
                return requestContext.getSecurityContext().isSecure();
            }

            @Override
            public String getAuthenticationScheme() {
                return "Bearer";
            }
        });
    }
    else {
        throw new WebApplicationException(Response.Status.UNAUTHORIZED);
    }
}
 
开发者ID:gchq,项目名称:stroom-stats,代码行数:51,代码来源:JwtVerificationFilter.java

示例11: filter

import javax.ws.rs.container.ContainerRequestContext; //导入方法依赖的package包/类
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
    // 检查是否是登录注册接口
    String relationPath = ((ContainerRequest) requestContext).getPath(false);
    if (relationPath.startsWith("account/login")
            || relationPath.startsWith("account/register")) {
        // 直接走正常逻辑,不做拦截
        return;
    }


    // 从Headers中去找到第一个token节点
    String token = requestContext.getHeaders().getFirst("token");
    if (!Strings.isNullOrEmpty(token)) {

        // 查询自己的信息
        final User self = UserFactory.findByToken(token);
        if (self != null) {
            // 给当前请求添加一个上下文
            requestContext.setSecurityContext(new SecurityContext() {
                // 主体部分
                @Override
                public Principal getUserPrincipal() {
                    // User 实现 Principal接口
                    return self;
                }

                @Override
                public boolean isUserInRole(String role) {
                    // 可以在这里写入用户的权限,role 是权限名,
                    // 可以管理管理员权限等等
                    return true;
                }

                @Override
                public boolean isSecure() {
                    // 默认false即可,HTTPS
                    return false;
                }

                @Override
                public String getAuthenticationScheme() {
                    // 不用理会
                    return null;
                }
            });
            // 写入上下文后就返回
            return;
        }
    }

    // 直接返回一个账户需要登录的Model
    ResponseModel model = ResponseModel.buildAccountError();
    // 构建一个返回
    Response response = Response.status(Response.Status.OK)
            .entity(model)
            .build();
    // 拦截,停止一个请求的继续下发,调用该方法后之间返回请求
    // 不会走到Service中去
    requestContext.abortWith(response);

}
 
开发者ID:FZZFVII,项目名称:pipe,代码行数:63,代码来源:AuthRequestFilter.java

示例12: filter

import javax.ws.rs.container.ContainerRequestContext; //导入方法依赖的package包/类
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {

    //Get request headers
    final Map<String, Cookie> cookies = requestContext.getCookies();

    //Fetch authorization header
    final Cookie authorization = cookies.get(AUTHORIZATION_PROPERTY);

    LOG.trace("URI : {}", requestContext.getUriInfo().getPath());

    //If no authorization information present; block access
    if( !(authorization == null) && ! requestContext.getUriInfo().getPath().equalsIgnoreCase(AuthenticateResource.PATH))
    {

        //Get encoded username and password
        final String bearerCookie = authorization.getValue().replaceFirst(AUTHENTICATION_SCHEME + " ", "");

        //Decode username and password
        byte[] bearer = Base64.decode(bearerCookie.getBytes());

        User user = UsersDao.getByBearer(bearer).orElseThrow(() -> new WebApplicationException(Response.Status.UNAUTHORIZED));

        user.setRoles(RolesDao.getUserRoles(user));

        LOG.trace("User accessing resource : {}", user);

        requestContext.setSecurityContext(new ApiSecurityContext(user));
    }


}
 
开发者ID:javathought,项目名称:devoxx-2017,代码行数:33,代码来源:SecurityFilter.java


注:本文中的javax.ws.rs.container.ContainerRequestContext.setSecurityContext方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。