本文整理匯總了Java中javax.ws.rs.NotAuthorizedException類的典型用法代碼示例。如果您正苦於以下問題:Java NotAuthorizedException類的具體用法?Java NotAuthorizedException怎麽用?Java NotAuthorizedException使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
NotAuthorizedException類屬於javax.ws.rs包,在下文中一共展示了NotAuthorizedException類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: toApplicationUser
import javax.ws.rs.NotAuthorizedException; //導入依賴的package包/類
/**
* Check the authentication, then create or get the application user
* matching to the given account.
*
* @param repository
* Repository used to authenticate the user, and also to use to
* fetch the user attributes.
* @param authentication
* The current authentication.
* @return A not <code>null</code> application user.
*/
protected String toApplicationUser(final UserLdapRepository repository, final Authentication authentication) {
// Check the authentication
final UserOrg account = repository.findOneBy(repository.getAuthenticateProperty(authentication.getName()),
authentication.getName());
// Check at least one mail is present
if (account.getMails().isEmpty()) {
// Mails are required to proceed the authentication
log.info("Account '{} [{} {}]' has no mail", account.getId(), account.getFirstName(),
account.getLastName());
throw new NotAuthorizedException("ambiguous-account-no-mail");
}
// Find the right application user
return toApplicationUser(account);
}
示例2: testLoginFailed
import javax.ws.rs.NotAuthorizedException; //導入依賴的package包/類
@Test
public void testLoginFailed() {
final User user = createUser();
final UserModel userModel = new UserModel();
userModel.setUsername(user.getUsername());
userModel.setPassword("wrongPassword");
final HttpServletRequest request = new TestHttpServletRequest();
try {
service.setRequest(request);
service.login(userModel, con);
fail();
}
catch(final NotAuthorizedException e) {
// should happen
}
final User userToCheck = (User) request.getSession().getAttribute(LoggedInUserService.SESSIONATTR_LOGGEDIN);
assertNull(userToCheck);
}
示例3: testLoginUnknownUser
import javax.ws.rs.NotAuthorizedException; //導入依賴的package包/類
@Test
public void testLoginUnknownUser() {
createUser();
final UserModel userModel = new UserModel();
userModel.setUsername("usssserrrr");
userModel.setPassword(PASSWORD);
final HttpServletRequest request = new TestHttpServletRequest();
try {
service.setRequest(request);
service.login(userModel, con);
fail();
}
catch(final NotAuthorizedException e) {
// should happen
}
final User userToCheck = (User) request.getSession().getAttribute(LoggedInUserService.SESSIONATTR_LOGGEDIN);
assertNull(userToCheck);
}
示例4: testFilterAppend
import javax.ws.rs.NotAuthorizedException; //導入依賴的package包/類
@Test
public void testFilterAppend() throws Exception {
final Set<IRI> modes = new HashSet<>();
when(mockContext.getMethod()).thenReturn("POST");
when(mockAccessControlService.getAccessModes(any(IRI.class), any(Session.class))).thenReturn(modes);
final WebAcFilter filter = new WebAcFilter(emptyList(), mockAccessControlService);
modes.add(ACL.Append);
filter.filter(mockContext);
modes.add(ACL.Write);
filter.filter(mockContext);
modes.remove(ACL.Append);
filter.filter(mockContext);
modes.clear();
assertThrows(NotAuthorizedException.class, () -> filter.filter(mockContext));
}
示例5: filter
import javax.ws.rs.NotAuthorizedException; //導入依賴的package包/類
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
// Get the HTTP Authorization header from the request
String authorizationHeader =
requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);
// Check if the HTTP Authorization header is present and formatted correctly
if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
throw new NotAuthorizedException("Authorization header must be provided");
}
// Extract the token from the HTTP Authorization header
String token = authorizationHeader.substring("Bearer".length()).trim();
// Validate the token
boolean isValid = validateToken(token);
if (!isValid) requestContext.abortWith(
Response.status(Response.Status.UNAUTHORIZED).build());
}
示例6: filter
import javax.ws.rs.NotAuthorizedException; //導入依賴的package包/類
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
String authorizationHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);
log.info("authorizationHeader : " + authorizationHeader);
// Check if the HTTP Authorization header is present and formatted correctly
if (authorizationHeader == null || !authorizationHeader.startsWith("token ")) {
log.error("invalid authorizationHeader : " + authorizationHeader);
throw new NotAuthorizedException("Authorization header must be provided");
}
// Extract the token from the HTTP Authorization header
String token = authorizationHeader.substring("Bearer".length()).trim();
try {
// Validate the token
Key key = keyGenerator.generateKey();
Jwts.parser().setSigningKey(key).parseClaimsJws(token);
log.info("valid token : " + token);
} catch (Exception ex) {
log.error("invalid token : " + token);
log.error("Exception occurred while validate the token : " + ex);
requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
}
}
示例7: filter
import javax.ws.rs.NotAuthorizedException; //導入依賴的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);
}
}
示例8: sendRequest
import javax.ws.rs.NotAuthorizedException; //導入依賴的package包/類
public <T> T sendRequest (Function <WebClient, T> request) {
int retries = 0;
do {
try {
WebClient webClientCopy = WebClient.fromClient(webClient);
T response = request.apply(webClientCopy);
webClientCopy.close();
return response;
}
catch (NotAuthorizedException e) {
if (retries < 5) {
retries ++;
authClient.refreshAuthenticationContext();
}
else throw e;
}
}
while (retries < 5);
return null;
}
示例9: filter
import javax.ws.rs.NotAuthorizedException; //導入依賴的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));
}
示例10: preprocessRequest
import javax.ws.rs.NotAuthorizedException; //導入依賴的package包/類
@Override
public UserDetails preprocessRequest(String name, ExecutionRequest executionRequest, HttpServletRequest request) {
StopWatch watch = new StopWatch();
UserDetails userDetails = gitUserHelper.createUserDetails(request);
// TODO this isn't really required if there's a secret associated with the BuildConfig source
if (Strings.isNullOrEmpty(userDetails.getUser()) || Strings.isNullOrEmpty(userDetails.getUser())) {
throw new NotAuthorizedException("You must authenticate to be able to perform this command");
}
if (Objects.equals(name, Constants.PROJECT_NEW_COMMAND)) {
List<Map<String, Object>> inputList = executionRequest.getInputList();
if (inputList != null) {
Map<String, Object> page1 = inputList.get(0);
if (page1 != null) {
if (page1.containsKey(Constants.TARGET_LOCATION_PROPERTY)) {
page1.put(Constants.TARGET_LOCATION_PROPERTY, projectFileSystem.getUserProjectFolderLocation(userDetails));
}
}
}
}
LOG.info("preprocessRequest took " + watch.taken());
return userDetails;
}
示例11: tokenReattempt
import javax.ws.rs.NotAuthorizedException; //導入依賴的package包/類
@Test
public void tokenReattempt() {
// prepare SUT
final SecretProvider sp = SecretProvider.fallback(UUID.randomUUID().toString(), new char[0]);
final String username = sp.getUsername();
final char[] password = sp.getPassword();
final ZonkyApiToken token = new ZonkyApiToken(UUID.randomUUID().toString(), UUID.randomUUID().toString(), 1);
final OAuth oauth = Mockito.mock(OAuth.class);
Mockito.when(oauth.login(ArgumentMatchers.eq(username), ArgumentMatchers.eq(password))).thenReturn(token);
final ZonkyApiToken newToken = new ZonkyApiToken(UUID.randomUUID().toString(), UUID.randomUUID().toString(),
299);
Mockito.when(oauth.refresh(ArgumentMatchers.eq(token))).thenReturn(newToken);
final Zonky z = Mockito.mock(Zonky.class);
final ApiProvider api = mockApiProvider(oauth, z);
final Duration never = Duration.ofDays(1000); // let's not auto-refresh during the test
final TokenBasedAccess a = (TokenBasedAccess) Authenticated.tokenBased(api, sp, never);
// call SUT
final Consumer<Zonky> f = Mockito.mock(Consumer.class);
Mockito.doThrow(NotAuthorizedException.class).when(f).accept(z);
Assertions.assertThatThrownBy(() -> a.run(f)).isInstanceOf(IllegalStateException.class);
Mockito.verify(oauth).refresh(ArgumentMatchers.any());
Mockito.verify(f, Mockito.times(3)).accept(z); // three attempts to execute
}
示例12: getVotes
import javax.ws.rs.NotAuthorizedException; //導入依賴的package包/類
/**
* Retrieves votes that have been casted on all the posts belonging to the topic
* @param authorization
* @param topicId The topic id
* @param memberId If specified, returns only votes casted by the member with this id
* @return
* @throws NotAuthorizedException
* @throws ServerErrorException
*/
public Response getVotes(
String authorization,
Long topicId,
Integer memberId)
throws NotAuthorizedException, ServerErrorException
{
try {
// Authorize. May throw NotAuthorizedException
authorize(authorization);
// Get the DAO implementation
VoteDAO voteDAO = DAOProvider.getDAO(VoteDAO.class);
// Get the votes
List<VoteDTO> voteDTOs = voteDAO.findByTopicAndMember(topicId, memberId);
// Convert the result
List<Vote> votes = new VoteConverter().convert(voteDTOs);
// Return the result
return Response.status(200).entity(votes).build();
}
catch (Exception e) {
Response response = ResponseUtils.serverError(e);
throw new ServerErrorException(response);
}
}
示例13: filter
import javax.ws.rs.NotAuthorizedException; //導入依賴的package包/類
@Override
public void filter(ContainerRequestContext containerRequestContext) throws IOException {
String authorizationHeader = containerRequestContext.getHeaderString(HttpHeaders.AUTHORIZATION);
if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
throw new NotAuthorizedException("Authorization header must be provided");
}
String token = TokenParser.parse(authorizationHeader);
try{
securityContextService.validateToken(token);
} catch (Exception e){
containerRequestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
}
}
示例14: testCreateException
import javax.ws.rs.NotAuthorizedException; //導入依賴的package包/類
@Test
public void testCreateException() {
assertExceptionType(Response.Status.INTERNAL_SERVER_ERROR, InternalServerErrorException.class);
assertExceptionType(Response.Status.NOT_FOUND, NotFoundException.class);
assertExceptionType(Response.Status.FORBIDDEN, ForbiddenException.class);
assertExceptionType(Response.Status.BAD_REQUEST, BadRequestException.class);
assertExceptionType(Response.Status.METHOD_NOT_ALLOWED, NotAllowedException.class);
assertExceptionType(Response.Status.UNAUTHORIZED, NotAuthorizedException.class);
assertExceptionType(Response.Status.NOT_ACCEPTABLE, NotAcceptableException.class);
assertExceptionType(Response.Status.UNSUPPORTED_MEDIA_TYPE, NotSupportedException.class);
assertExceptionType(Response.Status.SERVICE_UNAVAILABLE, ServiceUnavailableException.class);
assertExceptionType(Response.Status.TEMPORARY_REDIRECT, RedirectionException.class);
assertExceptionType(Response.Status.LENGTH_REQUIRED, ClientErrorException.class);
assertExceptionType(Response.Status.BAD_GATEWAY, ServerErrorException.class);
assertExceptionType(Response.Status.NO_CONTENT, WebApplicationException.class);
}
示例15: listNotificationChannels
import javax.ws.rs.NotAuthorizedException; //導入依賴的package包/類
@Override
public CronofyResponse<ListNotificationChannelsResponse> listNotificationChannels(final ListNotificationChannelsRequest request) {
assertCronofyRequest(request);
try {
return getClient()
.target(BASE_PATH)
.path(API_VERSION)
.path(CHANNELS_PATH)
.request(MediaType.APPLICATION_JSON_TYPE)
.header(AUTH_HEADER_KEY, getAccessTokenFromRequest(request))
.get(new GenericType<CronofyResponse<ListNotificationChannelsResponse>>() {
});
} catch (final NotAuthorizedException ignore) {
LOGGER.warn(NOT_AUTHORIZED_EXCEPTION_MSG, ignore, request);
return new CronofyResponse<>(ErrorTypeModel.NOT_AUTHORIZED);
}
}