當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。