Java Code Examples for javax.ws.rs.core.SecurityContext#getUserPrincipal()
The following examples show how to use
javax.ws.rs.core.SecurityContext#getUserPrincipal() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SecurityCatalogResource.java From streamline with Apache License 2.0 | 6 votes |
private User getCurrentUser(SecurityContext securityContext) { Principal principal = securityContext.getUserPrincipal(); if (principal == null) { throw EntityNotFoundException.byMessage("No principal in security context"); } String userName = SecurityUtil.getUserName(principal.getName()); if (userName == null || userName.isEmpty()) { throw EntityNotFoundException.byMessage("Empty user name for principal " + principal); } User user = catalogService.getUser(userName); if (user == null) { throw EntityNotFoundException.byMessage("User '" + userName + "' is not in the user database."); } AuthenticationContext context = new AuthenticationContext(); context.setPrincipal(principal); if (authorizer.hasRole(context, Roles.ROLE_ADMIN)) { user.setAdmin(true); } else { user.setAdmin(false); } return user; }
Example 2
Source File: JWTAuthenticationFilter.java From smallrye-jwt with Apache License 2.0 | 6 votes |
@Override public void filter(ContainerRequestContext requestContext) throws IOException { final SecurityContext securityContext = requestContext.getSecurityContext(); final Principal principal = securityContext.getUserPrincipal(); if (!(principal instanceof JsonWebToken)) { AbstractBearerTokenExtractor extractor = new BearerTokenExtractor(requestContext, authContextInfo); String bearerToken = extractor.getBearerToken(); if (bearerToken != null) { try { JsonWebToken jwtPrincipal = jwtParser.parse(bearerToken); producer.setJsonWebToken(jwtPrincipal); // Install the JWT principal as the caller JWTSecurityContext jwtSecurityContext = new JWTSecurityContext(securityContext, jwtPrincipal); requestContext.setSecurityContext(jwtSecurityContext); JAXRSLogging.log.success(); } catch (Exception e) { JAXRSLogging.log.unableParseJWT(e); } } } }
Example 3
Source File: SubjectExposingResource.java From quarkus with Apache License 2.0 | 6 votes |
@GET @Path("unsecured") @PermitAll public String getSubjectUnsecured(@Context SecurityContext sec) { Principal user = sec.getUserPrincipal(); String name = user != null ? user.getName() : "anonymous"; return name; }
Example 4
Source File: ClientRegistrationService.java From cxf-fediz with Apache License 2.0 | 5 votes |
private void checkSecurityContext() { SecurityContext sc = mc.getSecurityContext(); if (sc == null || sc.getUserPrincipal() == null) { throw ExceptionUtils.toNotAuthorizedException(null, null); } if (userRole != null && !sc.isUserInRole(userRole)) { throw ExceptionUtils.toForbiddenException(null, null); } }
Example 5
Source File: ContainerRequestContextAdapter.java From cf-java-logging-support with Apache License 2.0 | 5 votes |
@Override public String getUser() { SecurityContext sc = ctx.getSecurityContext(); if (sc != null) { Principal p = sc.getUserPrincipal(); if (p != null) { return p.getName(); } } return null; }
Example 6
Source File: FavoriteCityService.java From cloud-weatherapp with Apache License 2.0 | 5 votes |
@GET @Path("/{id}") public FavoriteCity getFavoriteCity(@PathParam(value = "id") String id, @Context SecurityContext ctx) { FavoriteCity retVal = null; String userName = (ctx.getUserPrincipal() != null) ? ctx.getUserPrincipal().getName() : "anonymous"; Map<String,String> props = new HashMap<String,String>(); props.put("tenant.id", userName); EntityManager em = this.getEntityManagerFactory().createEntityManager(props); try { Query query = em.createNamedQuery("FavoriteCityById"); query.setParameter("id", id); retVal = (FavoriteCity) query.getSingleResult(); } catch(Exception ex) { ex.printStackTrace(); } finally { em.close(); } return retVal; }
Example 7
Source File: Sample2Resource.java From jerseyoauth2 with MIT License | 5 votes |
@GET @Path("/{id}") @Produces({ MediaType.APPLICATION_JSON }) public SampleEntity getEntity(@WebParam(name="id") String id, @Context SecurityContext securityContext) { IOAuthPrincipal principal = (IOAuthPrincipal)securityContext.getUserPrincipal(); return new SampleEntity(id, principal.getUser().getName(), principal.getClientId()); }
Example 8
Source File: RolesEndpoint.java From quarkus with Apache License 2.0 | 5 votes |
@GET @Path("/echo") @RolesAllowed("Echoer") public String echoInput(@Context SecurityContext sec, @QueryParam("input") String input) { Principal user = sec.getUserPrincipal(); return input + ", user=" + user.getName(); }
Example 9
Source File: SecurityUtil.java From streamline with Apache License 2.0 | 5 votes |
public static void checkRole(StreamlineAuthorizer authorizer, SecurityContext securityContext, String... roles) { Principal principal = securityContext.getUserPrincipal(); AuthenticationContext authenticationCtx = SecurityUtil.getAuthenticationContext(principal); for (String role : roles) { if (!authorizer.hasRole(authenticationCtx, role)) { throw new WebserviceAuthorizationException("Principal: " + principal + " does not have role: " + role); } } }
Example 10
Source File: TokenSecuredResourceV2.java From quarkus-quickstarts with Apache License 2.0 | 5 votes |
@GET() @Path("roles-allowed") @RolesAllowed({ "Echoer", "Subscriber" }) @Produces(MediaType.TEXT_PLAIN) public String helloRolesAllowed(@Context SecurityContext ctx) { Principal caller = ctx.getUserPrincipal(); String name = caller == null ? "anonymous" : caller.getName(); boolean hasJWT = jwt.getClaimNames() != null; String helloReply = String.format("hello + %s, isSecure: %s, authScheme: %s, hasJWT: %s", name, ctx.isSecure(), ctx.getAuthenticationScheme(), hasJWT); return helloReply; }
Example 11
Source File: TokenSecuredResourceV2.java From quarkus-quickstarts with Apache License 2.0 | 5 votes |
@GET() @Path("permit-all") @PermitAll @Produces(MediaType.TEXT_PLAIN) public String hello(@Context SecurityContext ctx) { Principal caller = ctx.getUserPrincipal(); String name = caller == null ? "anonymous" : caller.getName(); String helloReply = String.format("hello + %s, isSecure: %s, authScheme: %s", name, ctx.isSecure(), ctx.getAuthenticationScheme()); return helloReply; }
Example 12
Source File: ThreadLocalSecurityContext.java From tomee with Apache License 2.0 | 5 votes |
public Principal getUserPrincipal() { final Principal callerPrincipal = service().getCallerPrincipal(); if (callerPrincipal == null) { final SecurityContext securityContext = get(); if (securityContext != null) { return securityContext.getUserPrincipal(); } } // JAX-RS doesn't return a default Principal return callerPrincipal == null || callerPrincipal.getName().equals(defaultUser) ? null : callerPrincipal; }
Example 13
Source File: RolesEndpoint.java From microprofile-jwt-auth with Apache License 2.0 | 5 votes |
@GET @Path("/echo-permit-all") @PermitAll public String echoInputPermitAll(@Context SecurityContext sec, @QueryParam("input") String input) { Principal user = sec.getUserPrincipal(); return input + ", permitAll, user="+user.getName(); }
Example 14
Source File: UserResource.java From irontest with Apache License 2.0 | 5 votes |
/** * Return HTTP 200 if user is authenticated; return 401 otherwise. */ @GET @Path("authenticated") @PermitAll public User authenticated(@Context SecurityContext context) { SimplePrincipal principal = (SimplePrincipal) context.getUserPrincipal(); return userDAO.findByUsername(principal.getName()); }
Example 15
Source File: JwtResource.java From boost with Eclipse Public License 1.0 | 5 votes |
@GET @RolesAllowed({ "admin", "user" }) @Path("/groups") public Response getJwtGroups(@Context SecurityContext securityContext) { Set<String> groups = null; Principal user = securityContext.getUserPrincipal(); if (user instanceof JsonWebToken) { JsonWebToken jwt = (JsonWebToken) user; groups = jwt.getGroups(); } return Response.ok(groups.toString()).build(); }
Example 16
Source File: PerDayAuthorizer.java From resteasy-examples with Apache License 2.0 | 5 votes |
public void filter(ContainerRequestContext requestContext) throws IOException { SecurityContext sc = requestContext.getSecurityContext(); if (sc == null) throw new ForbiddenException(); Principal principal = sc.getUserPrincipal(); if (principal == null) throw new ForbiddenException(); String user = principal.getName(); if (!authorized(user)) { throw new ForbiddenException(); } }
Example 17
Source File: DynamicRegistrationService.java From cxf with Apache License 2.0 | 4 votes |
protected Client createNewClient(ClientRegistration request) { // Client ID String clientId = generateClientId(); // Client Name String clientName = request.getClientName(); if (StringUtils.isEmpty(clientName)) { clientName = clientId; } List<String> grantTypes = request.getGrantTypes(); if (grantTypes == null) { grantTypes = Collections.singletonList(OAuthConstants.AUTHORIZATION_CODE_GRANT); } String tokenEndpointAuthMethod = request.getTokenEndpointAuthMethod(); //TODO: default is expected to be set to OAuthConstants.TOKEN_ENDPOINT_AUTH_BASIC boolean passwordRequired = isPasswordRequired(grantTypes, tokenEndpointAuthMethod); // Application Type // https://tools.ietf.org/html/rfc7591 has no this property but // but http://openid.net/specs/openid-connect-registration-1_0.html#ClientMetadata does String appType = request.getApplicationType(); if (appType == null) { appType = DEFAULT_APPLICATION_TYPE; } boolean isConfidential = DEFAULT_APPLICATION_TYPE.equals(appType) && (passwordRequired || OAuthConstants.TOKEN_ENDPOINT_AUTH_TLS.equals(tokenEndpointAuthMethod)); // Client Secret String clientSecret = passwordRequired ? generateClientSecret(request) : null; Client newClient = new Client(clientId, clientSecret, isConfidential, clientName); newClient.setAllowedGrantTypes(grantTypes); newClient.setTokenEndpointAuthMethod(tokenEndpointAuthMethod); if (OAuthConstants.TOKEN_ENDPOINT_AUTH_TLS.equals(tokenEndpointAuthMethod)) { String subjectDn = (String)request.getProperty(OAuthConstants.TLS_CLIENT_AUTH_SUBJECT_DN); if (subjectDn != null) { newClient.getProperties().put(OAuthConstants.TLS_CLIENT_AUTH_SUBJECT_DN, subjectDn); } String issuerDn = (String)request.getProperty(OAuthConstants.TLS_CLIENT_AUTH_ISSUER_DN); if (issuerDn != null) { newClient.getProperties().put(OAuthConstants.TLS_CLIENT_AUTH_ISSUER_DN, issuerDn); } } // Client Registration Time newClient.setRegisteredAt(System.currentTimeMillis() / 1000L); fromClientRegistrationToClient(request, newClient); SecurityContext sc = mc.getSecurityContext(); if (sc != null && sc.getUserPrincipal() != null && sc.getUserPrincipal().getName() != null) { UserSubject subject = new UserSubject(sc.getUserPrincipal().getName()); newClient.setResourceOwnerSubject(subject); } newClient.setRegisteredDynamically(true); return newClient; }
Example 18
Source File: SampleResource.java From jrestless-examples with Apache License 2.0 | 4 votes |
@GET @Path("/public") public CustomAuthorizerPrincipalResponse getPublic(@Context SecurityContext securityContext) { // principal == null return new CustomAuthorizerPrincipalResponse((CustomAuthorizerPrincipal) securityContext.getUserPrincipal()); }
Example 19
Source File: ArticlesResource.java From realworld-api-quarkus with MIT License | 4 votes |
private Long getLoggedUserId(SecurityContext securityContext) { Principal principal = securityContext.getUserPrincipal(); return principal != null ? Long.valueOf(principal.getName()) : null; }
Example 20
Source File: SampleResource.java From jrestless-examples with Apache License 2.0 | 4 votes |
@GET @Path("/private") public CustomAuthorizerPrincipalResponse getPrivate(@Context SecurityContext securityContext) { return new CustomAuthorizerPrincipalResponse((CustomAuthorizerPrincipal) securityContext.getUserPrincipal()); }